diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index f8f71e0813..42191e57a9 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -143,6 +143,9 @@ cassandra: concurrent_limit: "${CASSANDRA_QUERY_CONCURRENT_LIMIT:1000}" permit_max_wait_time: "${PERMIT_MAX_WAIT_TIME:120000}" rate_limit_print_interval_ms: "${CASSANDRA_QUERY_RATE_LIMIT_PRINT_MS:10000}" + tenant_rate_limits: + enabled: "${CASSANDRA_QUERY_TENANT_RATE_LIMITS_ENABLED:false}" + configuration: "${CASSANDRA_QUERY_TENANT_RATE_LIMITS_VALUE:1000:1,30000:60}" # SQL configuration parameters sql: diff --git a/common/message/pom.xml b/common/message/pom.xml index d914d4f21d..228cd1cbbe 100644 --- a/common/message/pom.xml +++ b/common/message/pom.xml @@ -60,6 +60,10 @@ ch.qos.logback logback-classic + + com.github.vladimir-bukhtoyarov + bucket4j-core + com.google.protobuf protobuf-java diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/TbTransportRateLimits.java b/common/message/src/main/java/org/thingsboard/server/common/msg/tools/TbRateLimits.java similarity index 89% rename from common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/TbTransportRateLimits.java rename to common/message/src/main/java/org/thingsboard/server/common/msg/tools/TbRateLimits.java index d598734a5a..de6d1b8871 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/TbTransportRateLimits.java +++ b/common/message/src/main/java/org/thingsboard/server/common/msg/tools/TbRateLimits.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.common.transport.service; +package org.thingsboard.server.common.msg.tools; import io.github.bucket4j.Bandwidth; import io.github.bucket4j.Bucket4j; @@ -25,10 +25,10 @@ import java.time.Duration; /** * Created by ashvayka on 22.10.18. */ -class TbTransportRateLimits { +public class TbRateLimits { private final LocalBucket bucket; - public TbTransportRateLimits(String limitsConfiguration) { + public TbRateLimits(String limitsConfiguration) { LocalBucketBuilder builder = Bucket4j.builder(); boolean initialized = false; for (String limitSrc : limitsConfiguration.split(",")) { @@ -46,7 +46,7 @@ class TbTransportRateLimits { } - boolean tryConsume() { + public boolean tryConsume() { return bucket.tryConsume(1); } diff --git a/common/transport/transport-api/pom.xml b/common/transport/transport-api/pom.xml index 4ed6ed784d..3538e468d4 100644 --- a/common/transport/transport-api/pom.xml +++ b/common/transport/transport-api/pom.xml @@ -99,10 +99,6 @@ com.google.protobuf protobuf-java - - com.github.vladimir-bukhtoyarov - bucket4j-core - diff --git a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/AbstractTransportService.java b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/AbstractTransportService.java index 4af594c421..c9f681fd3f 100644 --- a/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/AbstractTransportService.java +++ b/common/transport/transport-api/src/main/java/org/thingsboard/server/common/transport/service/AbstractTransportService.java @@ -20,6 +20,7 @@ import org.springframework.beans.factory.annotation.Value; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.tools.TbRateLimits; import org.thingsboard.server.common.transport.SessionMsgListener; import org.thingsboard.server.common.transport.TransportService; import org.thingsboard.server.common.transport.TransportServiceCallback; @@ -58,8 +59,8 @@ public abstract class AbstractTransportService implements TransportService { private ConcurrentMap sessions = new ConcurrentHashMap<>(); //TODO: Implement cleanup of this maps. - private ConcurrentMap perTenantLimits = new ConcurrentHashMap<>(); - private ConcurrentMap perDeviceLimits = new ConcurrentHashMap<>(); + private ConcurrentMap perTenantLimits = new ConcurrentHashMap<>(); + private ConcurrentMap perDeviceLimits = new ConcurrentHashMap<>(); @Override public void registerAsyncSession(TransportProtos.SessionInfoProto sessionInfo, SessionMsgListener listener) { @@ -204,7 +205,7 @@ public abstract class AbstractTransportService implements TransportService { return true; } TenantId tenantId = new TenantId(new UUID(sessionInfo.getTenantIdMSB(), sessionInfo.getTenantIdLSB())); - TbTransportRateLimits rateLimits = perTenantLimits.computeIfAbsent(tenantId, id -> new TbTransportRateLimits(perTenantLimitsConf)); + TbRateLimits rateLimits = perTenantLimits.computeIfAbsent(tenantId, id -> new TbRateLimits(perTenantLimitsConf)); if (!rateLimits.tryConsume()) { if (callback != null) { callback.onError(new TbRateLimitsException(EntityType.TENANT)); @@ -215,7 +216,7 @@ public abstract class AbstractTransportService implements TransportService { return false; } DeviceId deviceId = new DeviceId(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB())); - rateLimits = perDeviceLimits.computeIfAbsent(deviceId, id -> new TbTransportRateLimits(perDevicesLimitsConf)); + rateLimits = perDeviceLimits.computeIfAbsent(deviceId, id -> new TbRateLimits(perDevicesLimitsConf)); if (!rateLimits.tryConsume()) { if (callback != null) { callback.onError(new TbRateLimitsException(EntityType.DEVICE)); @@ -271,8 +272,8 @@ public abstract class AbstractTransportService implements TransportService { public void init() { if (rateLimitEnabled) { //Just checking the configuration parameters - new TbTransportRateLimits(perTenantLimitsConf); - new TbTransportRateLimits(perDevicesLimitsConf); + new TbRateLimits(perTenantLimitsConf); + new TbRateLimits(perDevicesLimitsConf); } this.schedulerExecutor = Executors.newSingleThreadScheduledExecutor(); this.transportCallbackExecutor = new ThreadPoolExecutor(0, 20, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); diff --git a/dao/src/main/java/org/thingsboard/server/dao/Dao.java b/dao/src/main/java/org/thingsboard/server/dao/Dao.java index c82379043b..041131dc7f 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/Dao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/Dao.java @@ -16,20 +16,21 @@ package org.thingsboard.server.dao; import com.google.common.util.concurrent.ListenableFuture; +import org.thingsboard.server.common.data.id.TenantId; import java.util.List; import java.util.UUID; public interface Dao { - List find(); + List find(TenantId tenantId); - T findById(UUID id); + T findById(TenantId tenantId, UUID id); - ListenableFuture findByIdAsync(UUID id); + ListenableFuture findByIdAsync(TenantId tenantId, UUID id); - T save(T t); + T save(TenantId tenantId, T t); - boolean removeById(UUID id); + boolean removeById(TenantId tenantId, UUID id); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java b/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java index fd625eab3f..5d5456fb44 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java @@ -33,9 +33,9 @@ public interface AlarmDao extends Dao { ListenableFuture findLatestByOriginatorAndType(TenantId tenantId, EntityId originator, String type); - ListenableFuture findAlarmByIdAsync(UUID key); + ListenableFuture findAlarmByIdAsync(TenantId tenantId, UUID key); - Alarm save(Alarm alarm); + Alarm save(TenantId tenantId, Alarm alarm); - ListenableFuture> findAlarms(AlarmQuery query); + ListenableFuture> findAlarms(TenantId tenantId, AlarmQuery query); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java b/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java index 6638818207..aace8327e9 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java @@ -35,17 +35,17 @@ public interface AlarmService { Alarm createOrUpdateAlarm(Alarm alarm); - ListenableFuture ackAlarm(AlarmId alarmId, long ackTs); + ListenableFuture ackAlarm(TenantId tenantId, AlarmId alarmId, long ackTs); - ListenableFuture clearAlarm(AlarmId alarmId, JsonNode details, long ackTs); + ListenableFuture clearAlarm(TenantId tenantId, AlarmId alarmId, JsonNode details, long ackTs); - ListenableFuture findAlarmByIdAsync(AlarmId alarmId); + ListenableFuture findAlarmByIdAsync(TenantId tenantId, AlarmId alarmId); - ListenableFuture findAlarmInfoByIdAsync(AlarmId alarmId); + ListenableFuture findAlarmInfoByIdAsync(TenantId tenantId, AlarmId alarmId); - ListenableFuture> findAlarms(AlarmQuery query); + ListenableFuture> findAlarms(TenantId tenantId, AlarmQuery query); - AlarmSeverity findHighestAlarmSeverity(EntityId entityId, AlarmSearchStatus alarmSearchStatus, + AlarmSeverity findHighestAlarmSeverity(TenantId tenantId, EntityId entityId, AlarmSearchStatus alarmSearchStatus, AlarmStatus alarmStatus); ListenableFuture findLatestByOriginatorAndType(TenantId tenantId, EntityId originator, String type); diff --git a/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java b/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java index 23fe85a802..d0698b6986 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java @@ -91,7 +91,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ @Override public Alarm createOrUpdateAlarm(Alarm alarm) { - alarmDataValidator.validate(alarm); + alarmDataValidator.validate(alarm, Alarm::getTenantId); try { if (alarm.getStartTs() == 0L) { alarm.setStartTs(System.currentTimeMillis()); @@ -120,7 +120,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ private Alarm createAlarm(Alarm alarm) throws InterruptedException, ExecutionException { log.debug("New Alarm : {}", alarm); - Alarm saved = alarmDao.save(alarm); + Alarm saved = alarmDao.save(alarm.getTenantId(), alarm); createAlarmRelations(saved); return saved; } @@ -129,17 +129,17 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ if (alarm.isPropagate()) { EntityRelationsQuery query = new EntityRelationsQuery(); query.setParameters(new RelationsSearchParameters(alarm.getOriginator(), EntitySearchDirection.TO, Integer.MAX_VALUE)); - List parentEntities = relationService.findByQuery(query).get().stream().map(r -> r.getFrom()).collect(Collectors.toList()); + List parentEntities = relationService.findByQuery(alarm.getTenantId(), query).get().stream().map(EntityRelation::getFrom).collect(Collectors.toList()); for (EntityId parentId : parentEntities) { - createAlarmRelation(parentId, alarm.getId(), alarm.getStatus(), true); + createAlarmRelation(alarm.getTenantId(), parentId, alarm.getId(), alarm.getStatus(), true); } } - createAlarmRelation(alarm.getOriginator(), alarm.getId(), alarm.getStatus(), true); + createAlarmRelation(alarm.getTenantId(), alarm.getOriginator(), alarm.getId(), alarm.getStatus(), true); } private ListenableFuture updateAlarm(Alarm update) { - alarmDataValidator.validate(update); - return getAndUpdate(update.getId(), new Function() { + alarmDataValidator.validate(update, Alarm::getTenantId); + return getAndUpdate(update.getTenantId(), update.getId(), new Function() { @Nullable @Override public Alarm apply(@Nullable Alarm alarm) { @@ -157,7 +157,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ AlarmStatus newStatus = newAlarm.getStatus(); boolean oldPropagate = oldAlarm.isPropagate(); boolean newPropagate = newAlarm.isPropagate(); - Alarm result = alarmDao.save(merge(oldAlarm, newAlarm)); + Alarm result = alarmDao.save(newAlarm.getTenantId(), merge(oldAlarm, newAlarm)); if (!oldPropagate && newPropagate) { try { createAlarmRelations(result); @@ -172,8 +172,8 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ } @Override - public ListenableFuture ackAlarm(AlarmId alarmId, long ackTime) { - return getAndUpdate(alarmId, new Function() { + public ListenableFuture ackAlarm(TenantId tenantId, AlarmId alarmId, long ackTime) { + return getAndUpdate(tenantId, alarmId, new Function() { @Nullable @Override public Boolean apply(@Nullable Alarm alarm) { @@ -184,7 +184,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ AlarmStatus newStatus = oldStatus.isCleared() ? AlarmStatus.CLEARED_ACK : AlarmStatus.ACTIVE_ACK; alarm.setStatus(newStatus); alarm.setAckTs(ackTime); - alarmDao.save(alarm); + alarmDao.save(alarm.getTenantId(), alarm); updateRelations(alarm, oldStatus, newStatus); return true; } @@ -193,8 +193,8 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ } @Override - public ListenableFuture clearAlarm(AlarmId alarmId, JsonNode details, long clearTime) { - return getAndUpdate(alarmId, new Function() { + public ListenableFuture clearAlarm(TenantId tenantId, AlarmId alarmId, JsonNode details, long clearTime) { + return getAndUpdate(tenantId, alarmId, new Function() { @Nullable @Override public Boolean apply(@Nullable Alarm alarm) { @@ -208,7 +208,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ if (details != null) { alarm.setDetails(details); } - alarmDao.save(alarm); + alarmDao.save(alarm.getTenantId(), alarm); updateRelations(alarm, oldStatus, newStatus); return true; } @@ -217,21 +217,21 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ } @Override - public ListenableFuture findAlarmByIdAsync(AlarmId alarmId) { + public ListenableFuture findAlarmByIdAsync(TenantId tenantId, AlarmId alarmId) { log.trace("Executing findAlarmById [{}]", alarmId); validateId(alarmId, "Incorrect alarmId " + alarmId); - return alarmDao.findAlarmByIdAsync(alarmId.getId()); + return alarmDao.findAlarmByIdAsync(tenantId, alarmId.getId()); } @Override - public ListenableFuture findAlarmInfoByIdAsync(AlarmId alarmId) { + public ListenableFuture findAlarmInfoByIdAsync(TenantId tenantId, AlarmId alarmId) { log.trace("Executing findAlarmInfoByIdAsync [{}]", alarmId); validateId(alarmId, "Incorrect alarmId " + alarmId); - return Futures.transformAsync(alarmDao.findAlarmByIdAsync(alarmId.getId()), + return Futures.transformAsync(alarmDao.findAlarmByIdAsync(tenantId, alarmId.getId()), a -> { AlarmInfo alarmInfo = new AlarmInfo(a); return Futures.transform( - entityService.fetchEntityNameAsync(alarmInfo.getOriginator()), originatorName -> { + entityService.fetchEntityNameAsync(tenantId, alarmInfo.getOriginator()), originatorName -> { alarmInfo.setOriginatorName(originatorName); return alarmInfo; } @@ -240,14 +240,14 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ } @Override - public ListenableFuture> findAlarms(AlarmQuery query) { - ListenableFuture> alarms = alarmDao.findAlarms(query); + public ListenableFuture> findAlarms(TenantId tenantId, AlarmQuery query) { + ListenableFuture> alarms = alarmDao.findAlarms(tenantId, query); if (query.getFetchOriginator() != null && query.getFetchOriginator().booleanValue()) { alarms = Futures.transformAsync(alarms, input -> { List> alarmFutures = new ArrayList<>(input.size()); for (AlarmInfo alarmInfo : input) { alarmFutures.add(Futures.transform( - entityService.fetchEntityNameAsync(alarmInfo.getOriginator()), originatorName -> { + entityService.fetchEntityNameAsync(tenantId, alarmInfo.getOriginator()), originatorName -> { if (originatorName == null) { originatorName = "Deleted"; } @@ -269,7 +269,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ } @Override - public AlarmSeverity findHighestAlarmSeverity(EntityId entityId, AlarmSearchStatus alarmSearchStatus, + public AlarmSeverity findHighestAlarmSeverity(TenantId tenantId, EntityId entityId, AlarmSearchStatus alarmSearchStatus, AlarmStatus alarmStatus) { TimePageLink nextPageLink = new TimePageLink(100); boolean hasNext = true; @@ -279,7 +279,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ query = new AlarmQuery(entityId, nextPageLink, alarmSearchStatus, alarmStatus, false); List alarms; try { - alarms = alarmDao.findAlarms(query).get(); + alarms = alarmDao.findAlarms(tenantId, query).get(); } catch (ExecutionException | InterruptedException e) { log.warn("Failed to find highest alarm severity. EntityId: [{}], AlarmSearchStatus: [{}], AlarmStatus: [{}]", entityId, alarmSearchStatus, alarmStatus); @@ -312,14 +312,14 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ } } - private void deleteRelation(EntityRelation alarmRelation) throws ExecutionException, InterruptedException { + private void deleteRelation(TenantId tenantId, EntityRelation alarmRelation) throws ExecutionException, InterruptedException { log.debug("Deleting Alarm relation: {}", alarmRelation); - relationService.deleteRelationAsync(alarmRelation).get(); + relationService.deleteRelationAsync(tenantId, alarmRelation).get(); } - private void createRelation(EntityRelation alarmRelation) throws ExecutionException, InterruptedException { + private void createRelation(TenantId tenantId, EntityRelation alarmRelation) throws ExecutionException, InterruptedException { log.debug("Creating Alarm relation: {}", alarmRelation); - relationService.saveRelationAsync(alarmRelation).get(); + relationService.saveRelationAsync(tenantId, alarmRelation).get(); } private Alarm merge(Alarm existing, Alarm alarm) { @@ -344,10 +344,10 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ private void updateRelations(Alarm alarm, AlarmStatus oldStatus, AlarmStatus newStatus) { try { - List relations = relationService.findByToAsync(alarm.getId(), RelationTypeGroup.ALARM).get(); + List relations = relationService.findByToAsync(alarm.getTenantId(), alarm.getId(), RelationTypeGroup.ALARM).get(); Set parents = relations.stream().map(EntityRelation::getFrom).collect(Collectors.toSet()); for (EntityId parentId : parents) { - updateAlarmRelation(parentId, alarm.getId(), oldStatus, newStatus); + updateAlarmRelation(alarm.getTenantId(), parentId, alarm.getId(), oldStatus, newStatus); } } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to update relations. Old status: [{}], New status: [{}]", alarm.getId(), oldStatus, newStatus); @@ -355,39 +355,39 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ } } - private void createAlarmRelation(EntityId entityId, EntityId alarmId, AlarmStatus status, boolean createAnyRelation) { + private void createAlarmRelation(TenantId tenantId, EntityId entityId, EntityId alarmId, AlarmStatus status, boolean createAnyRelation) { try { if (createAnyRelation) { - createRelation(new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + AlarmSearchStatus.ANY.name(), RelationTypeGroup.ALARM)); + createRelation(tenantId, new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + AlarmSearchStatus.ANY.name(), RelationTypeGroup.ALARM)); } - createRelation(new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.name(), RelationTypeGroup.ALARM)); - createRelation(new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.getClearSearchStatus().name(), RelationTypeGroup.ALARM)); - createRelation(new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.getAckSearchStatus().name(), RelationTypeGroup.ALARM)); + createRelation(tenantId, new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.name(), RelationTypeGroup.ALARM)); + createRelation(tenantId, new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.getClearSearchStatus().name(), RelationTypeGroup.ALARM)); + createRelation(tenantId, new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.getAckSearchStatus().name(), RelationTypeGroup.ALARM)); } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to create relation. Status: [{}]", alarmId, status); throw new RuntimeException(e); } } - private void deleteAlarmRelation(EntityId entityId, EntityId alarmId, AlarmStatus status) { + private void deleteAlarmRelation(TenantId tenantId, EntityId entityId, EntityId alarmId, AlarmStatus status) { try { - deleteRelation(new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.name(), RelationTypeGroup.ALARM)); - deleteRelation(new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.getClearSearchStatus().name(), RelationTypeGroup.ALARM)); - deleteRelation(new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.getAckSearchStatus().name(), RelationTypeGroup.ALARM)); + deleteRelation(tenantId, new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.name(), RelationTypeGroup.ALARM)); + deleteRelation(tenantId, new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.getClearSearchStatus().name(), RelationTypeGroup.ALARM)); + deleteRelation(tenantId, new EntityRelation(entityId, alarmId, ALARM_RELATION_PREFIX + status.getAckSearchStatus().name(), RelationTypeGroup.ALARM)); } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to delete relation. Status: [{}]", alarmId, status); throw new RuntimeException(e); } } - private void updateAlarmRelation(EntityId entityId, EntityId alarmId, AlarmStatus oldStatus, AlarmStatus newStatus) { - deleteAlarmRelation(entityId, alarmId, oldStatus); - createAlarmRelation(entityId, alarmId, newStatus, false); + private void updateAlarmRelation(TenantId tenantId, EntityId entityId, EntityId alarmId, AlarmStatus oldStatus, AlarmStatus newStatus) { + deleteAlarmRelation(tenantId, entityId, alarmId, oldStatus); + createAlarmRelation(tenantId, entityId, alarmId, newStatus, false); } - private ListenableFuture getAndUpdate(AlarmId alarmId, Function function) { + private ListenableFuture getAndUpdate(TenantId tenantId, AlarmId alarmId, Function function) { validateId(alarmId, "Alarm id should be specified!"); - ListenableFuture entity = alarmDao.findAlarmByIdAsync(alarmId.getId()); + ListenableFuture entity = alarmDao.findAlarmByIdAsync(tenantId, alarmId.getId()); return Futures.transform(entity, function, readResultsProcessingExecutor); } @@ -395,7 +395,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ new DataValidator() { @Override - protected void validateDataImpl(Alarm alarm) { + protected void validateDataImpl(TenantId tenantId, Alarm alarm) { if (StringUtils.isEmpty(alarm.getType())) { throw new DataValidationException("Alarm type should be specified!"); } @@ -411,7 +411,7 @@ public class BaseAlarmService extends AbstractEntityService implements AlarmServ if (alarm.getTenantId() == null) { throw new DataValidationException("Alarm should be assigned to tenant!"); } else { - Tenant tenant = tenantDao.findById(alarm.getTenantId().getId()); + Tenant tenant = tenantDao.findById(alarm.getTenantId(), alarm.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("Alarm is referencing to non-existent tenant!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/alarm/CassandraAlarmDao.java b/dao/src/main/java/org/thingsboard/server/dao/alarm/CassandraAlarmDao.java index 646c0556ae..ed8666fa81 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/alarm/CassandraAlarmDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/alarm/CassandraAlarmDao.java @@ -73,9 +73,9 @@ public class CassandraAlarmDao extends CassandraAbstractModelDao> findAlarms(AlarmQuery query) { + public ListenableFuture> findAlarms(TenantId tenantId, AlarmQuery query) { log.trace("Try to find alarms by entity [{}], searchStatus [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(), query.getSearchStatus(), query.getStatus(), query.getPageLink()); EntityId affectedEntity = query.getAffectedEntityId(); String searchStatusName; @@ -104,12 +104,12 @@ public class CassandraAlarmDao extends CassandraAbstractModelDao> relations = relationDao.findRelations(affectedEntity, relationType, RelationTypeGroup.ALARM, EntityType.ALARM, query.getPageLink()); + ListenableFuture> relations = relationDao.findRelations(tenantId, affectedEntity, relationType, RelationTypeGroup.ALARM, EntityType.ALARM, query.getPageLink()); return Futures.transformAsync(relations, input -> { List> alarmFutures = new ArrayList<>(input.size()); for (EntityRelation relation : input) { alarmFutures.add(Futures.transform( - findAlarmByIdAsync(relation.getTo().getId()), + findAlarmByIdAsync(tenantId, relation.getTo().getId()), AlarmInfo::new)); } return Futures.successfulAsList(alarmFutures); @@ -117,11 +117,11 @@ public class CassandraAlarmDao extends CassandraAbstractModelDao findAlarmByIdAsync(UUID key) { + public ListenableFuture findAlarmByIdAsync(TenantId tenantId, UUID key) { log.debug("Get alarm by id {}", key); Select.Where query = select().from(ALARM_BY_ID_VIEW_NAME).where(eq(ModelConstants.ID_PROPERTY, key)); query.limit(1); log.trace("Execute query {}", query); - return findOneByStatementAsync(query); + return findOneByStatementAsync(tenantId, query); } } diff --git a/dao/src/main/java/org/thingsboard/server/dao/asset/AssetDao.java b/dao/src/main/java/org/thingsboard/server/dao/asset/AssetDao.java index 3aa23d1504..be989d5c66 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/asset/AssetDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/asset/AssetDao.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.asset; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.EntitySubtype; import org.thingsboard.server.common.data.asset.Asset; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.Dao; @@ -37,7 +38,7 @@ public interface AssetDao extends Dao { * @param asset the asset object * @return saved asset object */ - Asset save(Asset asset); + Asset save(TenantId tenantId, Asset asset); /** * Find assets by tenantId and page link. diff --git a/dao/src/main/java/org/thingsboard/server/dao/asset/AssetService.java b/dao/src/main/java/org/thingsboard/server/dao/asset/AssetService.java index e373f0e27a..3ecbbd2d8d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/asset/AssetService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/asset/AssetService.java @@ -30,19 +30,19 @@ import java.util.Optional; public interface AssetService { - Asset findAssetById(AssetId assetId); + Asset findAssetById(TenantId tenantId, AssetId assetId); - ListenableFuture findAssetByIdAsync(AssetId assetId); + ListenableFuture findAssetByIdAsync(TenantId tenantId, AssetId assetId); Asset findAssetByTenantIdAndName(TenantId tenantId, String name); Asset saveAsset(Asset asset); - Asset assignAssetToCustomer(AssetId assetId, CustomerId customerId); + Asset assignAssetToCustomer(TenantId tenantId, AssetId assetId, CustomerId customerId); - Asset unassignAssetFromCustomer(AssetId assetId); + Asset unassignAssetFromCustomer(TenantId tenantId, AssetId assetId); - void deleteAsset(AssetId assetId); + void deleteAsset(TenantId tenantId, AssetId assetId); TextPageData findAssetsByTenantId(TenantId tenantId, TextPageLink pageLink); @@ -60,7 +60,7 @@ public interface AssetService { void unassignCustomerAssets(TenantId tenantId, CustomerId customerId); - ListenableFuture> findAssetsByQuery(AssetSearchQuery query); + ListenableFuture> findAssetsByQuery(TenantId tenantId, AssetSearchQuery query); ListenableFuture> findAssetTypesByTenantId(TenantId tenantId); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/asset/BaseAssetService.java b/dao/src/main/java/org/thingsboard/server/dao/asset/BaseAssetService.java index ebd056048b..0fca8c5de6 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/asset/BaseAssetService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/asset/BaseAssetService.java @@ -86,17 +86,17 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ private CacheManager cacheManager; @Override - public Asset findAssetById(AssetId assetId) { + public Asset findAssetById(TenantId tenantId, AssetId assetId) { log.trace("Executing findAssetById [{}]", assetId); validateId(assetId, INCORRECT_ASSET_ID + assetId); - return assetDao.findById(assetId.getId()); + return assetDao.findById(tenantId, assetId.getId()); } @Override - public ListenableFuture findAssetByIdAsync(AssetId assetId) { + public ListenableFuture findAssetByIdAsync(TenantId tenantId, AssetId assetId) { log.trace("Executing findAssetById [{}]", assetId); validateId(assetId, INCORRECT_ASSET_ID + assetId); - return assetDao.findByIdAsync(assetId.getId()); + return assetDao.findByIdAsync(tenantId, assetId.getId()); } @Cacheable(cacheNames = ASSET_CACHE, key = "{#tenantId, #name}") @@ -112,31 +112,31 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ @Override public Asset saveAsset(Asset asset) { log.trace("Executing saveAsset [{}]", asset); - assetValidator.validate(asset); - return assetDao.save(asset); + assetValidator.validate(asset, Asset::getTenantId); + return assetDao.save(asset.getTenantId(), asset); } @Override - public Asset assignAssetToCustomer(AssetId assetId, CustomerId customerId) { - Asset asset = findAssetById(assetId); + public Asset assignAssetToCustomer(TenantId tenantId, AssetId assetId, CustomerId customerId) { + Asset asset = findAssetById(tenantId, assetId); asset.setCustomerId(customerId); return saveAsset(asset); } @Override - public Asset unassignAssetFromCustomer(AssetId assetId) { - Asset asset = findAssetById(assetId); + public Asset unassignAssetFromCustomer(TenantId tenantId, AssetId assetId) { + Asset asset = findAssetById(tenantId, assetId); asset.setCustomerId(null); return saveAsset(asset); } @Override - public void deleteAsset(AssetId assetId) { + public void deleteAsset(TenantId tenantId, AssetId assetId) { log.trace("Executing deleteAsset [{}]", assetId); validateId(assetId, INCORRECT_ASSET_ID + assetId); - deleteEntityRelations(assetId); + deleteEntityRelations(tenantId, assetId); - Asset asset = assetDao.findById(assetId.getId()); + Asset asset = assetDao.findById(tenantId, assetId.getId()); try { List entityViews = entityViewService.findEntityViewsByTenantIdAndEntityIdAsync(asset.getTenantId(), assetId).get(); if (entityViews != null && !entityViews.isEmpty()) { @@ -153,7 +153,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ Cache cache = cacheManager.getCache(ASSET_CACHE); cache.evict(list); - assetDao.removeById(assetId.getId()); + assetDao.removeById(tenantId, assetId.getId()); } @Override @@ -187,7 +187,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ public void deleteAssetsByTenantId(TenantId tenantId) { log.trace("Executing deleteAssetsByTenantId, tenantId [{}]", tenantId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); - tenantAssetsRemover.removeEntities(tenantId); + tenantAssetsRemover.removeEntities(tenantId, tenantId); } @Override @@ -225,24 +225,24 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ log.trace("Executing unassignCustomerAssets, tenantId [{}], customerId [{}]", tenantId, customerId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); validateId(customerId, INCORRECT_CUSTOMER_ID + customerId); - new CustomerAssetsUnassigner(tenantId).removeEntities(customerId); + customerAssetsUnasigner.removeEntities(tenantId, customerId); } @Override - public ListenableFuture> findAssetsByQuery(AssetSearchQuery query) { - ListenableFuture> relations = relationService.findByQuery(query.toEntitySearchQuery()); + public ListenableFuture> findAssetsByQuery(TenantId tenantId, AssetSearchQuery query) { + ListenableFuture> relations = relationService.findByQuery(tenantId, query.toEntitySearchQuery()); ListenableFuture> assets = Futures.transformAsync(relations, r -> { EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection(); List> futures = new ArrayList<>(); for (EntityRelation relation : r) { EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom(); if (entityId.getEntityType() == EntityType.ASSET) { - futures.add(findAssetByIdAsync(new AssetId(entityId.getId()))); + futures.add(findAssetByIdAsync(tenantId, new AssetId(entityId.getId()))); } } return Futures.successfulAsList(futures); }); - assets = Futures.transform(assets, (Function, List>)assetList -> + assets = Futures.transform(assets, assetList -> assetList == null ? Collections.emptyList() : assetList.stream().filter(asset -> query.getAssetTypes().contains(asset.getType())).collect(Collectors.toList()) ); return assets; @@ -254,7 +254,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ validateId(tenantId, INCORRECT_TENANT_ID + tenantId); ListenableFuture> tenantAssetTypes = assetDao.findTenantAssetTypesAsync(tenantId.getId()); return Futures.transform(tenantAssetTypes, - (Function, List>) assetTypes -> { + assetTypes -> { assetTypes.sort(Comparator.comparing(EntitySubtype::getType)); return assetTypes; }); @@ -264,7 +264,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ new DataValidator() { @Override - protected void validateCreate(Asset asset) { + protected void validateCreate(TenantId tenantId, Asset asset) { assetDao.findAssetsByTenantIdAndName(asset.getTenantId().getId(), asset.getName()).ifPresent( d -> { throw new DataValidationException("Asset with such name already exists!"); @@ -273,7 +273,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ } @Override - protected void validateUpdate(Asset asset) { + protected void validateUpdate(TenantId tenantId, Asset asset) { assetDao.findAssetsByTenantIdAndName(asset.getTenantId().getId(), asset.getName()).ifPresent( d -> { if (!d.getId().equals(asset.getId())) { @@ -284,7 +284,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ } @Override - protected void validateDataImpl(Asset asset) { + protected void validateDataImpl(TenantId tenantId, Asset asset) { if (StringUtils.isEmpty(asset.getType())) { throw new DataValidationException("Asset type should be specified!"); } @@ -294,7 +294,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ if (asset.getTenantId() == null) { throw new DataValidationException("Asset should be assigned to tenant!"); } else { - Tenant tenant = tenantDao.findById(asset.getTenantId().getId()); + Tenant tenant = tenantDao.findById(tenantId, asset.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("Asset is referencing to non-existent tenant!"); } @@ -302,7 +302,7 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ if (asset.getCustomerId() == null) { asset.setCustomerId(new CustomerId(NULL_UUID)); } else if (!asset.getCustomerId().getId().equals(NULL_UUID)) { - Customer customer = customerDao.findById(asset.getCustomerId().getId()); + Customer customer = customerDao.findById(tenantId, asset.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("Can't assign asset to non-existent customer!"); } @@ -314,35 +314,29 @@ public class BaseAssetService extends AbstractEntityService implements AssetServ }; private PaginatedRemover tenantAssetsRemover = - new PaginatedRemover() { + new PaginatedRemover() { - @Override - protected List findEntities(TenantId id, TextPageLink pageLink) { - return assetDao.findAssetsByTenantId(id.getId(), pageLink); - } - - @Override - protected void removeEntity(Asset entity) { - deleteAsset(new AssetId(entity.getId().getId())); - } - }; + @Override + protected List findEntities(TenantId tenantId, TenantId id, TextPageLink pageLink) { + return assetDao.findAssetsByTenantId(id.getId(), pageLink); + } - class CustomerAssetsUnassigner extends PaginatedRemover { + @Override + protected void removeEntity(TenantId tenantId, Asset entity) { + deleteAsset(tenantId, new AssetId(entity.getId().getId())); + } + }; - private TenantId tenantId; - - CustomerAssetsUnassigner(TenantId tenantId) { - this.tenantId = tenantId; - } + private PaginatedRemover customerAssetsUnasigner = new PaginatedRemover() { @Override - protected List findEntities(CustomerId id, TextPageLink pageLink) { + protected List findEntities(TenantId tenantId, CustomerId id, TextPageLink pageLink) { return assetDao.findAssetsByTenantIdAndCustomerId(tenantId.getId(), id.getId(), pageLink); } @Override - protected void removeEntity(Asset entity) { - unassignAssetFromCustomer(new AssetId(entity.getId().getId())); + protected void removeEntity(TenantId tenantId, Asset entity) { + unassignAssetFromCustomer(tenantId, new AssetId(entity.getId().getId())); } - } + }; } diff --git a/dao/src/main/java/org/thingsboard/server/dao/asset/CassandraAssetDao.java b/dao/src/main/java/org/thingsboard/server/dao/asset/CassandraAssetDao.java index 80a6f43f75..48c8950c94 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/asset/CassandraAssetDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/asset/CassandraAssetDao.java @@ -28,6 +28,7 @@ import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.EntitySubtype; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.asset.Asset; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.EntitySubtypeEntity; @@ -77,19 +78,19 @@ public class CassandraAssetDao extends CassandraAbstractSearchTextDao findAssetsByTenantId(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find assets by tenantId [{}] and pageLink [{}]", tenantId, pageLink); - List assetEntities = findPageWithTextSearch(ASSET_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List assetEntities = findPageWithTextSearch(new TenantId(tenantId), ASSET_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Collections.singletonList(eq(ASSET_TENANT_ID_PROPERTY, tenantId)), pageLink); log.trace("Found assets [{}] by tenantId [{}] and pageLink [{}]", assetEntities, tenantId, pageLink); @@ -99,7 +100,7 @@ public class CassandraAssetDao extends CassandraAbstractSearchTextDao findAssetsByTenantIdAndType(UUID tenantId, String type, TextPageLink pageLink) { log.debug("Try to find assets by tenantId [{}], type [{}] and pageLink [{}]", tenantId, type, pageLink); - List assetEntities = findPageWithTextSearch(ASSET_BY_TENANT_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List assetEntities = findPageWithTextSearch(new TenantId(tenantId), ASSET_BY_TENANT_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(ASSET_TYPE_PROPERTY, type), eq(ASSET_TENANT_ID_PROPERTY, tenantId)), pageLink); log.trace("Found assets [{}] by tenantId [{}], type [{}] and pageLink [{}]", assetEntities, tenantId, type, pageLink); @@ -112,13 +113,13 @@ public class CassandraAssetDao extends CassandraAbstractSearchTextDao findAssetsByTenantIdAndCustomerId(UUID tenantId, UUID customerId, TextPageLink pageLink) { log.debug("Try to find assets by tenantId [{}], customerId[{}] and pageLink [{}]", tenantId, customerId, pageLink); - List assetEntities = findPageWithTextSearch(ASSET_BY_CUSTOMER_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List assetEntities = findPageWithTextSearch(new TenantId(tenantId), ASSET_BY_CUSTOMER_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(ASSET_CUSTOMER_ID_PROPERTY, customerId), eq(ASSET_TENANT_ID_PROPERTY, tenantId)), pageLink); @@ -130,7 +131,7 @@ public class CassandraAssetDao extends CassandraAbstractSearchTextDao findAssetsByTenantIdAndCustomerIdAndType(UUID tenantId, UUID customerId, String type, TextPageLink pageLink) { log.debug("Try to find assets by tenantId [{}], customerId [{}], type [{}] and pageLink [{}]", tenantId, customerId, type, pageLink); - List assetEntities = findPageWithTextSearch(ASSET_BY_CUSTOMER_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List assetEntities = findPageWithTextSearch(new TenantId(tenantId), ASSET_BY_CUSTOMER_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(ASSET_TYPE_PROPERTY, type), eq(ASSET_CUSTOMER_ID_PROPERTY, customerId), eq(ASSET_TENANT_ID_PROPERTY, tenantId)), @@ -148,7 +149,7 @@ public class CassandraAssetDao extends CassandraAbstractSearchTextDao>() { @Nullable @Override diff --git a/dao/src/main/java/org/thingsboard/server/dao/attributes/AttributesDao.java b/dao/src/main/java/org/thingsboard/server/dao/attributes/AttributesDao.java index c9510d276a..a6651648f0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/attributes/AttributesDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/attributes/AttributesDao.java @@ -17,6 +17,7 @@ package org.thingsboard.server.dao.attributes; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import java.util.Collection; @@ -28,13 +29,13 @@ import java.util.Optional; */ public interface AttributesDao { - ListenableFuture> find(EntityId entityId, String attributeType, String attributeKey); + ListenableFuture> find(TenantId tenantId, EntityId entityId, String attributeType, String attributeKey); - ListenableFuture> find(EntityId entityId, String attributeType, Collection attributeKey); + ListenableFuture> find(TenantId tenantId, EntityId entityId, String attributeType, Collection attributeKey); - ListenableFuture> findAll(EntityId entityId, String attributeType); + ListenableFuture> findAll(TenantId tenantId, EntityId entityId, String attributeType); - ListenableFuture save(EntityId entityId, String attributeType, AttributeKvEntry attribute); + ListenableFuture save(TenantId tenantId, EntityId entityId, String attributeType, AttributeKvEntry attribute); - ListenableFuture> removeAll(EntityId entityId, String attributeType, List keys); + ListenableFuture> removeAll(TenantId tenantId, EntityId entityId, String attributeType, List keys); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/attributes/AttributesService.java b/dao/src/main/java/org/thingsboard/server/dao/attributes/AttributesService.java index fa3a2b16f8..7c6b2e748b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/attributes/AttributesService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/attributes/AttributesService.java @@ -17,6 +17,7 @@ package org.thingsboard.server.dao.attributes; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import java.util.Collection; @@ -28,13 +29,13 @@ import java.util.Optional; */ public interface AttributesService { - ListenableFuture> find(EntityId entityId, String scope, String attributeKey); + ListenableFuture> find(TenantId tenantId, EntityId entityId, String scope, String attributeKey); - ListenableFuture> find(EntityId entityId, String scope, Collection attributeKeys); + ListenableFuture> find(TenantId tenantId, EntityId entityId, String scope, Collection attributeKeys); - ListenableFuture> findAll(EntityId entityId, String scope); + ListenableFuture> findAll(TenantId tenantId, EntityId entityId, String scope); - ListenableFuture> save(EntityId entityId, String scope, List attributes); + ListenableFuture> save(TenantId tenantId, EntityId entityId, String scope, List attributes); - ListenableFuture> removeAll(EntityId entityId, String scope, List attributeKeys); + ListenableFuture> removeAll(TenantId tenantId, EntityId entityId, String scope, List attributeKeys); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/attributes/BaseAttributesService.java b/dao/src/main/java/org/thingsboard/server/dao/attributes/BaseAttributesService.java index 079772bd50..29394bb770 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/attributes/BaseAttributesService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/attributes/BaseAttributesService.java @@ -21,6 +21,7 @@ import com.google.common.util.concurrent.ListenableFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.dao.exception.IncorrectParameterException; import org.thingsboard.server.dao.service.Validator; @@ -39,40 +40,40 @@ public class BaseAttributesService implements AttributesService { private AttributesDao attributesDao; @Override - public ListenableFuture> find(EntityId entityId, String scope, String attributeKey) { + public ListenableFuture> find(TenantId tenantId, EntityId entityId, String scope, String attributeKey) { validate(entityId, scope); Validator.validateString(attributeKey, "Incorrect attribute key " + attributeKey); - return attributesDao.find(entityId, scope, attributeKey); + return attributesDao.find(tenantId, entityId, scope, attributeKey); } @Override - public ListenableFuture> find(EntityId entityId, String scope, Collection attributeKeys) { + public ListenableFuture> find(TenantId tenantId, EntityId entityId, String scope, Collection attributeKeys) { validate(entityId, scope); attributeKeys.forEach(attributeKey -> Validator.validateString(attributeKey, "Incorrect attribute key " + attributeKey)); - return attributesDao.find(entityId, scope, attributeKeys); + return attributesDao.find(tenantId, entityId, scope, attributeKeys); } @Override - public ListenableFuture> findAll(EntityId entityId, String scope) { + public ListenableFuture> findAll(TenantId tenantId, EntityId entityId, String scope) { validate(entityId, scope); - return attributesDao.findAll(entityId, scope); + return attributesDao.findAll(tenantId, entityId, scope); } @Override - public ListenableFuture> save(EntityId entityId, String scope, List attributes) { + public ListenableFuture> save(TenantId tenantId, EntityId entityId, String scope, List attributes) { validate(entityId, scope); attributes.forEach(attribute -> validate(attribute)); List> futures = Lists.newArrayListWithExpectedSize(attributes.size()); for (AttributeKvEntry attribute : attributes) { - futures.add(attributesDao.save(entityId, scope, attribute)); + futures.add(attributesDao.save(tenantId, entityId, scope, attribute)); } return Futures.allAsList(futures); } @Override - public ListenableFuture> removeAll(EntityId entityId, String scope, List keys) { + public ListenableFuture> removeAll(TenantId tenantId, EntityId entityId, String scope, List keys) { validate(entityId, scope); - return attributesDao.removeAll(entityId, scope, keys); + return attributesDao.removeAll(tenantId, entityId, scope, keys); } private static void validate(EntityId id, String scope) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/attributes/CassandraBaseAttributesDao.java b/dao/src/main/java/org/thingsboard/server/dao/attributes/CassandraBaseAttributesDao.java index a736a69c5e..3674f3d64e 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/attributes/CassandraBaseAttributesDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/attributes/CassandraBaseAttributesDao.java @@ -28,6 +28,7 @@ import com.google.common.util.concurrent.ListenableFuture; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; import org.thingsboard.server.dao.model.ModelConstants; @@ -73,22 +74,22 @@ public class CassandraBaseAttributesDao extends CassandraAbstractAsyncDao implem } @Override - public ListenableFuture> find(EntityId entityId, String attributeType, String attributeKey) { + public ListenableFuture> find(TenantId tenantId, EntityId entityId, String attributeType, String attributeKey) { Select.Where select = select().from(ATTRIBUTES_KV_CF) .where(eq(ENTITY_TYPE_COLUMN, entityId.getEntityType())) .and(eq(ENTITY_ID_COLUMN, entityId.getId())) .and(eq(ATTRIBUTE_TYPE_COLUMN, attributeType)) .and(eq(ATTRIBUTE_KEY_COLUMN, attributeKey)); log.trace("Generated query [{}] for entityId {} and key {}", select, entityId, attributeKey); - return Futures.transform(executeAsyncRead(select), (Function>) input -> + return Futures.transform(executeAsyncRead(tenantId, select), (Function>) input -> Optional.ofNullable(convertResultToAttributesKvEntry(attributeKey, input.one())) , readResultsProcessingExecutor); } @Override - public ListenableFuture> find(EntityId entityId, String attributeType, Collection attributeKeys) { + public ListenableFuture> find(TenantId tenantId, EntityId entityId, String attributeType, Collection attributeKeys) { List>> entries = new ArrayList<>(); - attributeKeys.forEach(attributeKey -> entries.add(find(entityId, attributeType, attributeKey))); + attributeKeys.forEach(attributeKey -> entries.add(find(tenantId, entityId, attributeType, attributeKey))); return Futures.transform(Futures.allAsList(entries), (Function>, ? extends List>) input -> { List result = new ArrayList<>(); input.stream().filter(opt -> opt.isPresent()).forEach(opt -> result.add(opt.get())); @@ -98,19 +99,19 @@ public class CassandraBaseAttributesDao extends CassandraAbstractAsyncDao implem @Override - public ListenableFuture> findAll(EntityId entityId, String attributeType) { + public ListenableFuture> findAll(TenantId tenantId, EntityId entityId, String attributeType) { Select.Where select = select().from(ATTRIBUTES_KV_CF) .where(eq(ENTITY_TYPE_COLUMN, entityId.getEntityType())) .and(eq(ENTITY_ID_COLUMN, entityId.getId())) .and(eq(ATTRIBUTE_TYPE_COLUMN, attributeType)); log.trace("Generated query [{}] for entityId {} and attributeType {}", select, entityId, attributeType); - return Futures.transform(executeAsyncRead(select), (Function>) input -> + return Futures.transform(executeAsyncRead(tenantId, select), (Function>) input -> convertResultToAttributesKvEntryList(input) , readResultsProcessingExecutor); } @Override - public ListenableFuture save(EntityId entityId, String attributeType, AttributeKvEntry attribute) { + public ListenableFuture save(TenantId tenantId, EntityId entityId, String attributeType, AttributeKvEntry attribute) { BoundStatement stmt = getSaveStmt().bind(); stmt.setString(0, entityId.getEntityType().name()); stmt.setUUID(1, entityId.getId()); @@ -137,26 +138,26 @@ public class CassandraBaseAttributesDao extends CassandraAbstractAsyncDao implem stmt.setToNull(8); } log.trace("Generated save stmt [{}] for entityId {} and attributeType {} and attribute", stmt, entityId, attributeType, attribute); - return getFuture(executeAsyncWrite(stmt), rs -> null); + return getFuture(executeAsyncWrite(tenantId, stmt), rs -> null); } @Override - public ListenableFuture> removeAll(EntityId entityId, String attributeType, List keys) { + public ListenableFuture> removeAll(TenantId tenantId, EntityId entityId, String attributeType, List keys) { List> futures = keys .stream() - .map(key -> delete(entityId, attributeType, key)) + .map(key -> delete(tenantId, entityId, attributeType, key)) .collect(Collectors.toList()); return Futures.allAsList(futures); } - private ListenableFuture delete(EntityId entityId, String attributeType, String key) { + private ListenableFuture delete(TenantId tenantId, EntityId entityId, String attributeType, String key) { Statement delete = QueryBuilder.delete().all().from(ModelConstants.ATTRIBUTES_KV_CF) .where(eq(ENTITY_TYPE_COLUMN, entityId.getEntityType())) .and(eq(ENTITY_ID_COLUMN, entityId.getId())) .and(eq(ATTRIBUTE_TYPE_COLUMN, attributeType)) .and(eq(ATTRIBUTE_KEY_COLUMN, key)); log.debug("Remove request: {}", delete.toString()); - return getFuture(executeAsyncWrite(delete), rs -> null); + return getFuture(executeAsyncWrite(tenantId, delete), rs -> null); } private PreparedStatement getSaveStmt() { diff --git a/dao/src/main/java/org/thingsboard/server/dao/audit/AuditLogServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/audit/AuditLogServiceImpl.java index ecb2bd5a27..24c6a274f1 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/audit/AuditLogServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/audit/AuditLogServiceImpl.java @@ -128,7 +128,7 @@ public class AuditLogServiceImpl implements AuditLogService { entityName = entity.getName(); } else { try { - entityName = entityService.fetchEntityNameAsync(entityId).get(); + entityName = entityService.fetchEntityNameAsync(tenantId, entityId).get(); } catch (Exception ex) {} } if (e != null) { @@ -315,7 +315,7 @@ public class AuditLogServiceImpl implements AuditLogService { AuditLog auditLogEntry = createAuditLogEntry(tenantId, entityId, entityName, customerId, userId, userName, actionType, actionData, actionStatus, actionFailureDetails); log.trace("Executing logAction [{}]", auditLogEntry); - auditLogValidator.validate(auditLogEntry); + auditLogValidator.validate(auditLogEntry, AuditLog::getTenantId); List> futures = Lists.newArrayListWithExpectedSize(INSERTS_PER_ENTRY); futures.add(auditLogDao.savePartitionsByTenantId(auditLogEntry)); futures.add(auditLogDao.saveByTenantId(auditLogEntry)); @@ -331,7 +331,7 @@ public class AuditLogServiceImpl implements AuditLogService { private DataValidator auditLogValidator = new DataValidator() { @Override - protected void validateDataImpl(AuditLog auditLog) { + protected void validateDataImpl(TenantId tenantId, AuditLog auditLog) { if (auditLog.getEntityId() == null) { throw new DataValidationException("Entity Id should be specified!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/audit/CassandraAuditLogDao.java b/dao/src/main/java/org/thingsboard/server/dao/audit/CassandraAuditLogDao.java index 764f4687d3..f2b2973996 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/audit/CassandraAuditLogDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/audit/CassandraAuditLogDao.java @@ -32,6 +32,7 @@ import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.audit.AuditLog; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.dao.DaoUtil; @@ -142,7 +143,7 @@ public class CassandraAuditLogDao extends CassandraAbstractSearchTimeDao null); + return getFuture(executeAsyncWrite(auditLog.getTenantId(), stmt), rs -> null); } @Override @@ -151,7 +152,7 @@ public class CassandraAuditLogDao extends CassandraAbstractSearchTimeDao null); + return getFuture(executeAsyncWrite(auditLog.getTenantId(), stmt), rs -> null); } @Override @@ -160,7 +161,7 @@ public class CassandraAuditLogDao extends CassandraAbstractSearchTimeDao null); + return getFuture(executeAsyncWrite(auditLog.getTenantId(), stmt), rs -> null); } @Override @@ -169,11 +170,11 @@ public class CassandraAuditLogDao extends CassandraAbstractSearchTimeDao null); + return getFuture(executeAsyncWrite(auditLog.getTenantId(), stmt), rs -> null); } private BoundStatement setSaveStmtVariables(BoundStatement stmt, AuditLog auditLog, long partition) { - stmt.setUUID(0, auditLog.getId().getId()) + stmt.setUUID(0, auditLog.getId().getId()) .setUUID(1, auditLog.getTenantId().getId()) .setUUID(2, auditLog.getCustomerId().getId()) .setUUID(3, auditLog.getEntityId().getId()) @@ -200,7 +201,7 @@ public class CassandraAuditLogDao extends CassandraAbstractSearchTimeDao null); + return getFuture(executeAsyncWrite(auditLog.getTenantId(), stmt), rs -> null); } private PreparedStatement getSaveByTenantStmt() { @@ -249,7 +250,7 @@ public class CassandraAuditLogDao extends CassandraAbstractSearchTimeDao findAuditLogsByTenantIdAndEntityId(UUID tenantId, EntityId entityId, TimePageLink pageLink) { log.trace("Try to find audit logs by tenant [{}], entity [{}] and pageLink [{}]", tenantId, entityId, pageLink); - List entities = findPageWithTimeSearch(AUDIT_LOG_BY_ENTITY_ID_CF, + List entities = findPageWithTimeSearch(new TenantId(tenantId), AUDIT_LOG_BY_ENTITY_ID_CF, Arrays.asList(eq(ModelConstants.AUDIT_LOG_TENANT_ID_PROPERTY, tenantId), eq(ModelConstants.AUDIT_LOG_ENTITY_TYPE_PROPERTY, entityId.getEntityType()), eq(ModelConstants.AUDIT_LOG_ENTITY_ID_PROPERTY, entityId.getId())), @@ -286,7 +287,7 @@ public class CassandraAuditLogDao extends CassandraAbstractSearchTimeDao findAuditLogsByTenantIdAndCustomerId(UUID tenantId, CustomerId customerId, TimePageLink pageLink) { log.trace("Try to find audit logs by tenant [{}], customer [{}] and pageLink [{}]", tenantId, customerId, pageLink); - List entities = findPageWithTimeSearch(AUDIT_LOG_BY_CUSTOMER_ID_CF, + List entities = findPageWithTimeSearch(new TenantId(tenantId), AUDIT_LOG_BY_CUSTOMER_ID_CF, Arrays.asList(eq(ModelConstants.AUDIT_LOG_TENANT_ID_PROPERTY, tenantId), eq(ModelConstants.AUDIT_LOG_CUSTOMER_ID_PROPERTY, customerId.getId())), pageLink); @@ -297,7 +298,7 @@ public class CassandraAuditLogDao extends CassandraAbstractSearchTimeDao findAuditLogsByTenantIdAndUserId(UUID tenantId, UserId userId, TimePageLink pageLink) { log.trace("Try to find audit logs by tenant [{}], user [{}] and pageLink [{}]", tenantId, userId, pageLink); - List entities = findPageWithTimeSearch(AUDIT_LOG_BY_USER_ID_CF, + List entities = findPageWithTimeSearch(new TenantId(tenantId), AUDIT_LOG_BY_USER_ID_CF, Arrays.asList(eq(ModelConstants.AUDIT_LOG_TENANT_ID_PROPERTY, tenantId), eq(ModelConstants.AUDIT_LOG_USER_ID_PROPERTY, userId.getId())), pageLink); @@ -339,7 +340,7 @@ public class CassandraAuditLogDao extends CassandraAbstractSearchTimeDao result = componentDescriptorDao.saveIfNotExist(component); + public ComponentDescriptor saveComponent(TenantId tenantId, ComponentDescriptor component) { + componentValidator.validate(component, data -> new TenantId(EntityId.NULL_UUID)); + Optional result = componentDescriptorDao.saveIfNotExist(tenantId, component); if (result.isPresent()) { return result.get(); } else { - return componentDescriptorDao.findByClazz(component.getClazz()); + return componentDescriptorDao.findByClazz(tenantId, component.getClazz()); } } @Override - public ComponentDescriptor findById(ComponentDescriptorId componentId) { + public ComponentDescriptor findById(TenantId tenantId, ComponentDescriptorId componentId) { Validator.validateId(componentId, "Incorrect component id for search request."); - return componentDescriptorDao.findById(componentId); + return componentDescriptorDao.findById(tenantId, componentId); } @Override - public ComponentDescriptor findByClazz(String clazz) { + public ComponentDescriptor findByClazz(TenantId tenantId, String clazz) { Validator.validateString(clazz, "Incorrect clazz for search request."); - return componentDescriptorDao.findByClazz(clazz); + return componentDescriptorDao.findByClazz(tenantId, clazz); } @Override - public TextPageData findByTypeAndPageLink(ComponentType type, TextPageLink pageLink) { + public TextPageData findByTypeAndPageLink(TenantId tenantId, ComponentType type, TextPageLink pageLink) { Validator.validatePageLink(pageLink, "Incorrect PageLink object for search plugin components request."); - List components = componentDescriptorDao.findByTypeAndPageLink(type, pageLink); + List components = componentDescriptorDao.findByTypeAndPageLink(tenantId, type, pageLink); return new TextPageData<>(components, pageLink); } @Override - public TextPageData findByScopeAndTypeAndPageLink(ComponentScope scope, ComponentType type, TextPageLink pageLink) { + public TextPageData findByScopeAndTypeAndPageLink(TenantId tenantId, ComponentScope scope, ComponentType type, TextPageLink pageLink) { Validator.validatePageLink(pageLink, "Incorrect PageLink object for search plugin components request."); - List components = componentDescriptorDao.findByScopeAndTypeAndPageLink(scope, type, pageLink); + List components = componentDescriptorDao.findByScopeAndTypeAndPageLink(tenantId, scope, type, pageLink); return new TextPageData<>(components, pageLink); } @Override - public void deleteByClazz(String clazz) { + public void deleteByClazz(TenantId tenantId, String clazz) { Validator.validateString(clazz, "Incorrect clazz for delete request."); - componentDescriptorDao.deleteByClazz(clazz); + componentDescriptorDao.deleteByClazz(tenantId, clazz); } @Override - public boolean validate(ComponentDescriptor component, JsonNode configuration) { + public boolean validate(TenantId tenantId, ComponentDescriptor component, JsonNode configuration) { JsonValidator validator = JsonSchemaFactory.byDefault().getValidator(); try { if (!component.getConfigurationDescriptor().has("schema")) { @@ -109,7 +111,7 @@ public class BaseComponentDescriptorService implements ComponentDescriptorServic private DataValidator componentValidator = new DataValidator() { @Override - protected void validateDataImpl(ComponentDescriptor plugin) { + protected void validateDataImpl(TenantId tenantId, ComponentDescriptor plugin) { if (plugin.getType() == null) { throw new DataValidationException("Component type should be specified!."); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/component/CassandraBaseComponentDescriptorDao.java b/dao/src/main/java/org/thingsboard/server/dao/component/CassandraBaseComponentDescriptorDao.java index b5b9f15332..d7a0c7f092 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/component/CassandraBaseComponentDescriptorDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/component/CassandraBaseComponentDescriptorDao.java @@ -23,6 +23,7 @@ import com.datastax.driver.core.utils.UUIDs; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.id.ComponentDescriptorId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.plugin.ComponentDescriptor; import org.thingsboard.server.common.data.plugin.ComponentScope; @@ -62,10 +63,10 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch } @Override - public Optional saveIfNotExist(ComponentDescriptor component) { + public Optional saveIfNotExist(TenantId tenantId, ComponentDescriptor component) { ComponentDescriptorEntity entity = new ComponentDescriptorEntity(component); log.debug("Save component entity [{}]", entity); - Optional result = saveIfNotExist(entity); + Optional result = saveIfNotExist(tenantId, entity); if (log.isTraceEnabled()) { log.trace("Saved result: [{}] for component entity [{}]", result.isPresent(), result.orElse(null)); } else { @@ -75,9 +76,9 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch } @Override - public ComponentDescriptor findById(ComponentDescriptorId componentId) { + public ComponentDescriptor findById(TenantId tenantId, ComponentDescriptorId componentId) { log.debug("Search component entity by id [{}]", componentId); - ComponentDescriptor componentDescriptor = super.findById(componentId.getId()); + ComponentDescriptor componentDescriptor = super.findById(tenantId, componentId.getId()); if (log.isTraceEnabled()) { log.trace("Search result: [{}] for component entity [{}]", componentDescriptor != null, componentDescriptor); } else { @@ -87,11 +88,11 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch } @Override - public ComponentDescriptor findByClazz(String clazz) { + public ComponentDescriptor findByClazz(TenantId tenantId, String clazz) { log.debug("Search component entity by clazz [{}]", clazz); Select.Where query = select().from(getColumnFamilyName()).where(eq(ModelConstants.COMPONENT_DESCRIPTOR_CLASS_PROPERTY, clazz)); log.trace("Execute query [{}]", query); - ComponentDescriptorEntity entity = findOneByStatement(query); + ComponentDescriptorEntity entity = findOneByStatement(tenantId, query); if (log.isTraceEnabled()) { log.trace("Search result: [{}] for component entity [{}]", entity != null, entity); } else { @@ -101,9 +102,9 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch } @Override - public List findByTypeAndPageLink(ComponentType type, TextPageLink pageLink) { + public List findByTypeAndPageLink(TenantId tenantId, ComponentType type, TextPageLink pageLink) { log.debug("Try to find component by type [{}] and pageLink [{}]", type, pageLink); - List entities = findPageWithTextSearch(ModelConstants.COMPONENT_DESCRIPTOR_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List entities = findPageWithTextSearch(tenantId, 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())); @@ -114,9 +115,9 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch } @Override - public List findByScopeAndTypeAndPageLink(ComponentScope scope, ComponentType type, TextPageLink pageLink) { + public List findByScopeAndTypeAndPageLink(TenantId tenantId, ComponentScope scope, ComponentType type, TextPageLink pageLink) { log.debug("Try to find component by scope [{}] and type [{}] and pageLink [{}]", scope, type, pageLink); - List entities = findPageWithTextSearch(ModelConstants.COMPONENT_DESCRIPTOR_BY_SCOPE_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List entities = findPageWithTextSearch(tenantId, ModelConstants.COMPONENT_DESCRIPTOR_BY_SCOPE_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, type), eq(ModelConstants.COMPONENT_DESCRIPTOR_SCOPE_PROPERTY, scope.name())), pageLink); if (log.isTraceEnabled()) { @@ -127,34 +128,34 @@ public class CassandraBaseComponentDescriptorDao extends CassandraAbstractSearch return DaoUtil.convertDataList(entities); } - public boolean removeById(UUID key) { + public boolean removeById(TenantId tenantId, UUID key) { Statement delete = QueryBuilder.delete().all().from(ModelConstants.COMPONENT_DESCRIPTOR_BY_ID).where(eq(ModelConstants.ID_PROPERTY, key)); log.debug("Remove request: {}", delete.toString()); - return executeWrite(delete).wasApplied(); + return executeWrite(tenantId, delete).wasApplied(); } @Override - public void deleteById(ComponentDescriptorId id) { + public void deleteById(TenantId tenantId, ComponentDescriptorId id) { log.debug("Delete plugin meta-data entity by id [{}]", id); - boolean result = removeById(id.getId()); + boolean result = removeById(tenantId, id.getId()); log.debug("Delete result: [{}]", result); } @Override - public void deleteByClazz(String clazz) { + public void deleteByClazz(TenantId tenantId, String clazz) { log.debug("Delete plugin meta-data entity by id [{}]", clazz); Statement delete = QueryBuilder.delete().all().from(getColumnFamilyName()).where(eq(ModelConstants.COMPONENT_DESCRIPTOR_CLASS_PROPERTY, clazz)); log.debug("Remove request: {}", delete.toString()); - ResultSet resultSet = executeWrite(delete); + ResultSet resultSet = executeWrite(tenantId, delete); log.debug("Delete result: [{}]", resultSet.wasApplied()); } - private Optional saveIfNotExist(ComponentDescriptorEntity entity) { + private Optional saveIfNotExist(TenantId tenantId, ComponentDescriptorEntity entity) { if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } - ResultSet rs = executeRead(QueryBuilder.insertInto(getColumnFamilyName()) + ResultSet rs = executeRead(tenantId, QueryBuilder.insertInto(getColumnFamilyName()) .value(ModelConstants.ID_PROPERTY, entity.getId()) .value(ModelConstants.COMPONENT_DESCRIPTOR_NAME_PROPERTY, entity.getName()) .value(ModelConstants.COMPONENT_DESCRIPTOR_CLASS_PROPERTY, entity.getClazz()) diff --git a/dao/src/main/java/org/thingsboard/server/dao/component/ComponentDescriptorDao.java b/dao/src/main/java/org/thingsboard/server/dao/component/ComponentDescriptorDao.java index 7e874826d2..9ba0c96ae4 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/component/ComponentDescriptorDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/component/ComponentDescriptorDao.java @@ -16,6 +16,7 @@ package org.thingsboard.server.dao.component; import org.thingsboard.server.common.data.id.ComponentDescriptorId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.plugin.ComponentDescriptor; import org.thingsboard.server.common.data.plugin.ComponentScope; @@ -30,18 +31,18 @@ import java.util.Optional; */ public interface ComponentDescriptorDao extends Dao { - Optional saveIfNotExist(ComponentDescriptor component); + Optional saveIfNotExist(TenantId tenantId, ComponentDescriptor component); - ComponentDescriptor findById(ComponentDescriptorId componentId); + ComponentDescriptor findById(TenantId tenantId, ComponentDescriptorId componentId); - ComponentDescriptor findByClazz(String clazz); + ComponentDescriptor findByClazz(TenantId tenantId, String clazz); - List findByTypeAndPageLink(ComponentType type, TextPageLink pageLink); + List findByTypeAndPageLink(TenantId tenantId, ComponentType type, TextPageLink pageLink); - List findByScopeAndTypeAndPageLink(ComponentScope scope, ComponentType type, TextPageLink pageLink); + List findByScopeAndTypeAndPageLink(TenantId tenantId, ComponentScope scope, ComponentType type, TextPageLink pageLink); - void deleteById(ComponentDescriptorId componentId); + void deleteById(TenantId tenantId, ComponentDescriptorId componentId); - void deleteByClazz(String clazz); + void deleteByClazz(TenantId tenantId, String clazz); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/component/ComponentDescriptorService.java b/dao/src/main/java/org/thingsboard/server/dao/component/ComponentDescriptorService.java index bd101def49..63cc499811 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/component/ComponentDescriptorService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/component/ComponentDescriptorService.java @@ -17,6 +17,7 @@ package org.thingsboard.server.dao.component; import com.fasterxml.jackson.databind.JsonNode; import org.thingsboard.server.common.data.id.ComponentDescriptorId; +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.plugin.ComponentDescriptor; @@ -28,18 +29,18 @@ import org.thingsboard.server.common.data.plugin.ComponentType; */ public interface ComponentDescriptorService { - ComponentDescriptor saveComponent(ComponentDescriptor component); + ComponentDescriptor saveComponent(TenantId tenantId, ComponentDescriptor component); - ComponentDescriptor findById(ComponentDescriptorId componentId); + ComponentDescriptor findById(TenantId tenantId, ComponentDescriptorId componentId); - ComponentDescriptor findByClazz(String clazz); + ComponentDescriptor findByClazz(TenantId tenantId, String clazz); - TextPageData findByTypeAndPageLink(ComponentType type, TextPageLink pageLink); + TextPageData findByTypeAndPageLink(TenantId tenantId, ComponentType type, TextPageLink pageLink); - TextPageData findByScopeAndTypeAndPageLink(ComponentScope scope, ComponentType type, TextPageLink pageLink); + TextPageData findByScopeAndTypeAndPageLink(TenantId tenantId, ComponentScope scope, ComponentType type, TextPageLink pageLink); - boolean validate(ComponentDescriptor component, JsonNode configuration); + boolean validate(TenantId tenantId, ComponentDescriptor component, JsonNode configuration); - void deleteByClazz(String clazz); + void deleteByClazz(TenantId tenantId, String clazz); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/customer/CassandraCustomerDao.java b/dao/src/main/java/org/thingsboard/server/dao/customer/CassandraCustomerDao.java index 598f98ac47..f1b929b59d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/customer/CassandraCustomerDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/customer/CassandraCustomerDao.java @@ -19,6 +19,7 @@ import com.datastax.driver.core.querybuilder.Select; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.ModelConstants; @@ -36,6 +37,7 @@ import static com.datastax.driver.core.querybuilder.QueryBuilder.select; import static org.thingsboard.server.dao.model.ModelConstants.CUSTOMER_BY_TENANT_AND_TITLE_VIEW_NAME; import static org.thingsboard.server.dao.model.ModelConstants.CUSTOMER_TENANT_ID_PROPERTY; import static org.thingsboard.server.dao.model.ModelConstants.CUSTOMER_TITLE_PROPERTY; + @Component @Slf4j @NoSqlDao @@ -54,9 +56,9 @@ public class CassandraCustomerDao extends CassandraAbstractSearchTextDao findCustomersByTenantId(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find customers by tenantId [{}] and pageLink [{}]", tenantId, pageLink); - List customerEntities = findPageWithTextSearch(ModelConstants.CUSTOMER_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List customerEntities = findPageWithTextSearch(new TenantId(tenantId), ModelConstants.CUSTOMER_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(ModelConstants.CUSTOMER_TENANT_ID_PROPERTY, tenantId)), - pageLink); + pageLink); log.trace("Found customers [{}] by tenantId [{}] and pageLink [{}]", customerEntities, tenantId, pageLink); return DaoUtil.convertDataList(customerEntities); } @@ -67,7 +69,7 @@ public class CassandraCustomerDao extends CassandraAbstractSearchTextDao { * @param customer the customer object * @return saved customer object */ - Customer save(Customer customer); + Customer save(TenantId tenantId, Customer customer); /** * Find customers by tenant id and page link. diff --git a/dao/src/main/java/org/thingsboard/server/dao/customer/CustomerService.java b/dao/src/main/java/org/thingsboard/server/dao/customer/CustomerService.java index 4b702913b4..7471c545f0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/customer/CustomerService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/customer/CustomerService.java @@ -26,15 +26,15 @@ import java.util.Optional; public interface CustomerService { - Customer findCustomerById(CustomerId customerId); + Customer findCustomerById(TenantId tenantId, CustomerId customerId); Optional findCustomerByTenantIdAndTitle(TenantId tenantId, String title); - ListenableFuture findCustomerByIdAsync(CustomerId customerId); + ListenableFuture findCustomerByIdAsync(TenantId tenantId, CustomerId customerId); Customer saveCustomer(Customer customer); - void deleteCustomer(CustomerId customerId); + void deleteCustomer(TenantId tenantId, CustomerId customerId); Customer findOrCreatePublicCustomer(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/customer/CustomerServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/customer/CustomerServiceImpl.java index a9b8bfe181..1bbf273357 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/customer/CustomerServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/customer/CustomerServiceImpl.java @@ -77,10 +77,10 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom private DashboardService dashboardService; @Override - public Customer findCustomerById(CustomerId customerId) { + public Customer findCustomerById(TenantId tenantId, CustomerId customerId) { log.trace("Executing findCustomerById [{}]", customerId); Validator.validateId(customerId, INCORRECT_CUSTOMER_ID + customerId); - return customerDao.findById(customerId.getId()); + return customerDao.findById(tenantId, customerId.getId()); } @Override @@ -91,36 +91,36 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom } @Override - public ListenableFuture findCustomerByIdAsync(CustomerId customerId) { + public ListenableFuture findCustomerByIdAsync(TenantId tenantId, CustomerId customerId) { log.trace("Executing findCustomerByIdAsync [{}]", customerId); validateId(customerId, INCORRECT_CUSTOMER_ID + customerId); - return customerDao.findByIdAsync(customerId.getId()); + return customerDao.findByIdAsync(tenantId, customerId.getId()); } @Override public Customer saveCustomer(Customer customer) { log.trace("Executing saveCustomer [{}]", customer); - customerValidator.validate(customer); - Customer savedCustomer = customerDao.save(customer); - dashboardService.updateCustomerDashboards(savedCustomer.getId()); + customerValidator.validate(customer, Customer::getTenantId); + Customer savedCustomer = customerDao.save(customer.getTenantId(), customer); + dashboardService.updateCustomerDashboards(savedCustomer.getTenantId(), savedCustomer.getId()); return savedCustomer; } @Override - public void deleteCustomer(CustomerId customerId) { + public void deleteCustomer(TenantId tenantId, CustomerId customerId) { log.trace("Executing deleteCustomer [{}]", customerId); Validator.validateId(customerId, INCORRECT_CUSTOMER_ID + customerId); - Customer customer = findCustomerById(customerId); + Customer customer = findCustomerById(tenantId, customerId); if (customer == null) { throw new IncorrectParameterException("Unable to delete non-existent customer."); } - dashboardService.unassignCustomerDashboards(customerId); + dashboardService.unassignCustomerDashboards(tenantId, customerId); entityViewService.unassignCustomerEntityViews(customer.getTenantId(), customerId); assetService.unassignCustomerAssets(customer.getTenantId(), customerId); deviceService.unassignCustomerDevices(customer.getTenantId(), customerId); userService.deleteCustomerUsers(customer.getTenantId(), customerId); - deleteEntityRelations(customerId); - customerDao.removeById(customerId.getId()); + deleteEntityRelations(tenantId, customerId); + customerDao.removeById(tenantId, customerId.getId()); } @Override @@ -139,7 +139,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom } catch (IOException e) { throw new IncorrectParameterException("Unable to create public customer.", e); } - return customerDao.save(publicCustomer); + return customerDao.save(tenantId, publicCustomer); } } @@ -156,14 +156,14 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom public void deleteCustomersByTenantId(TenantId tenantId) { log.trace("Executing deleteCustomersByTenantId, tenantId [{}]", tenantId); Validator.validateId(tenantId, "Incorrect tenantId " + tenantId); - customersByTenantRemover.removeEntities(tenantId); + customersByTenantRemover.removeEntities(tenantId, tenantId); } private DataValidator customerValidator = new DataValidator() { @Override - protected void validateCreate(Customer customer) { + protected void validateCreate(TenantId tenantId, Customer customer) { customerDao.findCustomersByTenantIdAndTitle(customer.getTenantId().getId(), customer.getTitle()).ifPresent( c -> { throw new DataValidationException("Customer with such title already exists!"); @@ -172,7 +172,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom } @Override - protected void validateUpdate(Customer customer) { + protected void validateUpdate(TenantId tenantId, Customer customer) { customerDao.findCustomersByTenantIdAndTitle(customer.getTenantId().getId(), customer.getTitle()).ifPresent( c -> { if (!c.getId().equals(customer.getId())) { @@ -183,7 +183,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom } @Override - protected void validateDataImpl(Customer customer) { + protected void validateDataImpl(TenantId tenantId, Customer customer) { if (StringUtils.isEmpty(customer.getTitle())) { throw new DataValidationException("Customer title should be specified!"); } @@ -196,7 +196,7 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom if (customer.getTenantId() == null) { throw new DataValidationException("Customer should be assigned to tenant!"); } else { - Tenant tenant = tenantDao.findById(customer.getTenantId().getId()); + Tenant tenant = tenantDao.findById(tenantId, customer.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("Customer is referencing to non-existent tenant!"); } @@ -208,13 +208,13 @@ public class CustomerServiceImpl extends AbstractEntityService implements Custom new PaginatedRemover() { @Override - protected List findEntities(TenantId id, TextPageLink pageLink) { + protected List findEntities(TenantId tenantId, TenantId id, TextPageLink pageLink) { return customerDao.findCustomersByTenantId(id.getId(), pageLink); } @Override - protected void removeEntity(Customer entity) { - deleteCustomer(new CustomerId(entity.getUuidId())); + protected void removeEntity(TenantId tenantId, Customer entity) { + deleteCustomer(tenantId, new CustomerId(entity.getUuidId())); } }; } diff --git a/dao/src/main/java/org/thingsboard/server/dao/dashboard/CassandraDashboardInfoDao.java b/dao/src/main/java/org/thingsboard/server/dao/dashboard/CassandraDashboardInfoDao.java index 13a27c2ef5..4669d8fa92 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/dashboard/CassandraDashboardInfoDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/dashboard/CassandraDashboardInfoDao.java @@ -23,6 +23,7 @@ import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.relation.EntityRelation; @@ -64,7 +65,7 @@ public class CassandraDashboardInfoDao extends CassandraAbstractSearchTextDao findDashboardsByTenantId(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find dashboards by tenantId [{}] and pageLink [{}]", tenantId, pageLink); - List dashboardEntities = findPageWithTextSearch(DASHBOARD_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List dashboardEntities = findPageWithTextSearch(new TenantId(tenantId), DASHBOARD_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Collections.singletonList(eq(DASHBOARD_TENANT_ID_PROPERTY, tenantId)), pageLink); @@ -76,12 +77,12 @@ public class CassandraDashboardInfoDao extends CassandraAbstractSearchTextDao> findDashboardsByTenantIdAndCustomerId(UUID tenantId, UUID customerId, TimePageLink pageLink) { log.debug("Try to find dashboards by tenantId [{}], customerId[{}] and pageLink [{}]", tenantId, customerId, pageLink); - ListenableFuture> relations = relationDao.findRelations(new CustomerId(customerId), EntityRelation.CONTAINS_TYPE, RelationTypeGroup.DASHBOARD, EntityType.DASHBOARD, pageLink); + ListenableFuture> relations = relationDao.findRelations(new TenantId(tenantId), new CustomerId(customerId), EntityRelation.CONTAINS_TYPE, RelationTypeGroup.DASHBOARD, EntityType.DASHBOARD, pageLink); return Futures.transformAsync(relations, input -> { List> dashboardFutures = new ArrayList<>(input.size()); for (EntityRelation relation : input) { - dashboardFutures.add(findByIdAsync(relation.getTo().getId())); + dashboardFutures.add(findByIdAsync(new TenantId(tenantId), relation.getTo().getId())); } return Futures.successfulAsList(dashboardFutures); }); diff --git a/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardDao.java b/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardDao.java index c355eef6d6..16837762b1 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardDao.java @@ -16,6 +16,7 @@ package org.thingsboard.server.dao.dashboard; import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.Dao; /** @@ -29,6 +30,6 @@ public interface DashboardDao extends Dao { * @param dashboard the dashboard object * @return saved dashboard object */ - Dashboard save(Dashboard dashboard); + Dashboard save(TenantId tenantId, Dashboard dashboard); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardService.java b/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardService.java index c69364b8ce..c0a67ccbef 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardService.java @@ -28,21 +28,21 @@ import org.thingsboard.server.common.data.page.TimePageLink; public interface DashboardService { - Dashboard findDashboardById(DashboardId dashboardId); + Dashboard findDashboardById(TenantId tenantId, DashboardId dashboardId); - ListenableFuture findDashboardByIdAsync(DashboardId dashboardId); + ListenableFuture findDashboardByIdAsync(TenantId tenantId, DashboardId dashboardId); - DashboardInfo findDashboardInfoById(DashboardId dashboardId); + DashboardInfo findDashboardInfoById(TenantId tenantId, DashboardId dashboardId); - ListenableFuture findDashboardInfoByIdAsync(DashboardId dashboardId); + ListenableFuture findDashboardInfoByIdAsync(TenantId tenantId, DashboardId dashboardId); Dashboard saveDashboard(Dashboard dashboard); - Dashboard assignDashboardToCustomer(DashboardId dashboardId, CustomerId customerId); + Dashboard assignDashboardToCustomer(TenantId tenantId, DashboardId dashboardId, CustomerId customerId); - Dashboard unassignDashboardFromCustomer(DashboardId dashboardId, CustomerId customerId); + Dashboard unassignDashboardFromCustomer(TenantId tenantId, DashboardId dashboardId, CustomerId customerId); - void deleteDashboard(DashboardId dashboardId); + void deleteDashboard(TenantId tenantId, DashboardId dashboardId); TextPageData findDashboardsByTenantId(TenantId tenantId, TextPageLink pageLink); @@ -50,8 +50,8 @@ public interface DashboardService { ListenableFuture> findDashboardsByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TimePageLink pageLink); - void unassignCustomerDashboards(CustomerId customerId); + void unassignCustomerDashboards(TenantId tenantId, CustomerId customerId); - void updateCustomerDashboards(CustomerId customerId); + void updateCustomerDashboards(TenantId tenantId, CustomerId customerId); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardServiceImpl.java index e1f4e3c282..096484fe0b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/dashboard/DashboardServiceImpl.java @@ -69,44 +69,44 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb private CustomerDao customerDao; @Override - public Dashboard findDashboardById(DashboardId dashboardId) { + public Dashboard findDashboardById(TenantId tenantId, DashboardId dashboardId) { log.trace("Executing findDashboardById [{}]", dashboardId); Validator.validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId); - return dashboardDao.findById(dashboardId.getId()); + return dashboardDao.findById(tenantId, dashboardId.getId()); } @Override - public ListenableFuture findDashboardByIdAsync(DashboardId dashboardId) { + public ListenableFuture findDashboardByIdAsync(TenantId tenantId, DashboardId dashboardId) { log.trace("Executing findDashboardByIdAsync [{}]", dashboardId); validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId); - return dashboardDao.findByIdAsync(dashboardId.getId()); + return dashboardDao.findByIdAsync(tenantId, dashboardId.getId()); } @Override - public DashboardInfo findDashboardInfoById(DashboardId dashboardId) { + public DashboardInfo findDashboardInfoById(TenantId tenantId, DashboardId dashboardId) { log.trace("Executing findDashboardInfoById [{}]", dashboardId); Validator.validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId); - return dashboardInfoDao.findById(dashboardId.getId()); + return dashboardInfoDao.findById(tenantId, dashboardId.getId()); } @Override - public ListenableFuture findDashboardInfoByIdAsync(DashboardId dashboardId) { + public ListenableFuture findDashboardInfoByIdAsync(TenantId tenantId, DashboardId dashboardId) { log.trace("Executing findDashboardInfoByIdAsync [{}]", dashboardId); validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId); - return dashboardInfoDao.findByIdAsync(dashboardId.getId()); + return dashboardInfoDao.findByIdAsync(tenantId, dashboardId.getId()); } @Override public Dashboard saveDashboard(Dashboard dashboard) { log.trace("Executing saveDashboard [{}]", dashboard); - dashboardValidator.validate(dashboard); - return dashboardDao.save(dashboard); + dashboardValidator.validate(dashboard, DashboardInfo::getTenantId); + return dashboardDao.save(dashboard.getTenantId(), dashboard); } @Override - public Dashboard assignDashboardToCustomer(DashboardId dashboardId, CustomerId customerId) { - Dashboard dashboard = findDashboardById(dashboardId); - Customer customer = customerDao.findById(customerId.getId()); + public Dashboard assignDashboardToCustomer(TenantId tenantId, DashboardId dashboardId, CustomerId customerId) { + Dashboard dashboard = findDashboardById(tenantId, dashboardId); + Customer customer = customerDao.findById(tenantId, customerId.getId()); if (customer == null) { throw new DataValidationException("Can't assign dashboard to non-existent customer!"); } @@ -115,7 +115,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb } if (dashboard.addAssignedCustomer(customer)) { try { - createRelation(new EntityRelation(customerId, dashboardId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.DASHBOARD)); + createRelation(tenantId, new EntityRelation(customerId, dashboardId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.DASHBOARD)); } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to create dashboard relation. Customer Id: [{}]", dashboardId, customerId); throw new RuntimeException(e); @@ -127,15 +127,15 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb } @Override - public Dashboard unassignDashboardFromCustomer(DashboardId dashboardId, CustomerId customerId) { - Dashboard dashboard = findDashboardById(dashboardId); - Customer customer = customerDao.findById(customerId.getId()); + public Dashboard unassignDashboardFromCustomer(TenantId tenantId, DashboardId dashboardId, CustomerId customerId) { + Dashboard dashboard = findDashboardById(tenantId, dashboardId); + Customer customer = customerDao.findById(tenantId, customerId.getId()); if (customer == null) { throw new DataValidationException("Can't unassign dashboard from non-existent customer!"); } if (dashboard.removeAssignedCustomer(customer)) { try { - deleteRelation(new EntityRelation(customerId, dashboardId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.DASHBOARD)); + deleteRelation(tenantId, new EntityRelation(customerId, dashboardId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.DASHBOARD)); } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to delete dashboard relation. Customer Id: [{}]", dashboardId, customerId); throw new RuntimeException(e); @@ -146,8 +146,8 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb } } - private Dashboard updateAssignedCustomer(DashboardId dashboardId, Customer customer) { - Dashboard dashboard = findDashboardById(dashboardId); + private Dashboard updateAssignedCustomer(TenantId tenantId, DashboardId dashboardId, Customer customer) { + Dashboard dashboard = findDashboardById(tenantId, dashboardId); if (dashboard.updateAssignedCustomer(customer)) { return saveDashboard(dashboard); } else { @@ -155,22 +155,22 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb } } - private void deleteRelation(EntityRelation dashboardRelation) throws ExecutionException, InterruptedException { + private void deleteRelation(TenantId tenantId, EntityRelation dashboardRelation) throws ExecutionException, InterruptedException { log.debug("Deleting Dashboard relation: {}", dashboardRelation); - relationService.deleteRelationAsync(dashboardRelation).get(); + relationService.deleteRelationAsync(tenantId, dashboardRelation).get(); } - private void createRelation(EntityRelation dashboardRelation) throws ExecutionException, InterruptedException { + private void createRelation(TenantId tenantId, EntityRelation dashboardRelation) throws ExecutionException, InterruptedException { log.debug("Creating Dashboard relation: {}", dashboardRelation); - relationService.saveRelationAsync(dashboardRelation).get(); + relationService.saveRelationAsync(tenantId, dashboardRelation).get(); } @Override - public void deleteDashboard(DashboardId dashboardId) { + public void deleteDashboard(TenantId tenantId, DashboardId dashboardId) { log.trace("Executing deleteDashboard [{}]", dashboardId); Validator.validateId(dashboardId, INCORRECT_DASHBOARD_ID + dashboardId); - deleteEntityRelations(dashboardId); - dashboardDao.removeById(dashboardId.getId()); + deleteEntityRelations(tenantId, dashboardId); + dashboardDao.removeById(tenantId, dashboardId.getId()); } @Override @@ -186,7 +186,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb public void deleteDashboardsByTenantId(TenantId tenantId) { log.trace("Executing deleteDashboardsByTenantId, tenantId [{}]", tenantId); Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId); - tenantDashboardsRemover.removeEntities(tenantId); + tenantDashboardsRemover.removeEntities(tenantId, tenantId); } @Override @@ -207,10 +207,10 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb } @Override - public void unassignCustomerDashboards(CustomerId customerId) { + public void unassignCustomerDashboards(TenantId tenantId, CustomerId customerId) { log.trace("Executing unassignCustomerDashboards, customerId [{}]", customerId); Validator.validateId(customerId, "Incorrect customerId " + customerId); - Customer customer = customerDao.findById(customerId.getId()); + Customer customer = customerDao.findById(tenantId, customerId.getId()); if (customer == null) { throw new DataValidationException("Can't unassign dashboards from non-existent customer!"); } @@ -218,10 +218,10 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb } @Override - public void updateCustomerDashboards(CustomerId customerId) { + public void updateCustomerDashboards(TenantId tenantId, CustomerId customerId) { log.trace("Executing updateCustomerDashboards, customerId [{}]", customerId); Validator.validateId(customerId, "Incorrect customerId " + customerId); - Customer customer = customerDao.findById(customerId.getId()); + Customer customer = customerDao.findById(tenantId, customerId.getId()); if (customer == null) { throw new DataValidationException("Can't update dashboards for non-existent customer!"); } @@ -231,14 +231,14 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb private DataValidator dashboardValidator = new DataValidator() { @Override - protected void validateDataImpl(Dashboard dashboard) { + protected void validateDataImpl(TenantId tenantId, Dashboard dashboard) { if (StringUtils.isEmpty(dashboard.getTitle())) { throw new DataValidationException("Dashboard title should be specified!"); } if (dashboard.getTenantId() == null) { throw new DataValidationException("Dashboard should be assigned to tenant!"); } else { - Tenant tenant = tenantDao.findById(dashboard.getTenantId().getId()); + Tenant tenant = tenantDao.findById(tenantId, dashboard.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("Dashboard is referencing to non-existent tenant!"); } @@ -250,13 +250,13 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb new PaginatedRemover() { @Override - protected List findEntities(TenantId id, TextPageLink pageLink) { + protected List findEntities(TenantId tenantId, TenantId id, TextPageLink pageLink) { return dashboardInfoDao.findDashboardsByTenantId(id.getId(), pageLink); } @Override - protected void removeEntity(DashboardInfo entity) { - deleteDashboard(new DashboardId(entity.getUuidId())); + protected void removeEntity(TenantId tenantId, DashboardInfo entity) { + deleteDashboard(tenantId, new DashboardId(entity.getUuidId())); } }; @@ -280,7 +280,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb @Override protected void removeEntity(DashboardInfo entity) { - unassignDashboardFromCustomer(new DashboardId(entity.getUuidId()), this.customer.getId()); + unassignDashboardFromCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer.getId()); } } @@ -305,7 +305,7 @@ public class DashboardServiceImpl extends AbstractEntityService implements Dashb @Override protected void removeEntity(DashboardInfo entity) { - updateAssignedCustomer(new DashboardId(entity.getUuidId()), this.customer); + updateAssignedCustomer(customer.getTenantId(), new DashboardId(entity.getUuidId()), this.customer); } } diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/CassandraDeviceCredentialsDao.java b/dao/src/main/java/org/thingsboard/server/dao/device/CassandraDeviceCredentialsDao.java index 68c2caecf8..bff2b11f3a 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/CassandraDeviceCredentialsDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/CassandraDeviceCredentialsDao.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.device; import com.datastax.driver.core.querybuilder.Select.Where; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.ModelConstants; @@ -46,23 +47,23 @@ public class CassandraDeviceCredentialsDao extends CassandraAbstractModelDao findDevicesByTenantId(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find devices by tenantId [{}] and pageLink [{}]", tenantId, pageLink); - List deviceEntities = findPageWithTextSearch(DEVICE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List deviceEntities = findPageWithTextSearch(new TenantId(tenantId), DEVICE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Collections.singletonList(eq(DEVICE_TENANT_ID_PROPERTY, tenantId)), pageLink); log.trace("Found devices [{}] by tenantId [{}] and pageLink [{}]", deviceEntities, tenantId, pageLink); @@ -99,7 +100,7 @@ public class CassandraDeviceDao extends CassandraAbstractSearchTextDao findDevicesByTenantIdAndType(UUID tenantId, String type, TextPageLink pageLink) { log.debug("Try to find devices by tenantId [{}], type [{}] and pageLink [{}]", tenantId, type, pageLink); - List deviceEntities = findPageWithTextSearch(DEVICE_BY_TENANT_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List deviceEntities = findPageWithTextSearch(new TenantId(tenantId), DEVICE_BY_TENANT_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(DEVICE_TYPE_PROPERTY, type), eq(DEVICE_TENANT_ID_PROPERTY, tenantId)), pageLink); log.trace("Found devices [{}] by tenantId [{}], type [{}] and pageLink [{}]", deviceEntities, tenantId, type, pageLink); @@ -113,13 +114,13 @@ public class CassandraDeviceDao extends CassandraAbstractSearchTextDao findDevicesByTenantIdAndCustomerId(UUID tenantId, UUID customerId, TextPageLink pageLink) { log.debug("Try to find devices by tenantId [{}], customerId[{}] and pageLink [{}]", tenantId, customerId, pageLink); - List deviceEntities = findPageWithTextSearch(DEVICE_BY_CUSTOMER_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List deviceEntities = findPageWithTextSearch(new TenantId(tenantId), DEVICE_BY_CUSTOMER_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(DEVICE_CUSTOMER_ID_PROPERTY, customerId), eq(DEVICE_TENANT_ID_PROPERTY, tenantId)), pageLink); @@ -131,7 +132,7 @@ public class CassandraDeviceDao extends CassandraAbstractSearchTextDao findDevicesByTenantIdAndCustomerIdAndType(UUID tenantId, UUID customerId, String type, TextPageLink pageLink) { log.debug("Try to find devices by tenantId [{}], customerId [{}], type [{}] and pageLink [{}]", tenantId, customerId, type, pageLink); - List deviceEntities = findPageWithTextSearch(DEVICE_BY_CUSTOMER_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List deviceEntities = findPageWithTextSearch(new TenantId(tenantId), DEVICE_BY_CUSTOMER_BY_TYPE_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(DEVICE_TYPE_PROPERTY, type), eq(DEVICE_CUSTOMER_ID_PROPERTY, customerId), eq(DEVICE_TENANT_ID_PROPERTY, tenantId)), @@ -149,7 +150,7 @@ public class CassandraDeviceDao extends CassandraAbstractSearchTextDao>() { @Nullable @Override diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsDao.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsDao.java index bb36ee9987..fe6b874e81 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsDao.java @@ -15,6 +15,7 @@ */ package org.thingsboard.server.dao.device; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.dao.Dao; @@ -28,10 +29,11 @@ public interface DeviceCredentialsDao extends Dao { /** * Save or update device credentials object * + * @param tenantId the device tenant id * @param deviceCredentials the device credentials object * @return saved device credentials object */ - DeviceCredentials save(DeviceCredentials deviceCredentials); + DeviceCredentials save(TenantId tenantId, DeviceCredentials deviceCredentials); /** * Find device credentials by device id. @@ -39,7 +41,7 @@ public interface DeviceCredentialsDao extends Dao { * @param deviceId the device id * @return the device credentials object */ - DeviceCredentials findByDeviceId(UUID deviceId); + DeviceCredentials findByDeviceId(TenantId tenantId, UUID deviceId); /** * Find device credentials by credentials id. @@ -47,6 +49,6 @@ public interface DeviceCredentialsDao extends Dao { * @param credentialsId the credentials id * @return the device credentials object */ - DeviceCredentials findByCredentialsId(String credentialsId); + DeviceCredentials findByCredentialsId(TenantId tenantId, String credentialsId); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsService.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsService.java index 89389a5550..6485756834 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsService.java @@ -16,17 +16,18 @@ package org.thingsboard.server.dao.device; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.DeviceCredentials; public interface DeviceCredentialsService { - DeviceCredentials findDeviceCredentialsByDeviceId(DeviceId deviceId); + DeviceCredentials findDeviceCredentialsByDeviceId(TenantId tenantId, DeviceId deviceId); DeviceCredentials findDeviceCredentialsByCredentialsId(String credentialsId); - DeviceCredentials updateDeviceCredentials(DeviceCredentials deviceCredentials); + DeviceCredentials updateDeviceCredentials(TenantId tenantId, DeviceCredentials deviceCredentials); - DeviceCredentials createDeviceCredentials(DeviceCredentials deviceCredentials); + DeviceCredentials createDeviceCredentials(TenantId tenantId, DeviceCredentials deviceCredentials); - void deleteDeviceCredentials(DeviceCredentials deviceCredentials); + void deleteDeviceCredentials(TenantId tenantId, DeviceCredentials deviceCredentials); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsServiceImpl.java index 101bff2bdd..b457bcb8d5 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceCredentialsServiceImpl.java @@ -24,6 +24,8 @@ import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.common.msg.EncryptionUtil; @@ -45,38 +47,38 @@ public class DeviceCredentialsServiceImpl implements DeviceCredentialsService { private DeviceService deviceService; @Override - public DeviceCredentials findDeviceCredentialsByDeviceId(DeviceId deviceId) { + public DeviceCredentials findDeviceCredentialsByDeviceId(TenantId tenantId, DeviceId deviceId) { log.trace("Executing findDeviceCredentialsByDeviceId [{}]", deviceId); validateId(deviceId, "Incorrect deviceId " + deviceId); - return deviceCredentialsDao.findByDeviceId(deviceId.getId()); + return deviceCredentialsDao.findByDeviceId(tenantId, deviceId.getId()); } @Override - @Cacheable(cacheNames = DEVICE_CREDENTIALS_CACHE, unless="#result == null") + @Cacheable(cacheNames = DEVICE_CREDENTIALS_CACHE, unless = "#result == null") public DeviceCredentials findDeviceCredentialsByCredentialsId(String credentialsId) { log.trace("Executing findDeviceCredentialsByCredentialsId [{}]", credentialsId); validateString(credentialsId, "Incorrect credentialsId " + credentialsId); - return deviceCredentialsDao.findByCredentialsId(credentialsId); + return deviceCredentialsDao.findByCredentialsId(new TenantId(EntityId.NULL_UUID), credentialsId); } @Override - @CacheEvict(cacheNames = DEVICE_CREDENTIALS_CACHE, keyGenerator="previousDeviceCredentialsId", beforeInvocation = true) - public DeviceCredentials updateDeviceCredentials(DeviceCredentials deviceCredentials) { - return saveOrUpdate(deviceCredentials); + @CacheEvict(cacheNames = DEVICE_CREDENTIALS_CACHE, keyGenerator = "previousDeviceCredentialsId", beforeInvocation = true) + public DeviceCredentials updateDeviceCredentials(TenantId tenantId, DeviceCredentials deviceCredentials) { + return saveOrUpdate(tenantId, deviceCredentials); } @Override - public DeviceCredentials createDeviceCredentials(DeviceCredentials deviceCredentials) { - return saveOrUpdate(deviceCredentials); + public DeviceCredentials createDeviceCredentials(TenantId tenantId, DeviceCredentials deviceCredentials) { + return saveOrUpdate(tenantId, deviceCredentials); } - private DeviceCredentials saveOrUpdate(DeviceCredentials deviceCredentials) { + private DeviceCredentials saveOrUpdate(TenantId tenantId, DeviceCredentials deviceCredentials) { if (deviceCredentials.getCredentialsType() == DeviceCredentialsType.X509_CERTIFICATE) { formatCertData(deviceCredentials); } log.trace("Executing updateDeviceCredentials [{}]", deviceCredentials); - credentialsValidator.validate(deviceCredentials); - return deviceCredentialsDao.save(deviceCredentials); + credentialsValidator.validate(deviceCredentials, id -> tenantId); + return deviceCredentialsDao.save(tenantId, deviceCredentials); } private void formatCertData(DeviceCredentials deviceCredentials) { @@ -87,37 +89,37 @@ public class DeviceCredentialsServiceImpl implements DeviceCredentialsService { } @Override - @CacheEvict(cacheNames = DEVICE_CREDENTIALS_CACHE, key="#deviceCredentials.credentialsId") - public void deleteDeviceCredentials(DeviceCredentials deviceCredentials) { + @CacheEvict(cacheNames = DEVICE_CREDENTIALS_CACHE, key = "#deviceCredentials.credentialsId") + public void deleteDeviceCredentials(TenantId tenantId, DeviceCredentials deviceCredentials) { log.trace("Executing deleteDeviceCredentials [{}]", deviceCredentials); - deviceCredentialsDao.removeById(deviceCredentials.getUuidId()); + deviceCredentialsDao.removeById(tenantId, deviceCredentials.getUuidId()); } private DataValidator credentialsValidator = new DataValidator() { @Override - protected void validateCreate(DeviceCredentials deviceCredentials) { - DeviceCredentials existingCredentialsEntity = deviceCredentialsDao.findByCredentialsId(deviceCredentials.getCredentialsId()); + protected void validateCreate(TenantId tenantId, DeviceCredentials deviceCredentials) { + DeviceCredentials existingCredentialsEntity = deviceCredentialsDao.findByCredentialsId(tenantId, deviceCredentials.getCredentialsId()); if (existingCredentialsEntity != null) { throw new DataValidationException("Create of existent device credentials!"); } } @Override - protected void validateUpdate(DeviceCredentials deviceCredentials) { - DeviceCredentials existingCredentials = deviceCredentialsDao.findById(deviceCredentials.getUuidId()); + protected void validateUpdate(TenantId tenantId, DeviceCredentials deviceCredentials) { + DeviceCredentials existingCredentials = deviceCredentialsDao.findById(tenantId, deviceCredentials.getUuidId()); if (existingCredentials == null) { throw new DataValidationException("Unable to update non-existent device credentials!"); } - DeviceCredentials sameCredentialsId = deviceCredentialsDao.findByCredentialsId(deviceCredentials.getCredentialsId()); + DeviceCredentials sameCredentialsId = deviceCredentialsDao.findByCredentialsId(tenantId, deviceCredentials.getCredentialsId()); if (sameCredentialsId != null && !sameCredentialsId.getUuidId().equals(deviceCredentials.getUuidId())) { throw new DataValidationException("Specified credentials are already registered!"); } } @Override - protected void validateDataImpl(DeviceCredentials deviceCredentials) { + protected void validateDataImpl(TenantId tenantId, DeviceCredentials deviceCredentials) { if (deviceCredentials.getDeviceId() == null) { throw new DataValidationException("Device credentials should be assigned to device!"); } @@ -127,7 +129,7 @@ public class DeviceCredentialsServiceImpl implements DeviceCredentialsService { if (StringUtils.isEmpty(deviceCredentials.getCredentialsId())) { throw new DataValidationException("Device credentials id should be specified!"); } - Device device = deviceService.findDeviceById(deviceCredentials.getDeviceId()); + Device device = deviceService.findDeviceById(tenantId, deviceCredentials.getDeviceId()); if (device == null) { throw new DataValidationException("Can't assign device credentials to non-existent device!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceDao.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceDao.java index dbc098e575..e163a04645 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceDao.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.device; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntitySubtype; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.Dao; @@ -37,7 +38,7 @@ public interface DeviceDao extends Dao { * @param device the device object * @return saved device object */ - Device save(Device device); + Device save(TenantId tenantId, Device device); /** * Find devices by tenantId and page link. diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceService.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceService.java index c5edd9e03c..2bbd79ab46 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceService.java @@ -29,19 +29,19 @@ import java.util.List; public interface DeviceService { - Device findDeviceById(DeviceId deviceId); + Device findDeviceById(TenantId tenantId, DeviceId deviceId); - ListenableFuture findDeviceByIdAsync(DeviceId deviceId); + ListenableFuture findDeviceByIdAsync(TenantId tenantId, DeviceId deviceId); Device findDeviceByTenantIdAndName(TenantId tenantId, String name); Device saveDevice(Device device); - Device assignDeviceToCustomer(DeviceId deviceId, CustomerId customerId); + Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, CustomerId customerId); - Device unassignDeviceFromCustomer(DeviceId deviceId); + Device unassignDeviceFromCustomer(TenantId tenantId, DeviceId deviceId); - void deleteDevice(DeviceId deviceId); + void deleteDevice(TenantId tenantId, DeviceId deviceId); TextPageData findDevicesByTenantId(TenantId tenantId, TextPageLink pageLink); @@ -59,7 +59,7 @@ public interface DeviceService { void unassignCustomerDevices(TenantId tenantId, CustomerId customerId); - ListenableFuture> findDevicesByQuery(DeviceSearchQuery query); + ListenableFuture> findDevicesByQuery(TenantId tenantId, DeviceSearchQuery query); ListenableFuture> findDeviceTypesByTenantId(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java index 2be5ba4f41..902b4cd0d9 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceServiceImpl.java @@ -96,17 +96,17 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe private CacheManager cacheManager; @Override - public Device findDeviceById(DeviceId deviceId) { + public Device findDeviceById(TenantId tenantId, DeviceId deviceId) { log.trace("Executing findDeviceById [{}]", deviceId); validateId(deviceId, INCORRECT_DEVICE_ID + deviceId); - return deviceDao.findById(deviceId.getId()); + return deviceDao.findById(tenantId, deviceId.getId()); } @Override - public ListenableFuture findDeviceByIdAsync(DeviceId deviceId) { + public ListenableFuture findDeviceByIdAsync(TenantId tenantId, DeviceId deviceId) { log.trace("Executing findDeviceById [{}]", deviceId); validateId(deviceId, INCORRECT_DEVICE_ID + deviceId); - return deviceDao.findByIdAsync(deviceId.getId()); + return deviceDao.findByIdAsync(tenantId, deviceId.getId()); } @Cacheable(cacheNames = DEVICE_CACHE, key = "{#tenantId, #name}") @@ -122,38 +122,38 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe @Override public Device saveDevice(Device device) { log.trace("Executing saveDevice [{}]", device); - deviceValidator.validate(device); - Device savedDevice = deviceDao.save(device); + deviceValidator.validate(device, Device::getTenantId); + Device savedDevice = deviceDao.save(device.getTenantId(), device); if (device.getId() == null) { DeviceCredentials deviceCredentials = new DeviceCredentials(); deviceCredentials.setDeviceId(new DeviceId(savedDevice.getUuidId())); deviceCredentials.setCredentialsType(DeviceCredentialsType.ACCESS_TOKEN); deviceCredentials.setCredentialsId(RandomStringUtils.randomAlphanumeric(20)); - deviceCredentialsService.createDeviceCredentials(deviceCredentials); + deviceCredentialsService.createDeviceCredentials(device.getTenantId(), deviceCredentials); } return savedDevice; } @Override - public Device assignDeviceToCustomer(DeviceId deviceId, CustomerId customerId) { - Device device = findDeviceById(deviceId); + public Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, CustomerId customerId) { + Device device = findDeviceById(tenantId, deviceId); device.setCustomerId(customerId); return saveDevice(device); } @Override - public Device unassignDeviceFromCustomer(DeviceId deviceId) { - Device device = findDeviceById(deviceId); + public Device unassignDeviceFromCustomer(TenantId tenantId, DeviceId deviceId) { + Device device = findDeviceById(tenantId, deviceId); device.setCustomerId(null); return saveDevice(device); } @Override - public void deleteDevice(DeviceId deviceId) { + public void deleteDevice(TenantId tenantId, DeviceId deviceId) { log.trace("Executing deleteDevice [{}]", deviceId); validateId(deviceId, INCORRECT_DEVICE_ID + deviceId); - Device device = deviceDao.findById(deviceId.getId()); + Device device = deviceDao.findById(tenantId, deviceId.getId()); try { List entityViews = entityViewService.findEntityViewsByTenantIdAndEntityIdAsync(device.getTenantId(), deviceId).get(); if (entityViews != null && !entityViews.isEmpty()) { @@ -164,11 +164,11 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe throw new RuntimeException("Exception while finding entity views for deviceId [" + deviceId + "]", e); } - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(deviceId); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, deviceId); if (deviceCredentials != null) { - deviceCredentialsService.deleteDeviceCredentials(deviceCredentials); + deviceCredentialsService.deleteDeviceCredentials(tenantId, deviceCredentials); } - deleteEntityRelations(deviceId); + deleteEntityRelations(tenantId, deviceId); List list = new ArrayList<>(); list.add(device.getTenantId()); @@ -176,7 +176,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe Cache cache = cacheManager.getCache(DEVICE_CACHE); cache.evict(list); - deviceDao.removeById(deviceId.getId()); + deviceDao.removeById(tenantId, deviceId.getId()); } @Override @@ -211,7 +211,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe public void deleteDevicesByTenantId(TenantId tenantId) { log.trace("Executing deleteDevicesByTenantId, tenantId [{}]", tenantId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); - tenantDevicesRemover.removeEntities(tenantId); + tenantDevicesRemover.removeEntities(tenantId, tenantId); } @Override @@ -250,19 +250,19 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe log.trace("Executing unassignCustomerDevices, tenantId [{}], customerId [{}]", tenantId, customerId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); validateId(customerId, INCORRECT_CUSTOMER_ID + customerId); - new CustomerDevicesUnassigner(tenantId).removeEntities(customerId); + customerDeviceUnasigner.removeEntities(tenantId, customerId); } @Override - public ListenableFuture> findDevicesByQuery(DeviceSearchQuery query) { - ListenableFuture> relations = relationService.findByQuery(query.toEntitySearchQuery()); + public ListenableFuture> findDevicesByQuery(TenantId tenantId, DeviceSearchQuery query) { + ListenableFuture> relations = relationService.findByQuery(tenantId, query.toEntitySearchQuery()); ListenableFuture> devices = Futures.transformAsync(relations, r -> { EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection(); List> futures = new ArrayList<>(); for (EntityRelation relation : r) { EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom(); if (entityId.getEntityType() == EntityType.DEVICE) { - futures.add(findDeviceByIdAsync(new DeviceId(entityId.getId()))); + futures.add(findDeviceByIdAsync(tenantId, new DeviceId(entityId.getId()))); } } return Futures.successfulAsList(futures); @@ -285,7 +285,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe validateId(tenantId, INCORRECT_TENANT_ID + tenantId); ListenableFuture> tenantDeviceTypes = deviceDao.findTenantDeviceTypesAsync(tenantId.getId()); return Futures.transform(tenantDeviceTypes, - (Function, List>) deviceTypes -> { + deviceTypes -> { deviceTypes.sort(Comparator.comparing(EntitySubtype::getType)); return deviceTypes; }); @@ -295,7 +295,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe new DataValidator() { @Override - protected void validateCreate(Device device) { + protected void validateCreate(TenantId tenantId, Device device) { deviceDao.findDeviceByTenantIdAndName(device.getTenantId().getId(), device.getName()).ifPresent( d -> { throw new DataValidationException("Device with such name already exists!"); @@ -304,7 +304,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe } @Override - protected void validateUpdate(Device device) { + protected void validateUpdate(TenantId tenantId, Device device) { deviceDao.findDeviceByTenantIdAndName(device.getTenantId().getId(), device.getName()).ifPresent( d -> { if (!d.getUuidId().equals(device.getUuidId())) { @@ -315,7 +315,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe } @Override - protected void validateDataImpl(Device device) { + protected void validateDataImpl(TenantId tenantId, Device device) { if (StringUtils.isEmpty(device.getType())) { throw new DataValidationException("Device type should be specified!"); } @@ -325,7 +325,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe if (device.getTenantId() == null) { throw new DataValidationException("Device should be assigned to tenant!"); } else { - Tenant tenant = tenantDao.findById(device.getTenantId().getId()); + Tenant tenant = tenantDao.findById(device.getTenantId(), device.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("Device is referencing to non-existent tenant!"); } @@ -333,7 +333,7 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe if (device.getCustomerId() == null) { device.setCustomerId(new CustomerId(NULL_UUID)); } else if (!device.getCustomerId().getId().equals(NULL_UUID)) { - Customer customer = customerDao.findById(device.getCustomerId().getId()); + Customer customer = customerDao.findById(device.getTenantId(), device.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("Can't assign device to non-existent customer!"); } @@ -345,36 +345,29 @@ public class DeviceServiceImpl extends AbstractEntityService implements DeviceSe }; private PaginatedRemover tenantDevicesRemover = - new PaginatedRemover() { + new PaginatedRemover() { - @Override - protected List findEntities(TenantId id, TextPageLink pageLink) { - return deviceDao.findDevicesByTenantId(id.getId(), pageLink); - } - - @Override - protected void removeEntity(Device entity) { - deleteDevice(new DeviceId(entity.getUuidId())); - } - }; - - private class CustomerDevicesUnassigner extends PaginatedRemover { + @Override + protected List findEntities(TenantId tenantId, TenantId id, TextPageLink pageLink) { + return deviceDao.findDevicesByTenantId(id.getId(), pageLink); + } - private TenantId tenantId; + @Override + protected void removeEntity(TenantId tenantId, Device entity) { + deleteDevice(tenantId, new DeviceId(entity.getUuidId())); + } + }; - CustomerDevicesUnassigner(TenantId tenantId) { - this.tenantId = tenantId; - } + private PaginatedRemover customerDeviceUnasigner = new PaginatedRemover() { @Override - protected List findEntities(CustomerId id, TextPageLink pageLink) { + protected List findEntities(TenantId tenantId, CustomerId id, TextPageLink pageLink) { return deviceDao.findDevicesByTenantIdAndCustomerId(tenantId.getId(), id.getId(), pageLink); } @Override - protected void removeEntity(Device entity) { - unassignDeviceFromCustomer(new DeviceId(entity.getUuidId())); + protected void removeEntity(TenantId tenantId, Device entity) { + unassignDeviceFromCustomer(tenantId, new DeviceId(entity.getUuidId())); } - - } + }; } diff --git a/dao/src/main/java/org/thingsboard/server/dao/entity/AbstractEntityService.java b/dao/src/main/java/org/thingsboard/server/dao/entity/AbstractEntityService.java index bc530ab536..6afa877006 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/entity/AbstractEntityService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/entity/AbstractEntityService.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.entity; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.relation.RelationService; @Slf4j @@ -26,9 +27,9 @@ public abstract class AbstractEntityService { @Autowired protected RelationService relationService; - protected void deleteEntityRelations(EntityId entityId) { + protected void deleteEntityRelations(TenantId tenantId, EntityId entityId) { log.trace("Executing deleteEntityRelations [{}]", entityId); - relationService.deleteEntityRelations(entityId); + relationService.deleteEntityRelations(tenantId, entityId); } } diff --git a/dao/src/main/java/org/thingsboard/server/dao/entity/BaseEntityService.java b/dao/src/main/java/org/thingsboard/server/dao/entity/BaseEntityService.java index 33a26997ca..86bbada223 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/entity/BaseEntityService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/entity/BaseEntityService.java @@ -69,42 +69,42 @@ public class BaseEntityService extends AbstractEntityService implements EntitySe private RuleChainService ruleChainService; @Override - public void deleteEntityRelations(EntityId entityId) { - super.deleteEntityRelations(entityId); + public void deleteEntityRelations(TenantId tenantId, EntityId entityId) { + super.deleteEntityRelations(tenantId, entityId); } @Override - public ListenableFuture fetchEntityNameAsync(EntityId entityId) { + public ListenableFuture fetchEntityNameAsync(TenantId tenantId, EntityId entityId) { log.trace("Executing fetchEntityNameAsync [{}]", entityId); ListenableFuture entityName; ListenableFuture hasName; switch (entityId.getEntityType()) { case ASSET: - hasName = assetService.findAssetByIdAsync(new AssetId(entityId.getId())); + hasName = assetService.findAssetByIdAsync(tenantId, new AssetId(entityId.getId())); break; case DEVICE: - hasName = deviceService.findDeviceByIdAsync(new DeviceId(entityId.getId())); + hasName = deviceService.findDeviceByIdAsync(tenantId, new DeviceId(entityId.getId())); break; case ENTITY_VIEW: - hasName = entityViewService.findEntityViewByIdAsync(new EntityViewId(entityId.getId())); + hasName = entityViewService.findEntityViewByIdAsync(tenantId, new EntityViewId(entityId.getId())); break; case TENANT: - hasName = tenantService.findTenantByIdAsync(new TenantId(entityId.getId())); + hasName = tenantService.findTenantByIdAsync(tenantId, new TenantId(entityId.getId())); break; case CUSTOMER: - hasName = customerService.findCustomerByIdAsync(new CustomerId(entityId.getId())); + hasName = customerService.findCustomerByIdAsync(tenantId, new CustomerId(entityId.getId())); break; case USER: - hasName = userService.findUserByIdAsync(new UserId(entityId.getId())); + hasName = userService.findUserByIdAsync(tenantId, new UserId(entityId.getId())); break; case DASHBOARD: - hasName = dashboardService.findDashboardInfoByIdAsync(new DashboardId(entityId.getId())); + hasName = dashboardService.findDashboardInfoByIdAsync(tenantId, new DashboardId(entityId.getId())); break; case ALARM: - hasName = alarmService.findAlarmByIdAsync(new AlarmId(entityId.getId())); + hasName = alarmService.findAlarmByIdAsync(tenantId, new AlarmId(entityId.getId())); break; case RULE_CHAIN: - hasName = ruleChainService.findRuleChainByIdAsync(new RuleChainId(entityId.getId())); + hasName = ruleChainService.findRuleChainByIdAsync(tenantId, new RuleChainId(entityId.getId())); break; default: throw new IllegalStateException("Not Implemented!"); diff --git a/dao/src/main/java/org/thingsboard/server/dao/entity/EntityService.java b/dao/src/main/java/org/thingsboard/server/dao/entity/EntityService.java index aa4acb1c61..818dfc0114 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/entity/EntityService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/entity/EntityService.java @@ -17,11 +17,12 @@ package org.thingsboard.server.dao.entity; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; public interface EntityService { - ListenableFuture fetchEntityNameAsync(EntityId entityId); + ListenableFuture fetchEntityNameAsync(TenantId tenantId, EntityId entityId); - void deleteEntityRelations(EntityId entityId); + void deleteEntityRelations(TenantId tenantId, EntityId entityId); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/entityview/CassandraEntityViewDao.java b/dao/src/main/java/org/thingsboard/server/dao/entityview/CassandraEntityViewDao.java index 6ddc18d463..539b544a79 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/entityview/CassandraEntityViewDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/entityview/CassandraEntityViewDao.java @@ -28,6 +28,7 @@ import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.EntitySubtype; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.EntitySubtypeEntity; @@ -82,12 +83,12 @@ public class CassandraEntityViewDao extends CassandraAbstractSearchTextDao findEntityViewsByTenantId(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find entity views by tenantId [{}] and pageLink [{}]", tenantId, pageLink); List entityViewEntities = - findPageWithTextSearch(ENTITY_VIEW_BY_TENANT_AND_SEARCH_TEXT_CF, + findPageWithTextSearch(new TenantId(tenantId), ENTITY_VIEW_BY_TENANT_AND_SEARCH_TEXT_CF, Collections.singletonList(eq(TENANT_ID_PROPERTY, tenantId)), pageLink); log.trace("Found entity views [{}] by tenantId [{}] and pageLink [{}]", entityViewEntities, tenantId, pageLink); @@ -106,7 +107,7 @@ public class CassandraEntityViewDao extends CassandraAbstractSearchTextDao findEntityViewsByTenantIdAndType(UUID tenantId, String type, TextPageLink pageLink) { log.debug("Try to find entity views by tenantId [{}], type [{}] and pageLink [{}]", tenantId, type, pageLink); List entityViewEntities = - findPageWithTextSearch(ENTITY_VIEW_BY_TENANT_BY_TYPE_AND_SEARCH_TEXT_CF, + findPageWithTextSearch(new TenantId(tenantId), ENTITY_VIEW_BY_TENANT_BY_TYPE_AND_SEARCH_TEXT_CF, Arrays.asList(eq(ENTITY_VIEW_TYPE_PROPERTY, type), eq(TENANT_ID_PROPERTY, tenantId)), pageLink); log.trace("Found entity views [{}] by tenantId [{}], type [{}] and pageLink [{}]", @@ -119,14 +120,14 @@ public class CassandraEntityViewDao extends CassandraAbstractSearchTextDao findEntityViewsByTenantIdAndCustomerId(UUID tenantId, UUID customerId, TextPageLink pageLink) { log.debug("Try to find entity views by tenantId [{}], customerId[{}] and pageLink [{}]", tenantId, customerId, pageLink); - List entityViewEntities = findPageWithTextSearch( + List entityViewEntities = findPageWithTextSearch(new TenantId(tenantId), ENTITY_VIEW_BY_TENANT_AND_CUSTOMER_CF, Arrays.asList(eq(CUSTOMER_ID_PROPERTY, customerId), eq(TENANT_ID_PROPERTY, tenantId)), pageLink); @@ -139,7 +140,7 @@ public class CassandraEntityViewDao extends CassandraAbstractSearchTextDao findEntityViewsByTenantIdAndCustomerIdAndType(UUID tenantId, UUID customerId, String type, TextPageLink pageLink) { log.debug("Try to find entity views by tenantId [{}], customerId[{}], type [{}] and pageLink [{}]", tenantId, customerId, type, pageLink); - List entityViewEntities = findPageWithTextSearch( + List entityViewEntities = findPageWithTextSearch(new TenantId(tenantId), ENTITY_VIEW_BY_TENANT_AND_CUSTOMER_AND_TYPE_CF, Arrays.asList(eq(DEVICE_TYPE_PROPERTY, type), eq(CUSTOMER_ID_PROPERTY, customerId), eq(TENANT_ID_PROPERTY, tenantId)), pageLink); @@ -154,7 +155,7 @@ public class CassandraEntityViewDao extends CassandraAbstractSearchTextDao>() { @Nullable @Override diff --git a/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewDao.java b/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewDao.java index 8147a07a88..834a95d9f9 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewDao.java @@ -19,6 +19,7 @@ import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntitySubtype; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.Dao; @@ -37,7 +38,7 @@ public interface EntityViewDao extends Dao { * @param entityView the entity-view object * @return saved entity-view object */ - EntityView save(EntityView entityView); + EntityView save(TenantId tenantId, EntityView entityView); /** * Find entity views by tenantId and page link. diff --git a/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewService.java b/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewService.java index 9c828663c1..840d1da11b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewService.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.entityview; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.EntitySubtype; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.entityview.EntityViewSearchQuery; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EntityId; @@ -35,13 +36,13 @@ public interface EntityViewService { EntityView saveEntityView(EntityView entityView); - EntityView assignEntityViewToCustomer(EntityViewId entityViewId, CustomerId customerId); + EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, CustomerId customerId); - EntityView unassignEntityViewFromCustomer(EntityViewId entityViewId); + EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId); void unassignCustomerEntityViews(TenantId tenantId, CustomerId customerId); - EntityView findEntityViewById(EntityViewId entityViewId); + EntityView findEntityViewById(TenantId tenantId, EntityViewId entityViewId); EntityView findEntityViewByTenantIdAndName(TenantId tenantId, String name); @@ -53,13 +54,13 @@ public interface EntityViewService { TextPageData findEntityViewsByTenantIdAndCustomerIdAndType(TenantId tenantId, CustomerId customerId, TextPageLink pageLink, String type); - ListenableFuture> findEntityViewsByQuery(EntityViewSearchQuery query); + ListenableFuture> findEntityViewsByQuery(TenantId tenantId, EntityViewSearchQuery query); - ListenableFuture findEntityViewByIdAsync(EntityViewId entityViewId); + ListenableFuture findEntityViewByIdAsync(TenantId tenantId, EntityViewId entityViewId); ListenableFuture> findEntityViewsByTenantIdAndEntityIdAsync(TenantId tenantId, EntityId entityId); - void deleteEntityView(EntityViewId entityViewId); + void deleteEntityView(TenantId tenantId, EntityViewId entityViewId); void deleteEntityViewsByTenantId(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewServiceImpl.java index 9f8949dc4e..189a9a309b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/entityview/EntityViewServiceImpl.java @@ -95,23 +95,23 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti @Override public EntityView saveEntityView(EntityView entityView) { log.trace("Executing save entity view [{}]", entityView); - entityViewValidator.validate(entityView); - EntityView savedEntityView = entityViewDao.save(entityView); + entityViewValidator.validate(entityView, EntityView::getTenantId); + EntityView savedEntityView = entityViewDao.save(entityView.getTenantId(), entityView); return savedEntityView; } @CacheEvict(cacheNames = ENTITY_VIEW_CACHE, key = "{#entityViewId}") @Override - public EntityView assignEntityViewToCustomer(EntityViewId entityViewId, CustomerId customerId) { - EntityView entityView = findEntityViewById(entityViewId); + public EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, CustomerId customerId) { + EntityView entityView = findEntityViewById(tenantId, entityViewId); entityView.setCustomerId(customerId); return saveEntityView(entityView); } @CacheEvict(cacheNames = ENTITY_VIEW_CACHE, key = "{#entityViewId}") @Override - public EntityView unassignEntityViewFromCustomer(EntityViewId entityViewId) { - EntityView entityView = findEntityViewById(entityViewId); + public EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId) { + EntityView entityView = findEntityViewById(tenantId, entityViewId); entityView.setCustomerId(null); return saveEntityView(entityView); } @@ -121,15 +121,15 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti log.trace("Executing unassignCustomerEntityViews, tenantId [{}], customerId [{}]", tenantId, customerId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); validateId(customerId, INCORRECT_CUSTOMER_ID + customerId); - new CustomerEntityViewsUnAssigner(tenantId).removeEntities(customerId); + customerEntityViewsUnAssigner.removeEntities(tenantId, customerId); } @Cacheable(cacheNames = ENTITY_VIEW_CACHE, key = "{#entityViewId}") @Override - public EntityView findEntityViewById(EntityViewId entityViewId) { + public EntityView findEntityViewById(TenantId tenantId, EntityViewId entityViewId) { log.trace("Executing findEntityViewById [{}]", entityViewId); validateId(entityViewId, INCORRECT_ENTITY_VIEW_ID + entityViewId); - return entityViewDao.findById(entityViewId.getId()); + return entityViewDao.findById(tenantId, entityViewId.getId()); } @Cacheable(cacheNames = ENTITY_VIEW_CACHE, key = "{#tenantId, #name}") @@ -187,15 +187,15 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti } @Override - public ListenableFuture> findEntityViewsByQuery(EntityViewSearchQuery query) { - ListenableFuture> relations = relationService.findByQuery(query.toEntitySearchQuery()); + public ListenableFuture> findEntityViewsByQuery(TenantId tenantId, EntityViewSearchQuery query) { + ListenableFuture> relations = relationService.findByQuery(tenantId, query.toEntitySearchQuery()); ListenableFuture> entityViews = Futures.transformAsync(relations, r -> { EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection(); List> futures = new ArrayList<>(); for (EntityRelation relation : r) { EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom(); if (entityId.getEntityType() == EntityType.ENTITY_VIEW) { - futures.add(findEntityViewByIdAsync(new EntityViewId(entityId.getId()))); + futures.add(findEntityViewByIdAsync(tenantId, new EntityViewId(entityId.getId()))); } } return Futures.successfulAsList(futures); @@ -213,10 +213,10 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti } @Override - public ListenableFuture findEntityViewByIdAsync(EntityViewId entityViewId) { + public ListenableFuture findEntityViewByIdAsync(TenantId tenantId, EntityViewId entityViewId) { log.trace("Executing findEntityViewById [{}]", entityViewId); validateId(entityViewId, INCORRECT_ENTITY_VIEW_ID + entityViewId); - return entityViewDao.findByIdAsync(entityViewId.getId()); + return entityViewDao.findByIdAsync(tenantId, entityViewId.getId()); } @Override @@ -253,21 +253,21 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti @CacheEvict(cacheNames = ENTITY_VIEW_CACHE, key = "{#entityViewId}") @Override - public void deleteEntityView(EntityViewId entityViewId) { + public void deleteEntityView(TenantId tenantId, EntityViewId entityViewId) { log.trace("Executing deleteEntityView [{}]", entityViewId); validateId(entityViewId, INCORRECT_ENTITY_VIEW_ID + entityViewId); - deleteEntityRelations(entityViewId); - EntityView entityView = entityViewDao.findById(entityViewId.getId()); + deleteEntityRelations(tenantId, entityViewId); + EntityView entityView = entityViewDao.findById(tenantId, entityViewId.getId()); cacheManager.getCache(ENTITY_VIEW_CACHE).evict(Arrays.asList(entityView.getTenantId(), entityView.getEntityId())); cacheManager.getCache(ENTITY_VIEW_CACHE).evict(Arrays.asList(entityView.getTenantId(), entityView.getName())); - entityViewDao.removeById(entityViewId.getId()); + entityViewDao.removeById(tenantId, entityViewId.getId()); } @Override public void deleteEntityViewsByTenantId(TenantId tenantId) { log.trace("Executing deleteEntityViewsByTenantId, tenantId [{}]", tenantId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); - tenantEntityViewRemover.removeEntities(tenantId); + tenantEntityViewRemover.removeEntities(tenantId, tenantId); } @Override @@ -286,7 +286,7 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti new DataValidator() { @Override - protected void validateCreate(EntityView entityView) { + protected void validateCreate(TenantId tenantId, EntityView entityView) { entityViewDao.findEntityViewByTenantIdAndName(entityView.getTenantId().getId(), entityView.getName()) .ifPresent(e -> { throw new DataValidationException("Entity view with such name already exists!"); @@ -294,7 +294,7 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti } @Override - protected void validateUpdate(EntityView entityView) { + protected void validateUpdate(TenantId tenantId, EntityView entityView) { entityViewDao.findEntityViewByTenantIdAndName(entityView.getTenantId().getId(), entityView.getName()) .ifPresent(e -> { if (!e.getUuidId().equals(entityView.getUuidId())) { @@ -304,7 +304,7 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti } @Override - protected void validateDataImpl(EntityView entityView) { + protected void validateDataImpl(TenantId tenantId, EntityView entityView) { if (StringUtils.isEmpty(entityView.getType())) { throw new DataValidationException("Entity View type should be specified!"); } @@ -314,7 +314,7 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti if (entityView.getTenantId() == null) { throw new DataValidationException("Entity view should be assigned to tenant!"); } else { - Tenant tenant = tenantDao.findById(entityView.getTenantId().getId()); + Tenant tenant = tenantDao.findById(tenantId, entityView.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("Entity view is referencing to non-existent tenant!"); } @@ -322,7 +322,7 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti if (entityView.getCustomerId() == null) { entityView.setCustomerId(new CustomerId(NULL_UUID)); } else if (!entityView.getCustomerId().getId().equals(NULL_UUID)) { - Customer customer = customerDao.findById(entityView.getCustomerId().getId()); + Customer customer = customerDao.findById(tenantId, entityView.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("Can't assign entity view to non-existent customer!"); } @@ -333,36 +333,27 @@ public class EntityViewServiceImpl extends AbstractEntityService implements Enti } }; - private PaginatedRemover tenantEntityViewRemover = - new PaginatedRemover() { - - @Override - protected List findEntities(TenantId id, TextPageLink pageLink) { - return entityViewDao.findEntityViewsByTenantId(id.getId(), pageLink); - } - - @Override - protected void removeEntity(EntityView entity) { - deleteEntityView(new EntityViewId(entity.getUuidId())); - } - }; - - private class CustomerEntityViewsUnAssigner extends PaginatedRemover { - - private TenantId tenantId; + private PaginatedRemover tenantEntityViewRemover = new PaginatedRemover() { + @Override + protected List findEntities(TenantId tenantId, TenantId id, TextPageLink pageLink) { + return entityViewDao.findEntityViewsByTenantId(id.getId(), pageLink); + } - CustomerEntityViewsUnAssigner(TenantId tenantId) { - this.tenantId = tenantId; + @Override + protected void removeEntity(TenantId tenantId, EntityView entity) { + deleteEntityView(tenantId, new EntityViewId(entity.getUuidId())); } + }; + private PaginatedRemover customerEntityViewsUnAssigner = new PaginatedRemover() { @Override - protected List findEntities(CustomerId id, TextPageLink pageLink) { + protected List findEntities(TenantId tenantId, CustomerId id, TextPageLink pageLink) { return entityViewDao.findEntityViewsByTenantIdAndCustomerId(tenantId.getId(), id.getId(), pageLink); } @Override - protected void removeEntity(EntityView entity) { - unassignEntityViewFromCustomer(new EntityViewId(entity.getUuidId())); + protected void removeEntity(TenantId tenantId, EntityView entity) { + unassignEntityViewFromCustomer(tenantId, new EntityViewId(entity.getUuidId())); } - } + }; } diff --git a/dao/src/main/java/org/thingsboard/server/dao/event/BaseEventService.java b/dao/src/main/java/org/thingsboard/server/dao/event/BaseEventService.java index 7dddec17ef..3bc6aaeb54 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/event/BaseEventService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/event/BaseEventService.java @@ -40,19 +40,19 @@ public class BaseEventService implements EventService { @Override public Event save(Event event) { - eventValidator.validate(event); - return eventDao.save(event); + eventValidator.validate(event, Event::getTenantId); + return eventDao.save(event.getTenantId(), event); } @Override public ListenableFuture saveAsync(Event event) { - eventValidator.validate(event); + eventValidator.validate(event, Event::getTenantId); return eventDao.saveAsync(event); } @Override public Optional saveIfNotExists(Event event) { - eventValidator.validate(event); + eventValidator.validate(event, Event::getTenantId); if (StringUtils.isEmpty(event.getUid())) { throw new DataValidationException("Event uid should be specified!."); } @@ -97,7 +97,7 @@ public class BaseEventService implements EventService { private DataValidator eventValidator = new DataValidator() { @Override - protected void validateDataImpl(Event event) { + protected void validateDataImpl(TenantId tenantId, Event event) { if (event.getEntityId() == null) { throw new DataValidationException("Entity id should be specified!."); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/event/CassandraBaseEventDao.java b/dao/src/main/java/org/thingsboard/server/dao/event/CassandraBaseEventDao.java index 7549e40108..60af00543f 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/event/CassandraBaseEventDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/event/CassandraBaseEventDao.java @@ -64,7 +64,7 @@ public class CassandraBaseEventDao extends CassandraAbstractSearchTimeDao> optionalSave = saveAsync(new EventEntity(event), false); + ListenableFuture> optionalSave = saveAsync(event.getTenantId(), new EventEntity(event), false); return Futures.transform(optionalSave, opt -> opt.orElse(null)); } @@ -98,7 +98,7 @@ public class CassandraBaseEventDao extends CassandraAbstractSearchTimeDao findEvents(UUID tenantId, EntityId entityId, TimePageLink pageLink) { log.trace("Try to find events by tenant [{}], entity [{}]and pageLink [{}]", tenantId, entityId, pageLink); - List entities = findPageWithTimeSearch(EVENT_BY_ID_VIEW_NAME, + List entities = findPageWithTimeSearch(new TenantId(tenantId), EVENT_BY_ID_VIEW_NAME, Arrays.asList(eq(ModelConstants.EVENT_TENANT_ID_PROPERTY, tenantId), eq(ModelConstants.EVENT_ENTITY_TYPE_PROPERTY, entityId.getEntityType()), eq(ModelConstants.EVENT_ENTITY_ID_PROPERTY, entityId.getId())), @@ -135,7 +135,7 @@ public class CassandraBaseEventDao extends CassandraAbstractSearchTimeDao findEvents(UUID tenantId, EntityId entityId, String eventType, TimePageLink pageLink) { log.trace("Try to find events by tenant [{}], entity [{}], type [{}] and pageLink [{}]", tenantId, entityId, eventType, pageLink); - List entities = findPageWithTimeSearch(EVENT_BY_TYPE_AND_ID_VIEW_NAME, + List entities = findPageWithTimeSearch(new TenantId(tenantId), EVENT_BY_TYPE_AND_ID_VIEW_NAME, Arrays.asList(eq(ModelConstants.EVENT_TENANT_ID_PROPERTY, tenantId), eq(ModelConstants.EVENT_ENTITY_TYPE_PROPERTY, entityId.getEntityType()), eq(ModelConstants.EVENT_ENTITY_ID_PROPERTY, entityId.getId()), @@ -158,19 +158,19 @@ public class CassandraBaseEventDao extends CassandraAbstractSearchTimeDao entities = findListByStatement(query); + List entities = findListByStatement(new TenantId(tenantId), query); return DaoUtil.convertDataList(entities); } - private Optional save(EventEntity entity, boolean ifNotExists) { + private Optional save(TenantId tenantId, EventEntity entity, boolean ifNotExists) { try { - return saveAsync(entity, ifNotExists).get(); + return saveAsync(tenantId, entity, ifNotExists).get(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException("Could not save EventEntity", e); } } - private ListenableFuture> saveAsync(EventEntity entity, boolean ifNotExists) { + private ListenableFuture> saveAsync(TenantId tenantId, EventEntity entity, boolean ifNotExists) { if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } @@ -185,7 +185,7 @@ public class CassandraBaseEventDao extends CassandraAbstractSearchTimeDao { if (rs.wasApplied()) { return Optional.of(DaoUtil.getData(entity)); diff --git a/dao/src/main/java/org/thingsboard/server/dao/event/EventDao.java b/dao/src/main/java/org/thingsboard/server/dao/event/EventDao.java index 9469c61f63..473a00cf7c 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/event/EventDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/event/EventDao.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.event; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.Event; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.dao.Dao; @@ -36,7 +37,7 @@ public interface EventDao extends Dao { * @param event the event object * @return saved event object */ - Event save(Event event); + Event save(TenantId tenantId, Event event); /** * Save or update event object async diff --git a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractDao.java b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractDao.java index b38110b460..1a419df9a1 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractDao.java @@ -27,6 +27,7 @@ import com.datastax.driver.core.TypeCodec; import com.datastax.driver.core.exceptions.CodecNotFoundException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.cassandra.CassandraCluster; import org.thingsboard.server.dao.model.type.AuthorityCodec; import org.thingsboard.server.dao.model.type.ComponentLifecycleStateCodec; @@ -84,37 +85,37 @@ public abstract class CassandraAbstractDao { } } - protected ResultSet executeRead(Statement statement) { - return execute(statement, defaultReadLevel); + protected ResultSet executeRead(TenantId tenantId, Statement statement) { + return execute(tenantId, statement, defaultReadLevel); } - protected ResultSet executeWrite(Statement statement) { - return execute(statement, defaultWriteLevel); + protected ResultSet executeWrite(TenantId tenantId, Statement statement) { + return execute(tenantId, statement, defaultWriteLevel); } - protected ResultSetFuture executeAsyncRead(Statement statement) { - return executeAsync(statement, defaultReadLevel); + protected ResultSetFuture executeAsyncRead(TenantId tenantId, Statement statement) { + return executeAsync(tenantId, statement, defaultReadLevel); } - protected ResultSetFuture executeAsyncWrite(Statement statement) { - return executeAsync(statement, defaultWriteLevel); + protected ResultSetFuture executeAsyncWrite(TenantId tenantId, Statement statement) { + return executeAsync(tenantId, statement, defaultWriteLevel); } - private ResultSet execute(Statement statement, ConsistencyLevel level) { + private ResultSet execute(TenantId tenantId, Statement statement, ConsistencyLevel level) { if (log.isDebugEnabled()) { log.debug("Execute cassandra statement {}", statementToString(statement)); } - return executeAsync(statement, level).getUninterruptibly(); + return executeAsync(tenantId, statement, level).getUninterruptibly(); } - private ResultSetFuture executeAsync(Statement statement, ConsistencyLevel level) { + private ResultSetFuture executeAsync(TenantId tenantId, Statement statement, ConsistencyLevel level) { if (log.isDebugEnabled()) { log.debug("Execute cassandra async statement {}", statementToString(statement)); } if (statement.getConsistencyLevel() == null) { statement.setConsistencyLevel(level); } - return rateLimiter.submit(new CassandraStatementTask(getSession(), statement)); + return rateLimiter.submit(new CassandraStatementTask(tenantId, getSession(), statement)); } private static String statementToString(Statement statement) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractModelDao.java b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractModelDao.java index 000316b4ff..2605826c14 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractModelDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractModelDao.java @@ -27,6 +27,7 @@ import com.google.common.base.Function; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import lombok.extern.slf4j.Slf4j; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.Dao; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.BaseEntity; @@ -56,11 +57,11 @@ public abstract class CassandraAbstractModelDao, D> exte return cluster.getMapper(getColumnFamilyClass()); } - protected List findListByStatement(Statement statement) { + protected List findListByStatement(TenantId tenantId, Statement statement) { List list = Collections.emptyList(); if (statement != null) { statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel()); - ResultSet resultSet = executeRead(statement); + ResultSet resultSet = executeRead(tenantId, statement); Result result = getMapper().map(resultSet); if (result != null) { list = result.all(); @@ -69,10 +70,10 @@ public abstract class CassandraAbstractModelDao, D> exte return list; } - protected ListenableFuture> findListByStatementAsync(Statement statement) { + protected ListenableFuture> findListByStatementAsync(TenantId tenantId, Statement statement) { if (statement != null) { statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel()); - ResultSetFuture resultSetFuture = executeAsyncRead(statement); + ResultSetFuture resultSetFuture = executeAsyncRead(tenantId, statement); return Futures.transform(resultSetFuture, new Function>() { @Nullable @Override @@ -90,11 +91,11 @@ public abstract class CassandraAbstractModelDao, D> exte return Futures.immediateFuture(Collections.emptyList()); } - protected E findOneByStatement(Statement statement) { + protected E findOneByStatement(TenantId tenantId, Statement statement) { E object = null; if (statement != null) { statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel()); - ResultSet resultSet = executeRead(statement); + ResultSet resultSet = executeRead(tenantId, statement); Result result = getMapper().map(resultSet); if (result != null) { object = result.one(); @@ -103,10 +104,10 @@ public abstract class CassandraAbstractModelDao, D> exte return object; } - protected ListenableFuture findOneByStatementAsync(Statement statement) { + protected ListenableFuture findOneByStatementAsync(TenantId tenantId, Statement statement) { if (statement != null) { statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel()); - ResultSetFuture resultSetFuture = executeAsyncRead(statement); + ResultSetFuture resultSetFuture = executeAsyncRead(tenantId, statement); return Futures.transform(resultSetFuture, new Function() { @Nullable @Override @@ -128,16 +129,16 @@ public abstract class CassandraAbstractModelDao, D> exte return getMapper().saveQuery(dto); } - protected EntityResultSet saveWithResult(E entity) { + protected EntityResultSet saveWithResult(TenantId tenantId, E entity) { log.debug("Save entity {}", entity); if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } else if (isDeleteOnSave()) { - removeById(entity.getId()); + removeById(tenantId, entity.getId()); } Statement saveStatement = getSaveQuery(entity); saveStatement.setConsistencyLevel(cluster.getDefaultWriteConsistencyLevel()); - ResultSet resultSet = executeWrite(saveStatement); + ResultSet resultSet = executeWrite(tenantId, saveStatement); return new EntityResultSet<>(resultSet, entity); } @@ -146,7 +147,7 @@ public abstract class CassandraAbstractModelDao, D> exte } @Override - public D save(D domain) { + public D save(TenantId tenantId, D domain) { E entity; try { entity = getColumnFamilyClass().getConstructor(domain.getClass()).newInstance(domain); @@ -156,48 +157,39 @@ public abstract class CassandraAbstractModelDao, D> exte } entity = updateSearchTextIfPresent(entity); log.debug("Saving entity {}", entity); - entity = saveWithResult(entity).getEntity(); + entity = saveWithResult(tenantId, entity).getEntity(); return DaoUtil.getData(entity); } @Override - public D findById(UUID key) { + public D findById(TenantId tenantId, UUID key) { log.debug("Get entity by key {}", key); Select.Where query = select().from(getColumnFamilyName()).where(eq(ModelConstants.ID_PROPERTY, key)); log.trace("Execute query {}", query); - E entity = findOneByStatement(query); + E entity = findOneByStatement(tenantId, query); return DaoUtil.getData(entity); } @Override - public ListenableFuture findByIdAsync(UUID key) { + public ListenableFuture findByIdAsync(TenantId tenantId, UUID key) { log.debug("Get entity by key {}", key); Select.Where query = select().from(getColumnFamilyName()).where(eq(ModelConstants.ID_PROPERTY, key)); log.trace("Execute query {}", query); - return findOneByStatementAsync(query); + return findOneByStatementAsync(tenantId, query); } @Override - public boolean removeById(UUID key) { + public boolean removeById(TenantId tenantId, UUID key) { Statement delete = QueryBuilder.delete().all().from(getColumnFamilyName()).where(eq(ModelConstants.ID_PROPERTY, key)); log.debug("Remove request: {}", delete.toString()); - return executeWrite(delete).wasApplied(); + return executeWrite(tenantId, delete).wasApplied(); } @Override - public List find() { + public List find(TenantId tenantId) { log.debug("Get all entities from column family {}", getColumnFamilyName()); - List entities = findListByStatement(QueryBuilder.select().all().from(getColumnFamilyName()).setConsistencyLevel(cluster.getDefaultReadConsistencyLevel())); + List entities = findListByStatement(tenantId, QueryBuilder.select().all().from(getColumnFamilyName()).setConsistencyLevel(cluster.getDefaultReadConsistencyLevel())); return DaoUtil.convertDataList(entities); } - - protected static Function, T> toDataFunction() { - return new Function, T>() { - @Nullable - @Override - public T apply(@Nullable BaseEntity entity) { - return entity != null ? entity.toData() : null; - } - }; - } + } diff --git a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractSearchTextDao.java b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractSearchTextDao.java index 5130f311fd..e5712d147b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractSearchTextDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractSearchTextDao.java @@ -21,6 +21,7 @@ import com.datastax.driver.core.querybuilder.Select; import com.datastax.driver.core.querybuilder.Select.Where; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.dao.model.SearchTextEntity; @@ -43,38 +44,38 @@ public abstract class CassandraAbstractSearchTextDao findPageWithTextSearch(String searchView, List clauses, TextPageLink pageLink) { + protected List findPageWithTextSearch(TenantId tenantId, String searchView, List clauses, TextPageLink pageLink) { Select select = select().from(searchView); Where query = select.where(); for (Clause clause : clauses) { query.and(clause); - } + } query.limit(pageLink.getLimit()); if (!StringUtils.isEmpty(pageLink.getTextOffset())) { query.and(eq(ModelConstants.SEARCH_TEXT_PROPERTY, pageLink.getTextOffset())); query.and(QueryBuilder.lt(ModelConstants.ID_PROPERTY, pageLink.getIdOffset())); - List result = findListByStatement(query); + List result = findListByStatement(tenantId, query); if (result.size() < pageLink.getLimit()) { select = select().from(searchView); query = select.where(); for (Clause clause : clauses) { query.and(clause); - } + } query.and(QueryBuilder.gt(ModelConstants.SEARCH_TEXT_PROPERTY, pageLink.getTextOffset())); if (!StringUtils.isEmpty(pageLink.getTextSearch())) { query.and(QueryBuilder.lt(ModelConstants.SEARCH_TEXT_PROPERTY, pageLink.getTextSearchBound())); } int limit = pageLink.getLimit() - result.size(); query.limit(limit); - result.addAll(findListByStatement(query)); + result.addAll(findListByStatement(tenantId, query)); } return result; } else if (!StringUtils.isEmpty(pageLink.getTextSearch())) { query.and(QueryBuilder.gte(ModelConstants.SEARCH_TEXT_PROPERTY, pageLink.getTextSearch())); query.and(QueryBuilder.lt(ModelConstants.SEARCH_TEXT_PROPERTY, pageLink.getTextSearchBound())); - return findListByStatement(query); + return findListByStatement(tenantId, query); } else { - return findListByStatement(query); + return findListByStatement(tenantId, query); } } diff --git a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractSearchTimeDao.java b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractSearchTimeDao.java index c79381b3e4..baeae0ca23 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractSearchTimeDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraAbstractSearchTimeDao.java @@ -21,6 +21,7 @@ import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.querybuilder.Select; import com.datastax.driver.core.querybuilder.Select.Where; import com.datastax.driver.core.utils.UUIDs; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.dao.model.BaseEntity; import org.thingsboard.server.dao.model.ModelConstants; @@ -35,24 +36,24 @@ import static com.datastax.driver.core.querybuilder.QueryBuilder.select; public abstract class CassandraAbstractSearchTimeDao, D> extends CassandraAbstractModelDao { - protected List findPageWithTimeSearch(String searchView, List clauses, TimePageLink pageLink) { - return findPageWithTimeSearch(searchView, clauses, Collections.emptyList(), pageLink); + protected List findPageWithTimeSearch(TenantId tenantId, String searchView, List clauses, TimePageLink pageLink) { + return findPageWithTimeSearch(tenantId, searchView, clauses, Collections.emptyList(), pageLink); } - protected List findPageWithTimeSearch(String searchView, List clauses, Ordering ordering, TimePageLink pageLink) { - return findPageWithTimeSearch(searchView, clauses, Collections.singletonList(ordering), pageLink); + protected List findPageWithTimeSearch(TenantId tenantId, String searchView, List clauses, Ordering ordering, TimePageLink pageLink) { + return findPageWithTimeSearch(tenantId, searchView, clauses, Collections.singletonList(ordering), pageLink); } - protected List findPageWithTimeSearch(String searchView, List clauses, List topLevelOrderings, TimePageLink pageLink) { - return findPageWithTimeSearch(searchView, clauses, topLevelOrderings, pageLink, ModelConstants.ID_PROPERTY); + protected List findPageWithTimeSearch(TenantId tenantId, String searchView, List clauses, List topLevelOrderings, TimePageLink pageLink) { + return findPageWithTimeSearch(tenantId, searchView, clauses, topLevelOrderings, pageLink, ModelConstants.ID_PROPERTY); } - protected List findPageWithTimeSearch(String searchView, List clauses, TimePageLink pageLink, String idColumn) { - return findPageWithTimeSearch(searchView, clauses, Collections.emptyList(), pageLink, idColumn); + protected List findPageWithTimeSearch(TenantId tenantId, String searchView, List clauses, TimePageLink pageLink, String idColumn) { + return findPageWithTimeSearch(tenantId, searchView, clauses, Collections.emptyList(), pageLink, idColumn); } - protected List findPageWithTimeSearch(String searchView, List clauses, List topLevelOrderings, TimePageLink pageLink, String idColumn) { - return findListByStatement(buildQuery(searchView, clauses, topLevelOrderings, pageLink, idColumn)); + protected List findPageWithTimeSearch(TenantId tenantId, String searchView, List clauses, List topLevelOrderings, TimePageLink pageLink, String idColumn) { + return findListByStatement(tenantId, buildQuery(searchView, clauses, topLevelOrderings, pageLink, idColumn)); } public static Where buildQuery(String searchView, List clauses, TimePageLink pageLink, String idColumn) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraBufferedRateExecutor.java b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraBufferedRateExecutor.java index a3490bffdd..05370efce3 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraBufferedRateExecutor.java +++ b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraBufferedRateExecutor.java @@ -22,11 +22,16 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.tools.TbRateLimits; import org.thingsboard.server.dao.util.AbstractBufferedRateExecutor; import org.thingsboard.server.dao.util.AsyncTaskContext; import org.thingsboard.server.dao.util.NoSqlAnyDao; import javax.annotation.PreDestroy; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; /** * Created by ashvayka on 24.10.18. @@ -42,17 +47,19 @@ public class CassandraBufferedRateExecutor extends AbstractBufferedRateExecutor< @Value("${cassandra.query.permit_max_wait_time}") long maxWaitTime, @Value("${cassandra.query.dispatcher_threads:2}") int dispatcherThreads, @Value("${cassandra.query.callback_threads:2}") int callbackThreads, - @Value("${cassandra.query.poll_ms:50}") long pollMs) { - super(queueLimit, concurrencyLimit, maxWaitTime, dispatcherThreads, callbackThreads, pollMs); + @Value("${cassandra.query.poll_ms:50}") long pollMs, + @Value("${cassandra.query.tenant_rate_limits.enabled}") boolean tenantRateLimitsEnabled, + @Value("${cassandra.query.tenant_rate_limits.configuration}") String tenantRateLimitsConfiguration) { + super(queueLimit, concurrencyLimit, maxWaitTime, dispatcherThreads, callbackThreads, pollMs, tenantRateLimitsEnabled, tenantRateLimitsConfiguration); } @Scheduled(fixedDelayString = "${cassandra.query.rate_limit_print_interval_ms}") public void printStats() { - log.info("Permits queueSize [{}] totalAdded [{}] totalLaunched [{}] totalReleased [{}] totalFailed [{}] totalExpired [{}] totalRejected [{}] currBuffer [{}] ", + log.info("Permits queueSize [{}] totalAdded [{}] totalLaunched [{}] totalReleased [{}] totalFailed [{}] totalExpired [{}] totalRejected [{}] totalRateLimited [{}] currBuffer [{}] ", getQueueSize(), totalAdded.getAndSet(0), totalLaunched.getAndSet(0), totalReleased.getAndSet(0), totalFailed.getAndSet(0), totalExpired.getAndSet(0), totalRejected.getAndSet(0), - concurrencyLevel.get()); + totalRateLimited.getAndSet(0), concurrencyLevel.get()); } @PreDestroy diff --git a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraStatementTask.java b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraStatementTask.java index 19e56402db..091781fd81 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraStatementTask.java +++ b/dao/src/main/java/org/thingsboard/server/dao/nosql/CassandraStatementTask.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.nosql; import com.datastax.driver.core.Session; import com.datastax.driver.core.Statement; import lombok.Data; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.util.AsyncTask; /** @@ -26,6 +27,7 @@ import org.thingsboard.server.dao.util.AsyncTask; @Data public class CassandraStatementTask implements AsyncTask { + private final TenantId tenantId; private final Session session; private final Statement statement; diff --git a/dao/src/main/java/org/thingsboard/server/dao/relation/BaseRelationDao.java b/dao/src/main/java/org/thingsboard/server/dao/relation/BaseRelationDao.java index ba6d09d754..ab2b47e9cf 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/relation/BaseRelationDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/relation/BaseRelationDao.java @@ -29,6 +29,7 @@ import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.EntityIdFactory; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.data.relation.RelationTypeGroup; @@ -83,45 +84,45 @@ public class BaseRelationDao extends CassandraAbstractAsyncDao implements Relati } @Override - public ListenableFuture> findAllByFrom(EntityId from, RelationTypeGroup typeGroup) { + public ListenableFuture> findAllByFrom(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup) { BoundStatement stmt = getFindAllByFromStmt().bind() .setUUID(0, from.getId()) .setString(1, from.getEntityType().name()) .set(2, typeGroup, relationTypeGroupCodec); - return executeAsyncRead(from, stmt); + return executeAsyncRead(tenantId, from, stmt); } @Override - public ListenableFuture> findAllByFromAndType(EntityId from, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture> findAllByFromAndType(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup) { BoundStatement stmt = getFindAllByFromAndTypeStmt().bind() .setUUID(0, from.getId()) .setString(1, from.getEntityType().name()) .set(2, typeGroup, relationTypeGroupCodec) .setString(3, relationType); - return executeAsyncRead(from, stmt); + return executeAsyncRead(tenantId, from, stmt); } @Override - public ListenableFuture> findAllByTo(EntityId to, RelationTypeGroup typeGroup) { + public ListenableFuture> findAllByTo(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup) { BoundStatement stmt = getFindAllByToStmt().bind() .setUUID(0, to.getId()) .setString(1, to.getEntityType().name()) .set(2, typeGroup, relationTypeGroupCodec); - return executeAsyncRead(to, stmt); + return executeAsyncRead(tenantId, to, stmt); } @Override - public ListenableFuture> findAllByToAndType(EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture> findAllByToAndType(TenantId tenantId, EntityId to, String relationType, RelationTypeGroup typeGroup) { BoundStatement stmt = getFindAllByToAndTypeStmt().bind() .setUUID(0, to.getId()) .setString(1, to.getEntityType().name()) .set(2, typeGroup, relationTypeGroupCodec) .setString(3, relationType); - return executeAsyncRead(to, stmt); + return executeAsyncRead(tenantId, to, stmt); } @Override - public ListenableFuture checkRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture checkRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { BoundStatement stmt = getCheckRelationStmt().bind() .setUUID(0, from.getId()) .setString(1, from.getEntityType().name()) @@ -129,11 +130,11 @@ public class BaseRelationDao extends CassandraAbstractAsyncDao implements Relati .setString(3, to.getEntityType().name()) .set(4, typeGroup, relationTypeGroupCodec) .setString(5, relationType); - return getFuture(executeAsyncRead(stmt), rs -> rs != null ? rs.one() != null : false); + return getFuture(executeAsyncRead(tenantId, stmt), rs -> rs != null ? rs.one() != null : false); } @Override - public ListenableFuture getRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture getRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { BoundStatement stmt = getCheckRelationStmt().bind() .setUUID(0, from.getId()) .setString(1, from.getEntityType().name()) @@ -141,24 +142,24 @@ public class BaseRelationDao extends CassandraAbstractAsyncDao implements Relati .setString(3, to.getEntityType().name()) .set(4, typeGroup, relationTypeGroupCodec) .setString(5, relationType); - return getFuture(executeAsyncRead(stmt), rs -> rs != null ? getEntityRelation(rs.one()) : null); + return getFuture(executeAsyncRead(tenantId, stmt), rs -> rs != null ? getEntityRelation(rs.one()) : null); } @Override - public boolean saveRelation(EntityRelation relation) { - BoundStatement stmt = getSaveRelationStatement(relation); - ResultSet rs = executeWrite(stmt); + public boolean saveRelation(TenantId tenantId, EntityRelation relation) { + BoundStatement stmt = getSaveRelationStatement(tenantId, relation); + ResultSet rs = executeWrite(tenantId, stmt); return rs.wasApplied(); } @Override - public ListenableFuture saveRelationAsync(EntityRelation relation) { - BoundStatement stmt = getSaveRelationStatement(relation); - ResultSetFuture future = executeAsyncWrite(stmt); + public ListenableFuture saveRelationAsync(TenantId tenantId, EntityRelation relation) { + BoundStatement stmt = getSaveRelationStatement(tenantId, relation); + ResultSetFuture future = executeAsyncWrite(tenantId, stmt); return getBooleanListenableFuture(future); } - private BoundStatement getSaveRelationStatement(EntityRelation relation) { + private BoundStatement getSaveRelationStatement(TenantId tenantId, EntityRelation relation) { BoundStatement stmt = getSaveStmt().bind() .setUUID(0, relation.getFrom().getId()) .setString(1, relation.getFrom().getEntityType().name()) @@ -171,30 +172,30 @@ public class BaseRelationDao extends CassandraAbstractAsyncDao implements Relati } @Override - public boolean deleteRelation(EntityRelation relation) { - return deleteRelation(relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); + public boolean deleteRelation(TenantId tenantId, EntityRelation relation) { + return deleteRelation(tenantId, relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); } @Override - public ListenableFuture deleteRelationAsync(EntityRelation relation) { - return deleteRelationAsync(relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); + public ListenableFuture deleteRelationAsync(TenantId tenantId, EntityRelation relation) { + return deleteRelationAsync(tenantId, relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); } @Override - public boolean deleteRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { - BoundStatement stmt = getDeleteRelationStatement(from, to, relationType, typeGroup); - ResultSet rs = executeWrite(stmt); + public boolean deleteRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + BoundStatement stmt = getDeleteRelationStatement(tenantId, from, to, relationType, typeGroup); + ResultSet rs = executeWrite(tenantId, stmt); return rs.wasApplied(); } @Override - public ListenableFuture deleteRelationAsync(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { - BoundStatement stmt = getDeleteRelationStatement(from, to, relationType, typeGroup); - ResultSetFuture future = executeAsyncWrite(stmt); + public ListenableFuture deleteRelationAsync(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + BoundStatement stmt = getDeleteRelationStatement(tenantId, from, to, relationType, typeGroup); + ResultSetFuture future = executeAsyncWrite(tenantId, stmt); return getBooleanListenableFuture(future); } - private BoundStatement getDeleteRelationStatement(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + private BoundStatement getDeleteRelationStatement(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { BoundStatement stmt = getDeleteStmt().bind() .setUUID(0, from.getId()) .setString(1, from.getEntityType().name()) @@ -206,26 +207,26 @@ public class BaseRelationDao extends CassandraAbstractAsyncDao implements Relati } @Override - public boolean deleteOutboundRelations(EntityId entity) { + public boolean deleteOutboundRelations(TenantId tenantId, EntityId entity) { BoundStatement stmt = getDeleteAllByEntityStmt().bind() .setUUID(0, entity.getId()) .setString(1, entity.getEntityType().name()); - ResultSet rs = executeWrite(stmt); + ResultSet rs = executeWrite(tenantId, stmt); return rs.wasApplied(); } @Override - public ListenableFuture deleteOutboundRelationsAsync(EntityId entity) { + public ListenableFuture deleteOutboundRelationsAsync(TenantId tenantId, EntityId entity) { BoundStatement stmt = getDeleteAllByEntityStmt().bind() .setUUID(0, entity.getId()) .setString(1, entity.getEntityType().name()); - ResultSetFuture future = executeAsyncWrite(stmt); + ResultSetFuture future = executeAsyncWrite(tenantId, stmt); return getBooleanListenableFuture(future); } @Override - public ListenableFuture> findRelations(EntityId from, String relationType, RelationTypeGroup typeGroup, EntityType childType, TimePageLink pageLink) { + public ListenableFuture> findRelations(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup, EntityType childType, TimePageLink pageLink) { Select.Where query = CassandraAbstractSearchTimeDao.buildQuery(ModelConstants.RELATION_BY_TYPE_AND_CHILD_TYPE_VIEW_NAME, Arrays.asList(eq(ModelConstants.RELATION_FROM_ID_PROPERTY, from.getId()), eq(ModelConstants.RELATION_FROM_TYPE_PROPERTY, from.getEntityType().name()), @@ -241,7 +242,7 @@ public class BaseRelationDao extends CassandraAbstractAsyncDao implements Relati QueryBuilder.asc(ModelConstants.RELATION_TO_TYPE_PROPERTY) ), pageLink, ModelConstants.RELATION_TO_ID_PROPERTY); - return getFuture(executeAsyncRead(query), this::getEntityRelations); + return getFuture(executeAsyncRead(tenantId, query), this::getEntityRelations); } private PreparedStatement getSaveStmt() { @@ -347,9 +348,9 @@ public class BaseRelationDao extends CassandraAbstractAsyncDao implements Relati return EntityIdFactory.getByTypeAndUuid(row.getString(typeColumn), row.getUUID(uuidColumn)); } - private ListenableFuture> executeAsyncRead(EntityId from, BoundStatement stmt) { + private ListenableFuture> executeAsyncRead(TenantId tenantId, EntityId from, BoundStatement stmt) { log.debug("Generated query [{}] for entity {}", stmt, from); - return getFuture(executeAsyncRead(stmt), rs -> getEntityRelations(rs)); + return getFuture(executeAsyncRead(tenantId, stmt), rs -> getEntityRelations(rs)); } private ListenableFuture getBooleanListenableFuture(ResultSetFuture rsFuture) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/relation/BaseRelationService.java b/dao/src/main/java/org/thingsboard/server/dao/relation/BaseRelationService.java index 55c5987c74..f3db254f0d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/relation/BaseRelationService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/relation/BaseRelationService.java @@ -26,7 +26,9 @@ import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.data.relation.EntityRelationInfo; import org.thingsboard.server.common.data.relation.EntityRelationsQuery; @@ -66,27 +68,27 @@ public class BaseRelationService implements RelationService { private CacheManager cacheManager; @Override - public ListenableFuture checkRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture checkRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { log.trace("Executing checkRelation [{}][{}][{}][{}]", from, to, relationType, typeGroup); validate(from, to, relationType, typeGroup); - return relationDao.checkRelation(from, to, relationType, typeGroup); + return relationDao.checkRelation(tenantId, from, to, relationType, typeGroup); } @Cacheable(cacheNames = RELATIONS_CACHE, key = "{#from, #to, #relationType, #typeGroup}") @Override - public EntityRelation getRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public EntityRelation getRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { try { - return getRelationAsync(from, to, relationType, typeGroup).get(); + return getRelationAsync(tenantId, from, to, relationType, typeGroup).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } @Override - public ListenableFuture getRelationAsync(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture getRelationAsync(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { log.trace("Executing EntityRelation [{}][{}][{}][{}]", from, to, relationType, typeGroup); validate(from, to, relationType, typeGroup); - return relationDao.getRelation(from, to, relationType, typeGroup); + return relationDao.getRelation(tenantId, from, to, relationType, typeGroup); } @Caching(evict = { @@ -97,10 +99,10 @@ public class BaseRelationService implements RelationService { @CacheEvict(cacheNames = RELATIONS_CACHE, key = "{#relation.to, #relation.type, #relation.typeGroup, 'TO'}") }) @Override - public boolean saveRelation(EntityRelation relation) { + public boolean saveRelation(TenantId tenantId, EntityRelation relation) { log.trace("Executing saveRelation [{}]", relation); validate(relation); - return relationDao.saveRelation(relation); + return relationDao.saveRelation(tenantId, relation); } @Caching(evict = { @@ -111,10 +113,10 @@ public class BaseRelationService implements RelationService { @CacheEvict(cacheNames = RELATIONS_CACHE, key = "{#relation.to, #relation.type, #relation.typeGroup, 'TO'}") }) @Override - public ListenableFuture saveRelationAsync(EntityRelation relation) { + public ListenableFuture saveRelationAsync(TenantId tenantId, EntityRelation relation) { log.trace("Executing saveRelationAsync [{}]", relation); validate(relation); - return relationDao.saveRelationAsync(relation); + return relationDao.saveRelationAsync(tenantId, relation); } @Caching(evict = { @@ -125,10 +127,10 @@ public class BaseRelationService implements RelationService { @CacheEvict(cacheNames = RELATIONS_CACHE, key = "{#relation.to, #relation.type, #relation.typeGroup, 'TO'}") }) @Override - public boolean deleteRelation(EntityRelation relation) { + public boolean deleteRelation(TenantId tenantId, EntityRelation relation) { log.trace("Executing deleteRelation [{}]", relation); validate(relation); - return relationDao.deleteRelation(relation); + return relationDao.deleteRelation(tenantId, relation); } @Caching(evict = { @@ -139,10 +141,10 @@ public class BaseRelationService implements RelationService { @CacheEvict(cacheNames = RELATIONS_CACHE, key = "{#relation.to, #relation.type, #relation.typeGroup, 'TO'}") }) @Override - public ListenableFuture deleteRelationAsync(EntityRelation relation) { + public ListenableFuture deleteRelationAsync(TenantId tenantId, EntityRelation relation) { log.trace("Executing deleteRelationAsync [{}]", relation); validate(relation); - return relationDao.deleteRelationAsync(relation); + return relationDao.deleteRelationAsync(tenantId, relation); } @Caching(evict = { @@ -153,10 +155,10 @@ public class BaseRelationService implements RelationService { @CacheEvict(cacheNames = RELATIONS_CACHE, key = "{#to, #relationType, #typeGroup, 'TO'}") }) @Override - public boolean deleteRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public boolean deleteRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { log.trace("Executing deleteRelation [{}][{}][{}][{}]", from, to, relationType, typeGroup); validate(from, to, relationType, typeGroup); - return relationDao.deleteRelation(from, to, relationType, typeGroup); + return relationDao.deleteRelation(tenantId, from, to, relationType, typeGroup); } @Caching(evict = { @@ -167,69 +169,69 @@ public class BaseRelationService implements RelationService { @CacheEvict(cacheNames = RELATIONS_CACHE, key = "{#to, #relationType, #typeGroup, 'TO'}") }) @Override - public ListenableFuture deleteRelationAsync(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture deleteRelationAsync(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { log.trace("Executing deleteRelationAsync [{}][{}][{}][{}]", from, to, relationType, typeGroup); validate(from, to, relationType, typeGroup); - return relationDao.deleteRelationAsync(from, to, relationType, typeGroup); + return relationDao.deleteRelationAsync(tenantId, from, to, relationType, typeGroup); } @Override - public void deleteEntityRelations(EntityId entityId) { + public void deleteEntityRelations(TenantId tenantId, EntityId entityId) { try { - deleteEntityRelationsAsync(entityId).get(); + deleteEntityRelationsAsync(tenantId, entityId).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } @Override - public ListenableFuture deleteEntityRelationsAsync(EntityId entityId) { + public ListenableFuture deleteEntityRelationsAsync(TenantId tenantId, EntityId entityId) { Cache cache = cacheManager.getCache(RELATIONS_CACHE); log.trace("Executing deleteEntityRelationsAsync [{}]", entityId); validate(entityId); List>> inboundRelationsList = new ArrayList<>(); for (RelationTypeGroup typeGroup : RelationTypeGroup.values()) { - inboundRelationsList.add(relationDao.findAllByTo(entityId, typeGroup)); + inboundRelationsList.add(relationDao.findAllByTo(tenantId, entityId, typeGroup)); } ListenableFuture>> inboundRelations = Futures.allAsList(inboundRelationsList); List>> outboundRelationsList = new ArrayList<>(); for (RelationTypeGroup typeGroup : RelationTypeGroup.values()) { - outboundRelationsList.add(relationDao.findAllByFrom(entityId, typeGroup)); + outboundRelationsList.add(relationDao.findAllByFrom(tenantId, entityId, typeGroup)); } ListenableFuture>> outboundRelations = Futures.allAsList(outboundRelationsList); ListenableFuture> inboundDeletions = Futures.transformAsync(inboundRelations, relations -> { - List> results = deleteRelationGroupsAsync(relations, cache, true); + List> results = deleteRelationGroupsAsync(tenantId, relations, cache, true); return Futures.allAsList(results); }); ListenableFuture> outboundDeletions = Futures.transformAsync(outboundRelations, relations -> { - List> results = deleteRelationGroupsAsync(relations, cache, false); + List> results = deleteRelationGroupsAsync(tenantId, relations, cache, false); return Futures.allAsList(results); }); ListenableFuture>> deletionsFuture = Futures.allAsList(inboundDeletions, outboundDeletions); - return Futures.transform(Futures.transformAsync(deletionsFuture, (deletions) -> relationDao.deleteOutboundRelationsAsync(entityId)), result -> null); + return Futures.transform(Futures.transformAsync(deletionsFuture, (deletions) -> relationDao.deleteOutboundRelationsAsync(tenantId, entityId)), result -> null); } - private List> deleteRelationGroupsAsync(List> relations, Cache cache, boolean deleteFromDb) { + private List> deleteRelationGroupsAsync(TenantId tenantId, List> relations, Cache cache, boolean deleteFromDb) { List> results = new ArrayList<>(); for (List relationList : relations) { - relationList.forEach(relation -> results.add(deleteAsync(cache, relation, deleteFromDb))); + relationList.forEach(relation -> results.add(deleteAsync(tenantId, cache, relation, deleteFromDb))); } return results; } - private ListenableFuture deleteAsync(Cache cache, EntityRelation relation, boolean deleteFromDb) { + private ListenableFuture deleteAsync(TenantId tenantId, Cache cache, EntityRelation relation, boolean deleteFromDb) { cacheEviction(relation, cache); if (deleteFromDb) { - return relationDao.deleteRelationAsync(relation); + return relationDao.deleteRelationAsync(tenantId, relation); } else { return Futures.immediateFuture(false); } @@ -272,18 +274,18 @@ public class BaseRelationService implements RelationService { @Cacheable(cacheNames = RELATIONS_CACHE, key = "{#from, #typeGroup, 'FROM'}") @Override - public List findByFrom(EntityId from, RelationTypeGroup typeGroup) { + public List findByFrom(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup) { validate(from); validateTypeGroup(typeGroup); try { - return relationDao.findAllByFrom(from, typeGroup).get(); + return relationDao.findAllByFrom(tenantId, from, typeGroup).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } @Override - public ListenableFuture> findByFromAsync(EntityId from, RelationTypeGroup typeGroup) { + public ListenableFuture> findByFromAsync(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup) { log.trace("Executing findByFrom [{}][{}]", from, typeGroup); validate(from); validateTypeGroup(typeGroup); @@ -298,7 +300,7 @@ public class BaseRelationService implements RelationService { if (fromCache != null) { return Futures.immediateFuture(fromCache); } else { - ListenableFuture> relationsFuture = relationDao.findAllByFrom(from, typeGroup); + ListenableFuture> relationsFuture = relationDao.findAllByFrom(tenantId, from, typeGroup); Futures.addCallback(relationsFuture, new FutureCallback>() { @Override @@ -313,16 +315,16 @@ public class BaseRelationService implements RelationService { } @Override - public ListenableFuture> findInfoByFrom(EntityId from, RelationTypeGroup typeGroup) { + public ListenableFuture> findInfoByFrom(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup) { log.trace("Executing findInfoByFrom [{}][{}]", from, typeGroup); validate(from); validateTypeGroup(typeGroup); - ListenableFuture> relations = relationDao.findAllByFrom(from, typeGroup); + ListenableFuture> relations = relationDao.findAllByFrom(tenantId, from, typeGroup); return Futures.transformAsync(relations, relations1 -> { List> futures = new ArrayList<>(); relations1.forEach(relation -> - futures.add(fetchRelationInfoAsync(relation, + futures.add(fetchRelationInfoAsync(tenantId, relation, EntityRelation::getTo, EntityRelationInfo::setToName)) ); @@ -332,37 +334,37 @@ public class BaseRelationService implements RelationService { @Cacheable(cacheNames = RELATIONS_CACHE, key = "{#from, #relationType, #typeGroup, 'FROM'}") @Override - public List findByFromAndType(EntityId from, String relationType, RelationTypeGroup typeGroup) { + public List findByFromAndType(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup) { try { - return findByFromAndTypeAsync(from, relationType, typeGroup).get(); + return findByFromAndTypeAsync(tenantId, from, relationType, typeGroup).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } @Override - public ListenableFuture> findByFromAndTypeAsync(EntityId from, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture> findByFromAndTypeAsync(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup) { log.trace("Executing findByFromAndType [{}][{}][{}]", from, relationType, typeGroup); validate(from); validateType(relationType); validateTypeGroup(typeGroup); - return relationDao.findAllByFromAndType(from, relationType, typeGroup); + return relationDao.findAllByFromAndType(tenantId, from, relationType, typeGroup); } @Cacheable(cacheNames = RELATIONS_CACHE, key = "{#to, #typeGroup, 'TO'}") @Override - public List findByTo(EntityId to, RelationTypeGroup typeGroup) { + public List findByTo(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup) { validate(to); validateTypeGroup(typeGroup); try { - return relationDao.findAllByTo(to, typeGroup).get(); + return relationDao.findAllByTo(tenantId, to, typeGroup).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } @Override - public ListenableFuture> findByToAsync(EntityId to, RelationTypeGroup typeGroup) { + public ListenableFuture> findByToAsync(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup) { log.trace("Executing findByTo [{}][{}]", to, typeGroup); validate(to); validateTypeGroup(typeGroup); @@ -377,7 +379,7 @@ public class BaseRelationService implements RelationService { if (fromCache != null) { return Futures.immediateFuture(fromCache); } else { - ListenableFuture> relationsFuture = relationDao.findAllByTo(to, typeGroup); + ListenableFuture> relationsFuture = relationDao.findAllByTo(tenantId, to, typeGroup); Futures.addCallback(relationsFuture, new FutureCallback>() { @Override @@ -392,16 +394,16 @@ public class BaseRelationService implements RelationService { } @Override - public ListenableFuture> findInfoByTo(EntityId to, RelationTypeGroup typeGroup) { + public ListenableFuture> findInfoByTo(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup) { log.trace("Executing findInfoByTo [{}][{}]", to, typeGroup); validate(to); validateTypeGroup(typeGroup); - ListenableFuture> relations = relationDao.findAllByTo(to, typeGroup); + ListenableFuture> relations = relationDao.findAllByTo(tenantId, to, typeGroup); return Futures.transformAsync(relations, relations1 -> { List> futures = new ArrayList<>(); relations1.forEach(relation -> - futures.add(fetchRelationInfoAsync(relation, + futures.add(fetchRelationInfoAsync(tenantId, relation, EntityRelation::getFrom, EntityRelationInfo::setFromName)) ); @@ -409,10 +411,10 @@ public class BaseRelationService implements RelationService { }); } - private ListenableFuture fetchRelationInfoAsync(EntityRelation relation, + private ListenableFuture fetchRelationInfoAsync(TenantId tenantId, EntityRelation relation, Function entityIdGetter, BiConsumer entityNameSetter) { - ListenableFuture entityName = entityService.fetchEntityNameAsync(entityIdGetter.apply(relation)); + ListenableFuture entityName = entityService.fetchEntityNameAsync(tenantId, entityIdGetter.apply(relation)); return Futures.transform(entityName, entityName1 -> { EntityRelationInfo entityRelationInfo1 = new EntityRelationInfo(relation); entityNameSetter.accept(entityRelationInfo1, entityName1); @@ -422,25 +424,25 @@ public class BaseRelationService implements RelationService { @Cacheable(cacheNames = RELATIONS_CACHE, key = "{#to, #relationType, #typeGroup, 'TO'}") @Override - public List findByToAndType(EntityId to, String relationType, RelationTypeGroup typeGroup) { + public List findByToAndType(TenantId tenantId, EntityId to, String relationType, RelationTypeGroup typeGroup) { try { - return findByToAndTypeAsync(to, relationType, typeGroup).get(); + return findByToAndTypeAsync(tenantId, to, relationType, typeGroup).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } @Override - public ListenableFuture> findByToAndTypeAsync(EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture> findByToAndTypeAsync(TenantId tenantId, EntityId to, String relationType, RelationTypeGroup typeGroup) { log.trace("Executing findByToAndType [{}][{}][{}]", to, relationType, typeGroup); validate(to); validateType(relationType); validateTypeGroup(typeGroup); - return relationDao.findAllByToAndType(to, relationType, typeGroup); + return relationDao.findAllByToAndType(tenantId, to, relationType, typeGroup); } @Override - public ListenableFuture> findByQuery(EntityRelationsQuery query) { + public ListenableFuture> findByQuery(TenantId tenantId, EntityRelationsQuery query) { log.trace("Executing findByQuery [{}]", query); RelationsSearchParameters params = query.getParameters(); final List filters = query.getFilters(); @@ -451,7 +453,7 @@ public class BaseRelationService implements RelationService { int maxLvl = params.getMaxLevel() > 0 ? params.getMaxLevel() : Integer.MAX_VALUE; try { - ListenableFuture> relationSet = findRelationsRecursively(params.getEntityId(), params.getDirection(), params.getRelationTypeGroup(), maxLvl, new ConcurrentHashMap<>()); + ListenableFuture> relationSet = findRelationsRecursively(tenantId, params.getEntityId(), params.getDirection(), params.getRelationTypeGroup(), maxLvl, new ConcurrentHashMap<>()); return Futures.transform(relationSet, input -> { List relations = new ArrayList<>(); if (filters == null || filters.isEmpty()) { @@ -472,15 +474,15 @@ public class BaseRelationService implements RelationService { } @Override - public ListenableFuture> findInfoByQuery(EntityRelationsQuery query) { + public ListenableFuture> findInfoByQuery(TenantId tenantId, EntityRelationsQuery query) { log.trace("Executing findInfoByQuery [{}]", query); - ListenableFuture> relations = findByQuery(query); + ListenableFuture> relations = findByQuery(tenantId, query); EntitySearchDirection direction = query.getParameters().getDirection(); return Futures.transformAsync(relations, relations1 -> { List> futures = new ArrayList<>(); relations1.forEach(relation -> - futures.add(fetchRelationInfoAsync(relation, + futures.add(fetchRelationInfoAsync(tenantId, relation, relation2 -> direction == EntitySearchDirection.FROM ? relation2.getTo() : relation2.getFrom(), (EntityRelationInfo relationInfo, String entityName) -> { if (direction == EntitySearchDirection.FROM) { @@ -567,7 +569,7 @@ public class BaseRelationService implements RelationService { } } - private ListenableFuture> findRelationsRecursively(final EntityId rootId, final EntitySearchDirection direction, + private ListenableFuture> findRelationsRecursively(final TenantId tenantId, final EntityId rootId, final EntitySearchDirection direction, RelationTypeGroup relationTypeGroup, int lvl, final ConcurrentHashMap uniqueMap) throws Exception { if (lvl == 0) { @@ -575,7 +577,7 @@ public class BaseRelationService implements RelationService { } lvl--; //TODO: try to remove this blocking operation - Set children = new HashSet<>(findRelations(rootId, direction, relationTypeGroup).get()); + Set children = new HashSet<>(findRelations(tenantId, rootId, direction, relationTypeGroup).get()); Set childrenIds = new HashSet<>(); for (EntityRelation childRelation : children) { log.trace("Found Relation: {}", childRelation); @@ -594,7 +596,7 @@ public class BaseRelationService implements RelationService { } List>> futures = new ArrayList<>(); for (EntityId entityId : childrenIds) { - futures.add(findRelationsRecursively(entityId, direction, relationTypeGroup, lvl, uniqueMap)); + futures.add(findRelationsRecursively(tenantId, entityId, direction, relationTypeGroup, lvl, uniqueMap)); } //TODO: try to remove this blocking operation List> relations = Futures.successfulAsList(futures).get(); @@ -602,15 +604,15 @@ public class BaseRelationService implements RelationService { return Futures.immediateFuture(children); } - private ListenableFuture> findRelations(final EntityId rootId, final EntitySearchDirection direction, RelationTypeGroup relationTypeGroup) { + private ListenableFuture> findRelations(final TenantId tenantId, final EntityId rootId, final EntitySearchDirection direction, RelationTypeGroup relationTypeGroup) { ListenableFuture> relations; if (relationTypeGroup == null) { relationTypeGroup = RelationTypeGroup.COMMON; } if (direction == EntitySearchDirection.FROM) { - relations = findByFromAsync(rootId, relationTypeGroup); + relations = findByFromAsync(tenantId, rootId, relationTypeGroup); } else { - relations = findByToAsync(rootId, relationTypeGroup); + relations = findByToAsync(tenantId, rootId, relationTypeGroup); } return relations; } diff --git a/dao/src/main/java/org/thingsboard/server/dao/relation/RelationDao.java b/dao/src/main/java/org/thingsboard/server/dao/relation/RelationDao.java index 8f49e89e3d..18d4526cf2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/relation/RelationDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/relation/RelationDao.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.relation; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.data.relation.RelationTypeGroup; @@ -29,34 +30,34 @@ import java.util.List; */ public interface RelationDao { - ListenableFuture> findAllByFrom(EntityId from, RelationTypeGroup typeGroup); + ListenableFuture> findAllByFrom(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup); - ListenableFuture> findAllByFromAndType(EntityId from, String relationType, RelationTypeGroup typeGroup); + ListenableFuture> findAllByFromAndType(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup); - ListenableFuture> findAllByTo(EntityId to, RelationTypeGroup typeGroup); + ListenableFuture> findAllByTo(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup); - ListenableFuture> findAllByToAndType(EntityId to, String relationType, RelationTypeGroup typeGroup); + ListenableFuture> findAllByToAndType(TenantId tenantId, EntityId to, String relationType, RelationTypeGroup typeGroup); - ListenableFuture checkRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); + ListenableFuture checkRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); - ListenableFuture getRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); + ListenableFuture getRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); - boolean saveRelation(EntityRelation relation); + boolean saveRelation(TenantId tenantId, EntityRelation relation); - ListenableFuture saveRelationAsync(EntityRelation relation); + ListenableFuture saveRelationAsync(TenantId tenantId, EntityRelation relation); - boolean deleteRelation(EntityRelation relation); + boolean deleteRelation(TenantId tenantId, EntityRelation relation); - ListenableFuture deleteRelationAsync(EntityRelation relation); + ListenableFuture deleteRelationAsync(TenantId tenantId, EntityRelation relation); - boolean deleteRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); + boolean deleteRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); - ListenableFuture deleteRelationAsync(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); + ListenableFuture deleteRelationAsync(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); - boolean deleteOutboundRelations(EntityId entity); + boolean deleteOutboundRelations(TenantId tenantId, EntityId entity); - ListenableFuture deleteOutboundRelationsAsync(EntityId entity); + ListenableFuture deleteOutboundRelationsAsync(TenantId tenantId, EntityId entity); - ListenableFuture> findRelations(EntityId from, String relationType, RelationTypeGroup typeGroup, EntityType toType, TimePageLink pageLink); + ListenableFuture> findRelations(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup, EntityType toType, TimePageLink pageLink); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/relation/RelationService.java b/dao/src/main/java/org/thingsboard/server/dao/relation/RelationService.java index da58b11a25..cbd0c92353 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/relation/RelationService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/relation/RelationService.java @@ -17,6 +17,7 @@ package org.thingsboard.server.dao.relation; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.data.relation.EntityRelationInfo; import org.thingsboard.server.common.data.relation.EntityRelationsQuery; @@ -30,51 +31,51 @@ import java.util.concurrent.ExecutionException; */ public interface RelationService { - ListenableFuture checkRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); + ListenableFuture checkRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); - EntityRelation getRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); + EntityRelation getRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); - ListenableFuture getRelationAsync(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); + ListenableFuture getRelationAsync(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); - boolean saveRelation(EntityRelation relation); + boolean saveRelation(TenantId tenantId, EntityRelation relation); - ListenableFuture saveRelationAsync(EntityRelation relation); + ListenableFuture saveRelationAsync(TenantId tenantId, EntityRelation relation); - boolean deleteRelation(EntityRelation relation); + boolean deleteRelation(TenantId tenantId, EntityRelation relation); - ListenableFuture deleteRelationAsync(EntityRelation relation); + ListenableFuture deleteRelationAsync(TenantId tenantId, EntityRelation relation); - boolean deleteRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); + boolean deleteRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); - ListenableFuture deleteRelationAsync(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); + ListenableFuture deleteRelationAsync(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup); - void deleteEntityRelations(EntityId entity); + void deleteEntityRelations(TenantId tenantId, EntityId entity); - ListenableFuture deleteEntityRelationsAsync(EntityId entity); + ListenableFuture deleteEntityRelationsAsync(TenantId tenantId, EntityId entity); - List findByFrom(EntityId from, RelationTypeGroup typeGroup); + List findByFrom(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup); - ListenableFuture> findByFromAsync(EntityId from, RelationTypeGroup typeGroup); + ListenableFuture> findByFromAsync(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup); - ListenableFuture> findInfoByFrom(EntityId from, RelationTypeGroup typeGroup); + ListenableFuture> findInfoByFrom(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup); - List findByFromAndType(EntityId from, String relationType, RelationTypeGroup typeGroup); + List findByFromAndType(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup); - ListenableFuture> findByFromAndTypeAsync(EntityId from, String relationType, RelationTypeGroup typeGroup); + ListenableFuture> findByFromAndTypeAsync(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup); - List findByTo(EntityId to, RelationTypeGroup typeGroup); + List findByTo(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup); - ListenableFuture> findByToAsync(EntityId to, RelationTypeGroup typeGroup); + ListenableFuture> findByToAsync(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup); - ListenableFuture> findInfoByTo(EntityId to, RelationTypeGroup typeGroup); + ListenableFuture> findInfoByTo(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup); - List findByToAndType(EntityId to, String relationType, RelationTypeGroup typeGroup); + List findByToAndType(TenantId tenantId, EntityId to, String relationType, RelationTypeGroup typeGroup); - ListenableFuture> findByToAndTypeAsync(EntityId to, String relationType, RelationTypeGroup typeGroup); + ListenableFuture> findByToAndTypeAsync(TenantId tenantId, EntityId to, String relationType, RelationTypeGroup typeGroup); - ListenableFuture> findByQuery(EntityRelationsQuery query); + ListenableFuture> findByQuery(TenantId tenantId, EntityRelationsQuery query); - ListenableFuture> findInfoByQuery(EntityRelationsQuery query); + ListenableFuture> findInfoByQuery(TenantId tenantId, EntityRelationsQuery query); // TODO: This method may be useful for some validations in the future // ListenableFuture checkRecursiveRelation(EntityId from, EntityId to); diff --git a/dao/src/main/java/org/thingsboard/server/dao/rule/BaseRuleChainService.java b/dao/src/main/java/org/thingsboard/server/dao/rule/BaseRuleChainService.java index 14de1a45e3..0c5690c144 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/rule/BaseRuleChainService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/rule/BaseRuleChainService.java @@ -67,11 +67,11 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC @Override public RuleChain saveRuleChain(RuleChain ruleChain) { - ruleChainValidator.validate(ruleChain); - RuleChain savedRuleChain = ruleChainDao.save(ruleChain); + ruleChainValidator.validate(ruleChain, RuleChain::getTenantId); + RuleChain savedRuleChain = ruleChainDao.save(ruleChain.getTenantId(), ruleChain); if (ruleChain.isRoot() && ruleChain.getId() == null) { try { - createRelation(new EntityRelation(savedRuleChain.getTenantId(), savedRuleChain.getId(), + createRelation(ruleChain.getTenantId(), new EntityRelation(savedRuleChain.getTenantId(), savedRuleChain.getId(), EntityRelation.CONTAINS_TYPE, RelationTypeGroup.RULE_CHAIN)); } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to create tenant to root rule chain relation. from: [{}], to: [{}]", @@ -83,20 +83,20 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC } @Override - public boolean setRootRuleChain(RuleChainId ruleChainId) { - RuleChain ruleChain = ruleChainDao.findById(ruleChainId.getId()); + public boolean setRootRuleChain(TenantId tenantId, RuleChainId ruleChainId) { + RuleChain ruleChain = ruleChainDao.findById(tenantId, ruleChainId.getId()); if (!ruleChain.isRoot()) { RuleChain previousRootRuleChain = getRootTenantRuleChain(ruleChain.getTenantId()); if (!previousRootRuleChain.getId().equals(ruleChain.getId())) { try { - deleteRelation(new EntityRelation(previousRootRuleChain.getTenantId(), previousRootRuleChain.getId(), + deleteRelation(tenantId, new EntityRelation(previousRootRuleChain.getTenantId(), previousRootRuleChain.getId(), EntityRelation.CONTAINS_TYPE, RelationTypeGroup.RULE_CHAIN)); previousRootRuleChain.setRoot(false); - ruleChainDao.save(previousRootRuleChain); - createRelation(new EntityRelation(ruleChain.getTenantId(), ruleChain.getId(), + ruleChainDao.save(tenantId, previousRootRuleChain); + createRelation(tenantId, new EntityRelation(ruleChain.getTenantId(), ruleChain.getId(), EntityRelation.CONTAINS_TYPE, RelationTypeGroup.RULE_CHAIN)); ruleChain.setRoot(true); - ruleChainDao.save(ruleChain); + ruleChainDao.save(tenantId, ruleChain); return true; } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to set root rule chain, ruleChainId: [{}]", ruleChainId); @@ -108,9 +108,9 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC } @Override - public RuleChainMetaData saveRuleChainMetaData(RuleChainMetaData ruleChainMetaData) { + public RuleChainMetaData saveRuleChainMetaData(TenantId tenantId, RuleChainMetaData ruleChainMetaData) { Validator.validateId(ruleChainMetaData.getRuleChainId(), "Incorrect rule chain id."); - RuleChain ruleChain = findRuleChainById(ruleChainMetaData.getRuleChainId()); + RuleChain ruleChain = findRuleChainById(tenantId, ruleChainMetaData.getRuleChainId()); if (ruleChain == null) { return null; } @@ -130,9 +130,9 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC } } - List existingRuleNodes = getRuleChainNodes(ruleChainMetaData.getRuleChainId()); + List existingRuleNodes = getRuleChainNodes(tenantId, ruleChainMetaData.getRuleChainId()); for (RuleNode existingNode : existingRuleNodes) { - deleteEntityRelations(existingNode.getId()); + deleteEntityRelations(tenantId, existingNode.getId()); Integer index = ruleNodeIndexMap.get(existingNode.getId()); if (index != null) { toAddOrUpdate.add(ruleChainMetaData.getNodes().get(index)); @@ -142,9 +142,9 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC } for (RuleNode node : toAddOrUpdate) { node.setRuleChainId(ruleChain.getId()); - RuleNode savedNode = ruleNodeDao.save(node); + RuleNode savedNode = ruleNodeDao.save(tenantId, node); try { - createRelation(new EntityRelation(ruleChainMetaData.getRuleChainId(), savedNode.getId(), + createRelation(tenantId, new EntityRelation(ruleChainMetaData.getRuleChainId(), savedNode.getId(), EntityRelation.CONTAINS_TYPE, RelationTypeGroup.RULE_CHAIN)); } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to create rule chain to rule node relation. from: [{}], to: [{}]", @@ -156,7 +156,7 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC ruleNodeIndexMap.put(savedNode.getId(), index); } for (RuleNode node : toDelete) { - deleteRuleNode(node.getId()); + deleteRuleNode(tenantId, node.getId()); } RuleNodeId firstRuleNodeId = null; if (ruleChainMetaData.getFirstNodeIndex() != null) { @@ -165,7 +165,7 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC if ((ruleChain.getFirstRuleNodeId() != null && !ruleChain.getFirstRuleNodeId().equals(firstRuleNodeId)) || (ruleChain.getFirstRuleNodeId() == null && firstRuleNodeId != null)) { ruleChain.setFirstRuleNodeId(firstRuleNodeId); - ruleChainDao.save(ruleChain); + ruleChainDao.save(tenantId, ruleChain); } if (ruleChainMetaData.getConnections() != null) { for (NodeConnectionInfo nodeConnection : ruleChainMetaData.getConnections()) { @@ -173,7 +173,7 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC EntityId to = nodes.get(nodeConnection.getToIndex()).getId(); String type = nodeConnection.getType(); try { - createRelation(new EntityRelation(from, to, type, RelationTypeGroup.RULE_NODE)); + createRelation(tenantId, new EntityRelation(from, to, type, RelationTypeGroup.RULE_NODE)); } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to create rule node relation. from: [{}], to: [{}]", from, to); throw new RuntimeException(e); @@ -186,7 +186,7 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC EntityId to = nodeToRuleChainConnection.getTargetRuleChainId(); String type = nodeToRuleChainConnection.getType(); try { - createRelation(new EntityRelation(from, to, type, RelationTypeGroup.RULE_NODE, nodeToRuleChainConnection.getAdditionalInfo())); + createRelation(tenantId, new EntityRelation(from, to, type, RelationTypeGroup.RULE_NODE, nodeToRuleChainConnection.getAdditionalInfo())); } catch (ExecutionException | InterruptedException e) { log.warn("[{}] Failed to create rule node to rule chain relation. from: [{}], to: [{}]", from, to); throw new RuntimeException(e); @@ -194,19 +194,19 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC } } - return loadRuleChainMetaData(ruleChainMetaData.getRuleChainId()); + return loadRuleChainMetaData(tenantId, ruleChainMetaData.getRuleChainId()); } @Override - public RuleChainMetaData loadRuleChainMetaData(RuleChainId ruleChainId) { + public RuleChainMetaData loadRuleChainMetaData(TenantId tenantId, RuleChainId ruleChainId) { Validator.validateId(ruleChainId, "Incorrect rule chain id."); - RuleChain ruleChain = findRuleChainById(ruleChainId); + RuleChain ruleChain = findRuleChainById(tenantId, ruleChainId); if (ruleChain == null) { return null; } RuleChainMetaData ruleChainMetaData = new RuleChainMetaData(); ruleChainMetaData.setRuleChainId(ruleChainId); - List ruleNodes = getRuleChainNodes(ruleChainId); + List ruleNodes = getRuleChainNodes(tenantId, ruleChainId); Map ruleNodeIndexMap = new HashMap<>(); for (RuleNode node : ruleNodes) { ruleNodeIndexMap.put(node.getId(), ruleNodes.indexOf(node)); @@ -217,7 +217,7 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC } for (RuleNode node : ruleNodes) { int fromIndex = ruleNodeIndexMap.get(node.getId()); - List nodeRelations = getRuleNodeRelations(node.getId()); + List nodeRelations = getRuleNodeRelations(tenantId, node.getId()); for (EntityRelation nodeRelation : nodeRelations) { String type = nodeRelation.getType(); if (nodeRelation.getTo().getEntityType() == EntityType.RULE_NODE) { @@ -234,54 +234,54 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC } @Override - public RuleChain findRuleChainById(RuleChainId ruleChainId) { + public RuleChain findRuleChainById(TenantId tenantId, RuleChainId ruleChainId) { Validator.validateId(ruleChainId, "Incorrect rule chain id for search request."); - return ruleChainDao.findById(ruleChainId.getId()); + return ruleChainDao.findById(tenantId, ruleChainId.getId()); } @Override - public RuleNode findRuleNodeById(RuleNodeId ruleNodeId) { + public RuleNode findRuleNodeById(TenantId tenantId, RuleNodeId ruleNodeId) { Validator.validateId(ruleNodeId, "Incorrect rule node id for search request."); - return ruleNodeDao.findById(ruleNodeId.getId()); + return ruleNodeDao.findById(tenantId, ruleNodeId.getId()); } @Override - public ListenableFuture findRuleChainByIdAsync(RuleChainId ruleChainId) { + public ListenableFuture findRuleChainByIdAsync(TenantId tenantId, RuleChainId ruleChainId) { Validator.validateId(ruleChainId, "Incorrect rule chain id for search request."); - return ruleChainDao.findByIdAsync(ruleChainId.getId()); + return ruleChainDao.findByIdAsync(tenantId, ruleChainId.getId()); } @Override - public ListenableFuture findRuleNodeByIdAsync(RuleNodeId ruleNodeId) { + public ListenableFuture findRuleNodeByIdAsync(TenantId tenantId, RuleNodeId ruleNodeId) { Validator.validateId(ruleNodeId, "Incorrect rule node id for search request."); - return ruleNodeDao.findByIdAsync(ruleNodeId.getId()); + return ruleNodeDao.findByIdAsync(tenantId, ruleNodeId.getId()); } @Override public RuleChain getRootTenantRuleChain(TenantId tenantId) { Validator.validateId(tenantId, "Incorrect tenant id for search request."); - List relations = relationService.findByFrom(tenantId, RelationTypeGroup.RULE_CHAIN); + List relations = relationService.findByFrom(tenantId, tenantId, RelationTypeGroup.RULE_CHAIN); if (relations != null && !relations.isEmpty()) { EntityRelation relation = relations.get(0); RuleChainId ruleChainId = new RuleChainId(relation.getTo().getId()); - return findRuleChainById(ruleChainId); + return findRuleChainById(tenantId, ruleChainId); } else { return null; } } @Override - public List getRuleChainNodes(RuleChainId ruleChainId) { + public List getRuleChainNodes(TenantId tenantId, RuleChainId ruleChainId) { Validator.validateId(ruleChainId, "Incorrect rule chain id for search request."); - List relations = getRuleChainToNodeRelations(ruleChainId); - List ruleNodes = relations.stream().map(relation -> ruleNodeDao.findById(relation.getTo().getId())).collect(Collectors.toList()); + List relations = getRuleChainToNodeRelations(tenantId, ruleChainId); + List ruleNodes = relations.stream().map(relation -> ruleNodeDao.findById(tenantId, relation.getTo().getId())).collect(Collectors.toList()); return ruleNodes; } @Override - public List getRuleNodeRelations(RuleNodeId ruleNodeId) { + public List getRuleNodeRelations(TenantId tenantId, RuleNodeId ruleNodeId) { Validator.validateId(ruleNodeId, "Incorrect rule node id for search request."); - return relationService.findByFrom(ruleNodeId, RelationTypeGroup.RULE_NODE); + return relationService.findByFrom(tenantId, ruleNodeId, RelationTypeGroup.RULE_NODE); } @Override @@ -293,60 +293,60 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC } @Override - public void deleteRuleChainById(RuleChainId ruleChainId) { + public void deleteRuleChainById(TenantId tenantId, RuleChainId ruleChainId) { Validator.validateId(ruleChainId, "Incorrect rule chain id for delete request."); - RuleChain ruleChain = ruleChainDao.findById(ruleChainId.getId()); + RuleChain ruleChain = ruleChainDao.findById(tenantId, ruleChainId.getId()); if (ruleChain != null && ruleChain.isRoot()) { throw new DataValidationException("Deletion of Root Tenant Rule Chain is prohibited!"); } - checkRuleNodesAndDelete(ruleChainId); + checkRuleNodesAndDelete(tenantId, ruleChainId); } @Override public void deleteRuleChainsByTenantId(TenantId tenantId) { Validator.validateId(tenantId, "Incorrect tenant id for delete rule chains request."); - tenantRuleChainsRemover.removeEntities(tenantId); + tenantRuleChainsRemover.removeEntities(tenantId, tenantId); } - private void checkRuleNodesAndDelete(RuleChainId ruleChainId) { - List nodeRelations = getRuleChainToNodeRelations(ruleChainId); + private void checkRuleNodesAndDelete(TenantId tenantId, RuleChainId ruleChainId) { + List nodeRelations = getRuleChainToNodeRelations(tenantId, ruleChainId); for (EntityRelation relation : nodeRelations) { - deleteRuleNode(relation.getTo()); + deleteRuleNode(tenantId, relation.getTo()); } - deleteEntityRelations(ruleChainId); - ruleChainDao.removeById(ruleChainId.getId()); + deleteEntityRelations(tenantId, ruleChainId); + ruleChainDao.removeById(tenantId, ruleChainId.getId()); } - private List getRuleChainToNodeRelations(RuleChainId ruleChainId) { - return relationService.findByFrom(ruleChainId, RelationTypeGroup.RULE_CHAIN); + private List getRuleChainToNodeRelations(TenantId tenantId, RuleChainId ruleChainId) { + return relationService.findByFrom(tenantId, ruleChainId, RelationTypeGroup.RULE_CHAIN); } - private void deleteRuleNode(EntityId entityId) { - deleteEntityRelations(entityId); - ruleNodeDao.removeById(entityId.getId()); + private void deleteRuleNode(TenantId tenantId, EntityId entityId) { + deleteEntityRelations(tenantId, entityId); + ruleNodeDao.removeById(tenantId, entityId.getId()); } - private void createRelation(EntityRelation relation) throws ExecutionException, InterruptedException { + private void createRelation(TenantId tenantId, EntityRelation relation) throws ExecutionException, InterruptedException { log.debug("Creating relation: {}", relation); - relationService.saveRelation(relation); + relationService.saveRelation(tenantId, relation); } - private void deleteRelation(EntityRelation relation) throws ExecutionException, InterruptedException { + private void deleteRelation(TenantId tenantId, EntityRelation relation) throws ExecutionException, InterruptedException { log.debug("Deleting relation: {}", relation); - relationService.deleteRelation(relation); + relationService.deleteRelation(tenantId, relation); } private DataValidator ruleChainValidator = new DataValidator() { @Override - protected void validateDataImpl(RuleChain ruleChain) { + protected void validateDataImpl(TenantId tenantId, RuleChain ruleChain) { if (StringUtils.isEmpty(ruleChain.getName())) { throw new DataValidationException("Rule chain name should be specified!."); } if (ruleChain.getTenantId() == null || ruleChain.getTenantId().isNullUid()) { throw new DataValidationException("Rule chain should be assigned to tenant!"); } - Tenant tenant = tenantDao.findById(ruleChain.getTenantId().getId()); + Tenant tenant = tenantDao.findById(tenantId, ruleChain.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("Rule chain is referencing to non-existent tenant!"); } @@ -363,13 +363,13 @@ public class BaseRuleChainService extends AbstractEntityService implements RuleC new PaginatedRemover() { @Override - protected List findEntities(TenantId id, TextPageLink pageLink) { + protected List findEntities(TenantId tenantId, TenantId id, TextPageLink pageLink) { return ruleChainDao.findRuleChainsByTenantId(id.getId(), pageLink); } @Override - protected void removeEntity(RuleChain entity) { - checkRuleNodesAndDelete(entity.getId()); + protected void removeEntity(TenantId tenantId, RuleChain entity) { + checkRuleNodesAndDelete(tenantId, entity.getId()); } }; } diff --git a/dao/src/main/java/org/thingsboard/server/dao/rule/CassandraRuleChainDao.java b/dao/src/main/java/org/thingsboard/server/dao/rule/CassandraRuleChainDao.java index ff672a78db..69ff8f8190 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/rule/CassandraRuleChainDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/rule/CassandraRuleChainDao.java @@ -17,6 +17,7 @@ package org.thingsboard.server.dao.rule; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.dao.DaoUtil; @@ -51,7 +52,7 @@ public class CassandraRuleChainDao extends CassandraAbstractSearchTextDao findRuleChainsByTenantId(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find rule chains by tenantId [{}] and pageLink [{}]", tenantId, pageLink); - List ruleChainEntities = findPageWithTextSearch(RULE_CHAIN_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List ruleChainEntities = findPageWithTextSearch(new TenantId(tenantId), RULE_CHAIN_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Collections.singletonList(eq(RULE_CHAIN_TENANT_ID_PROPERTY, tenantId)), pageLink); diff --git a/dao/src/main/java/org/thingsboard/server/dao/rule/RuleChainService.java b/dao/src/main/java/org/thingsboard/server/dao/rule/RuleChainService.java index 4dbe6c9de4..7dfd8477c4 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/rule/RuleChainService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/rule/RuleChainService.java @@ -36,29 +36,29 @@ public interface RuleChainService { RuleChain saveRuleChain(RuleChain ruleChain); - boolean setRootRuleChain(RuleChainId ruleChainId); + boolean setRootRuleChain(TenantId tenantId, RuleChainId ruleChainId); - RuleChainMetaData saveRuleChainMetaData(RuleChainMetaData ruleChainMetaData); + RuleChainMetaData saveRuleChainMetaData(TenantId tenantId, RuleChainMetaData ruleChainMetaData); - RuleChainMetaData loadRuleChainMetaData(RuleChainId ruleChainId); + RuleChainMetaData loadRuleChainMetaData(TenantId tenantId, RuleChainId ruleChainId); - RuleChain findRuleChainById(RuleChainId ruleChainId); + RuleChain findRuleChainById(TenantId tenantId, RuleChainId ruleChainId); - RuleNode findRuleNodeById(RuleNodeId ruleNodeId); + RuleNode findRuleNodeById(TenantId tenantId, RuleNodeId ruleNodeId); - ListenableFuture findRuleChainByIdAsync(RuleChainId ruleChainId); + ListenableFuture findRuleChainByIdAsync(TenantId tenantId, RuleChainId ruleChainId); - ListenableFuture findRuleNodeByIdAsync(RuleNodeId ruleNodeId); + ListenableFuture findRuleNodeByIdAsync(TenantId tenantId, RuleNodeId ruleNodeId); RuleChain getRootTenantRuleChain(TenantId tenantId); - List getRuleChainNodes(RuleChainId ruleChainId); + List getRuleChainNodes(TenantId tenantId, RuleChainId ruleChainId); - List getRuleNodeRelations(RuleNodeId ruleNodeId); + List getRuleNodeRelations(TenantId tenantId, RuleNodeId ruleNodeId); TextPageData findTenantRuleChains(TenantId tenantId, TextPageLink pageLink); - void deleteRuleChainById(RuleChainId ruleChainId); + void deleteRuleChainById(TenantId tenantId, RuleChainId ruleChainId); void deleteRuleChainsByTenantId(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/DataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/DataValidator.java index fd74e8ebce..cc36c17faa 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/DataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/DataValidator.java @@ -19,70 +19,73 @@ import com.fasterxml.jackson.databind.JsonNode; import lombok.extern.slf4j.Slf4j; import org.apache.commons.validator.routines.EmailValidator; import org.thingsboard.server.common.data.BaseData; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.exception.DataValidationException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; +import java.util.function.Function; @Slf4j public abstract class DataValidator> { private static EmailValidator emailValidator = EmailValidator.getInstance(); - - public void validate(D data) { + + public void validate(D data, Function tenantIdFunction) { try { if (data == null) { throw new DataValidationException("Data object can't be null!"); } - validateDataImpl(data); + TenantId tenantId = tenantIdFunction.apply(data); + validateDataImpl(tenantId, data); if (data.getId() == null) { - validateCreate(data); + validateCreate(tenantId, data); } else { - validateUpdate(data); + validateUpdate(tenantId, data); } } catch (DataValidationException e) { log.error("Data object is invalid: [{}]", e.getMessage()); throw e; } } - - protected void validateDataImpl(D data) { + + protected void validateDataImpl(TenantId tenantId, D data) { } - - protected void validateCreate(D data) { + + protected void validateCreate(TenantId tenantId, D data) { } - protected void validateUpdate(D data) { + protected void validateUpdate(TenantId tenantId, D data) { } - + protected boolean isSameData(D existentData, D actualData) { return actualData.getId() != null && existentData.getId().equals(actualData.getId()); } - + protected static void validateEmail(String email) { if (!emailValidator.isValid(email)) { throw new DataValidationException("Invalid email address format '" + email + "'!"); } } - + protected static void validateJsonStructure(JsonNode expectedNode, JsonNode actualNode) { - Set expectedFields = new HashSet<>(); + Set expectedFields = new HashSet<>(); Iterator fieldsIterator = expectedNode.fieldNames(); while (fieldsIterator.hasNext()) { expectedFields.add(fieldsIterator.next()); } - - Set actualFields = new HashSet<>(); + + Set actualFields = new HashSet<>(); fieldsIterator = actualNode.fieldNames(); while (fieldsIterator.hasNext()) { actualFields.add(fieldsIterator.next()); } - + if (!expectedFields.containsAll(actualFields) || !actualFields.containsAll(expectedFields)) { throw new DataValidationException("Provided json structure is different from stored one '" + actualNode + "'!"); } - + for (String field : actualFields) { if (!actualNode.get(field).isTextual()) { throw new DataValidationException("Provided json structure can't contain non-text values '" + actualNode + "'!"); diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/PaginatedRemover.java b/dao/src/main/java/org/thingsboard/server/dao/service/PaginatedRemover.java index d9f3a0554e..44d7c6dca5 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/PaginatedRemover.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/PaginatedRemover.java @@ -16,6 +16,7 @@ package org.thingsboard.server.dao.service; import org.thingsboard.server.common.data.id.IdBased; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import java.util.List; @@ -25,13 +26,13 @@ public abstract class PaginatedRemover> { private static final int DEFAULT_LIMIT = 100; - public void removeEntities(I id) { + public void removeEntities(TenantId tenantId, I id) { TextPageLink pageLink = new TextPageLink(DEFAULT_LIMIT); boolean hasNext = true; while (hasNext) { - List entities = findEntities(id, pageLink); + List entities = findEntities(tenantId, id, pageLink); for (D entity : entities) { - removeEntity(entity); + removeEntity(tenantId, entity); } hasNext = entities.size() == pageLink.getLimit(); if (hasNext) { @@ -42,8 +43,8 @@ public abstract class PaginatedRemover> { } } - protected abstract List findEntities(I id, TextPageLink pageLink); + protected abstract List findEntities(TenantId tenantId,I id, TextPageLink pageLink); - protected abstract void removeEntity(D entity); + protected abstract void removeEntity(TenantId tenantId, D entity); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsDao.java b/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsDao.java index 871d19470e..630428f6a0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsDao.java @@ -16,6 +16,7 @@ package org.thingsboard.server.dao.settings; import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.Dao; public interface AdminSettingsDao extends Dao { @@ -26,7 +27,7 @@ public interface AdminSettingsDao extends Dao { * @param adminSettings the admin settings object * @return saved admin settings object */ - AdminSettings save(AdminSettings adminSettings); + AdminSettings save(TenantId tenantId, AdminSettings adminSettings); /** * Find admin settings by key. @@ -34,6 +35,6 @@ public interface AdminSettingsDao extends Dao { * @param key the key * @return the admin settings object */ - AdminSettings findByKey(String key); + AdminSettings findByKey(TenantId tenantId, String key); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsService.java b/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsService.java index 29559ff12f..5a79935017 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsService.java @@ -17,13 +17,14 @@ package org.thingsboard.server.dao.settings; import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.id.AdminSettingsId; +import org.thingsboard.server.common.data.id.TenantId; public interface AdminSettingsService { - AdminSettings findAdminSettingsById(AdminSettingsId adminSettingsId); + AdminSettings findAdminSettingsById(TenantId tenantId, AdminSettingsId adminSettingsId); - AdminSettings findAdminSettingsByKey(String key); + AdminSettings findAdminSettingsByKey(TenantId tenantId, String key); - AdminSettings saveAdminSettings(AdminSettings adminSettings); + AdminSettings saveAdminSettings(TenantId tenantId, AdminSettings adminSettings); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsServiceImpl.java index 7e7dfa2729..9205a5cd9c 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/settings/AdminSettingsServiceImpl.java @@ -20,7 +20,9 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.id.AdminSettingsId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.exception.DataValidationException; import org.thingsboard.server.dao.service.DataValidator; import org.thingsboard.server.dao.service.Validator; @@ -33,40 +35,40 @@ public class AdminSettingsServiceImpl implements AdminSettingsService { private AdminSettingsDao adminSettingsDao; @Override - public AdminSettings findAdminSettingsById(AdminSettingsId adminSettingsId) { + public AdminSettings findAdminSettingsById(TenantId tenantId, AdminSettingsId adminSettingsId) { log.trace("Executing findAdminSettingsById [{}]", adminSettingsId); Validator.validateId(adminSettingsId, "Incorrect adminSettingsId " + adminSettingsId); - return adminSettingsDao.findById(adminSettingsId.getId()); + return adminSettingsDao.findById(tenantId, adminSettingsId.getId()); } @Override - public AdminSettings findAdminSettingsByKey(String key) { + public AdminSettings findAdminSettingsByKey(TenantId tenantId, String key) { log.trace("Executing findAdminSettingsByKey [{}]", key); Validator.validateString(key, "Incorrect key " + key); - return adminSettingsDao.findByKey(key); + return adminSettingsDao.findByKey(tenantId, key); } @Override - public AdminSettings saveAdminSettings(AdminSettings adminSettings) { + public AdminSettings saveAdminSettings(TenantId tenantId, AdminSettings adminSettings) { log.trace("Executing saveAdminSettings [{}]", adminSettings); - adminSettingsValidator.validate(adminSettings); - return adminSettingsDao.save(adminSettings); + adminSettingsValidator.validate(adminSettings, data -> tenantId); + return adminSettingsDao.save(tenantId, adminSettings); } private DataValidator adminSettingsValidator = new DataValidator() { @Override - protected void validateCreate(AdminSettings adminSettings) { - AdminSettings existentAdminSettingsWithKey = findAdminSettingsByKey(adminSettings.getKey()); + protected void validateCreate(TenantId tenantId, AdminSettings adminSettings) { + AdminSettings existentAdminSettingsWithKey = findAdminSettingsByKey(tenantId, adminSettings.getKey()); if (existentAdminSettingsWithKey != null) { throw new DataValidationException("Admin settings with such name already exists!"); } } @Override - protected void validateUpdate(AdminSettings adminSettings) { - AdminSettings existentAdminSettings = findAdminSettingsById(adminSettings.getId()); + protected void validateUpdate(TenantId tenantId, AdminSettings adminSettings) { + AdminSettings existentAdminSettings = findAdminSettingsById(tenantId, adminSettings.getId()); if (existentAdminSettings != null) { if (!existentAdminSettings.getKey().equals(adminSettings.getKey())) { throw new DataValidationException("Changing key of admin settings entry is prohibited!"); @@ -77,7 +79,7 @@ public class AdminSettingsServiceImpl implements AdminSettingsService { @Override - protected void validateDataImpl(AdminSettings adminSettings) { + protected void validateDataImpl(TenantId tenantId, AdminSettings adminSettings) { if (StringUtils.isEmpty(adminSettings.getKey())) { throw new DataValidationException("Key should be specified!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/settings/CassandraAdminSettingsDao.java b/dao/src/main/java/org/thingsboard/server/dao/settings/CassandraAdminSettingsDao.java index ebc66d7d9a..2b8eea95a0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/settings/CassandraAdminSettingsDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/settings/CassandraAdminSettingsDao.java @@ -19,6 +19,7 @@ import com.datastax.driver.core.querybuilder.Select.Where; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.nosql.AdminSettingsEntity; import org.thingsboard.server.dao.nosql.CassandraAbstractModelDao; @@ -46,11 +47,11 @@ public class CassandraAdminSettingsDao extends CassandraAbstractModelDao, D> @Override @Transactional - public D save(D domain) { + public D save(TenantId tenantId, D domain) { E entity; try { entity = getEntityClass().getConstructor(domain.getClass()).newInstance(domain); @@ -64,21 +65,21 @@ public abstract class JpaAbstractDao, D> } @Override - public D findById(UUID key) { + public D findById(TenantId tenantId, UUID key) { log.debug("Get entity by key {}", key); E entity = getCrudRepository().findOne(fromTimeUUID(key)); return DaoUtil.getData(entity); } @Override - public ListenableFuture findByIdAsync(UUID key) { + public ListenableFuture findByIdAsync(TenantId tenantId, UUID key) { log.debug("Get entity by key async {}", key); return service.submit(() -> DaoUtil.getData(getCrudRepository().findOne(fromTimeUUID(key)))); } @Override @Transactional - public boolean removeById(UUID id) { + public boolean removeById(TenantId tenantId, UUID id) { String key = fromTimeUUID(id); getCrudRepository().delete(key); log.debug("Remove request: {}", key); @@ -86,7 +87,7 @@ public abstract class JpaAbstractDao, D> } @Override - public List find() { + public List find(TenantId tenantId) { List entities = Lists.newArrayList(getCrudRepository().findAll()); return DaoUtil.convertDataList(entities); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java index ff6e2130f8..2e071b1a89 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java @@ -82,12 +82,12 @@ public class JpaAlarmDao extends JpaAbstractDao implements A } @Override - public ListenableFuture findAlarmByIdAsync(UUID key) { - return findByIdAsync(key); + public ListenableFuture findAlarmByIdAsync(TenantId tenantId, UUID key) { + return findByIdAsync(tenantId, key); } @Override - public ListenableFuture> findAlarms(AlarmQuery query) { + public ListenableFuture> findAlarms(TenantId tenantId, AlarmQuery query) { log.trace("Try to find alarms by entity [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(), query.getStatus(), query.getPageLink()); EntityId affectedEntity = query.getAffectedEntityId(); String searchStatusName; @@ -99,12 +99,12 @@ public class JpaAlarmDao extends JpaAbstractDao implements A searchStatusName = query.getStatus().name(); } String relationType = BaseAlarmService.ALARM_RELATION_PREFIX + searchStatusName; - ListenableFuture> relations = relationDao.findRelations(affectedEntity, relationType, RelationTypeGroup.ALARM, EntityType.ALARM, query.getPageLink()); + ListenableFuture> relations = relationDao.findRelations(tenantId, affectedEntity, relationType, RelationTypeGroup.ALARM, EntityType.ALARM, query.getPageLink()); return Futures.transformAsync(relations, input -> { List> alarmFutures = new ArrayList<>(input.size()); for (EntityRelation relation : input) { alarmFutures.add(Futures.transform( - findAlarmByIdAsync(relation.getTo().getId()), + findAlarmByIdAsync(tenantId, relation.getTo().getId()), AlarmInfo::new)); } return Futures.successfulAsList(alarmFutures); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/attributes/JpaAttributeDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/attributes/JpaAttributeDao.java index 4ac0c0ca38..2193646ec9 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/attributes/JpaAttributeDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/attributes/JpaAttributeDao.java @@ -23,6 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.UUIDConverter; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.attributes.AttributesDao; @@ -47,7 +48,7 @@ public class JpaAttributeDao extends JpaAbstractDaoListeningExecutorService impl private AttributeKvRepository attributeKvRepository; @Override - public ListenableFuture> find(EntityId entityId, String attributeType, String attributeKey) { + public ListenableFuture> find(TenantId tenantId, EntityId entityId, String attributeType, String attributeKey) { AttributeKvCompositeKey compositeKey = getAttributeKvCompositeKey(entityId, attributeType, attributeKey); return Futures.immediateFuture( @@ -55,7 +56,7 @@ public class JpaAttributeDao extends JpaAbstractDaoListeningExecutorService impl } @Override - public ListenableFuture> find(EntityId entityId, String attributeType, Collection attributeKeys) { + public ListenableFuture> find(TenantId tenantId, EntityId entityId, String attributeType, Collection attributeKeys) { List compositeKeys = attributeKeys .stream() @@ -67,7 +68,7 @@ public class JpaAttributeDao extends JpaAbstractDaoListeningExecutorService impl } @Override - public ListenableFuture> findAll(EntityId entityId, String attributeType) { + public ListenableFuture> findAll(TenantId tenantId, EntityId entityId, String attributeType) { return Futures.immediateFuture( DaoUtil.convertDataList(Lists.newArrayList( attributeKvRepository.findAllByEntityTypeAndEntityIdAndAttributeType( @@ -77,7 +78,7 @@ public class JpaAttributeDao extends JpaAbstractDaoListeningExecutorService impl } @Override - public ListenableFuture save(EntityId entityId, String attributeType, AttributeKvEntry attribute) { + public ListenableFuture save(TenantId tenantId, EntityId entityId, String attributeType, AttributeKvEntry attribute) { AttributeKvEntity entity = new AttributeKvEntity(); entity.setId(new AttributeKvCompositeKey(entityId.getEntityType(), fromTimeUUID(entityId.getId()), attributeType, attribute.getKey())); entity.setLastUpdateTs(attribute.getLastUpdateTs()); @@ -92,7 +93,7 @@ public class JpaAttributeDao extends JpaAbstractDaoListeningExecutorService impl } @Override - public ListenableFuture> removeAll(EntityId entityId, String attributeType, List keys) { + public ListenableFuture> removeAll(TenantId tenantId, EntityId entityId, String attributeType, List keys) { List entitiesToDelete = keys .stream() .map(key -> { diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/audit/JpaAuditLogDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/audit/JpaAuditLogDao.java index e94f3b33ed..e2960ef68a 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/audit/JpaAuditLogDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/audit/JpaAuditLogDao.java @@ -75,7 +75,7 @@ public class JpaAuditLogDao extends JpaAbstractDao imp @Override public ListenableFuture saveByTenantId(AuditLog auditLog) { return insertService.submit(() -> { - save(auditLog); + save(auditLog.getTenantId(), auditLog); return null; }); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/component/JpaBaseComponentDescriptorDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/component/JpaBaseComponentDescriptorDao.java index 172881812b..47b006e3b1 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/component/JpaBaseComponentDescriptorDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/component/JpaBaseComponentDescriptorDao.java @@ -23,6 +23,7 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.thingsboard.server.common.data.UUIDConverter; import org.thingsboard.server.common.data.id.ComponentDescriptorId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.plugin.ComponentDescriptor; import org.thingsboard.server.common.data.plugin.ComponentScope; @@ -61,28 +62,28 @@ public class JpaBaseComponentDescriptorDao extends JpaAbstractSearchTextDao saveIfNotExist(ComponentDescriptor component) { + public Optional saveIfNotExist(TenantId tenantId, ComponentDescriptor component) { if (component.getId() == null) { component.setId(new ComponentDescriptorId(UUIDs.timeBased())); } if (componentDescriptorRepository.findOne(UUIDConverter.fromTimeUUID(component.getId().getId())) == null) { - return Optional.of(save(component)); + return Optional.of(save(tenantId, component)); } return Optional.empty(); } @Override - public ComponentDescriptor findById(ComponentDescriptorId componentId) { - return findById(componentId.getId()); + public ComponentDescriptor findById(TenantId tenantId, ComponentDescriptorId componentId) { + return findById(tenantId, componentId.getId()); } @Override - public ComponentDescriptor findByClazz(String clazz) { + public ComponentDescriptor findByClazz(TenantId tenantId, String clazz) { return DaoUtil.getData(componentDescriptorRepository.findByClazz(clazz)); } @Override - public List findByTypeAndPageLink(ComponentType type, TextPageLink pageLink) { + public List findByTypeAndPageLink(TenantId tenantId, ComponentType type, TextPageLink pageLink) { return DaoUtil.convertDataList(componentDescriptorRepository .findByType( type, @@ -92,7 +93,7 @@ public class JpaBaseComponentDescriptorDao extends JpaAbstractSearchTextDao findByScopeAndTypeAndPageLink(ComponentScope scope, ComponentType type, TextPageLink pageLink) { + public List findByScopeAndTypeAndPageLink(TenantId tenantId, ComponentScope scope, ComponentType type, TextPageLink pageLink) { return DaoUtil.convertDataList(componentDescriptorRepository .findByScopeAndType( type, @@ -104,13 +105,13 @@ public class JpaBaseComponentDescriptorDao extends JpaAbstractSearchTextDao> findDashboardsByTenantIdAndCustomerId(UUID tenantId, UUID customerId, TimePageLink pageLink) { log.debug("Try to find dashboards by tenantId [{}], customerId[{}] and pageLink [{}]", tenantId, customerId, pageLink); - ListenableFuture> relations = relationDao.findRelations(new CustomerId(customerId), EntityRelation.CONTAINS_TYPE, RelationTypeGroup.DASHBOARD, EntityType.DASHBOARD, pageLink); + ListenableFuture> relations = relationDao.findRelations(new TenantId(tenantId), new CustomerId(customerId), EntityRelation.CONTAINS_TYPE, RelationTypeGroup.DASHBOARD, EntityType.DASHBOARD, pageLink); return Futures.transformAsync(relations, input -> { List> dashboardFutures = new ArrayList<>(input.size()); for (EntityRelation relation : input) { - dashboardFutures.add(findByIdAsync(relation.getTo().getId())); + dashboardFutures.add(findByIdAsync(new TenantId(tenantId), relation.getTo().getId())); } return Futures.successfulAsList(dashboardFutures); }); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/device/JpaDeviceCredentialsDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/device/JpaDeviceCredentialsDao.java index fb41a88241..d7a2ccf7f0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/device/JpaDeviceCredentialsDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/device/JpaDeviceCredentialsDao.java @@ -19,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.UUIDConverter; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.device.DeviceCredentialsDao; @@ -49,12 +50,12 @@ public class JpaDeviceCredentialsDao extends JpaAbstractDao> findAllByFrom(EntityId from, RelationTypeGroup typeGroup) { + public ListenableFuture> findAllByFrom(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup) { return service.submit(() -> DaoUtil.convertDataList( relationRepository.findAllByFromIdAndFromTypeAndRelationTypeGroup( UUIDConverter.fromTimeUUID(from.getId()), @@ -65,7 +66,7 @@ public class JpaRelationDao extends JpaAbstractDaoListeningExecutorService imple } @Override - public ListenableFuture> findAllByFromAndType(EntityId from, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture> findAllByFromAndType(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup) { return service.submit(() -> DaoUtil.convertDataList( relationRepository.findAllByFromIdAndFromTypeAndRelationTypeAndRelationTypeGroup( UUIDConverter.fromTimeUUID(from.getId()), @@ -75,7 +76,7 @@ public class JpaRelationDao extends JpaAbstractDaoListeningExecutorService imple } @Override - public ListenableFuture> findAllByTo(EntityId to, RelationTypeGroup typeGroup) { + public ListenableFuture> findAllByTo(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup) { return service.submit(() -> DaoUtil.convertDataList( relationRepository.findAllByToIdAndToTypeAndRelationTypeGroup( UUIDConverter.fromTimeUUID(to.getId()), @@ -84,7 +85,7 @@ public class JpaRelationDao extends JpaAbstractDaoListeningExecutorService imple } @Override - public ListenableFuture> findAllByToAndType(EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture> findAllByToAndType(TenantId tenantId, EntityId to, String relationType, RelationTypeGroup typeGroup) { return service.submit(() -> DaoUtil.convertDataList( relationRepository.findAllByToIdAndToTypeAndRelationTypeAndRelationTypeGroup( UUIDConverter.fromTimeUUID(to.getId()), @@ -94,13 +95,13 @@ public class JpaRelationDao extends JpaAbstractDaoListeningExecutorService imple } @Override - public ListenableFuture checkRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture checkRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { RelationCompositeKey key = getRelationCompositeKey(from, to, relationType, typeGroup); return service.submit(() -> relationRepository.findOne(key) != null); } @Override - public ListenableFuture getRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture getRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { RelationCompositeKey key = getRelationCompositeKey(from, to, relationType, typeGroup); return service.submit(() -> DaoUtil.getData(relationRepository.findOne(key))); } @@ -115,36 +116,36 @@ public class JpaRelationDao extends JpaAbstractDaoListeningExecutorService imple } @Override - public boolean saveRelation(EntityRelation relation) { + public boolean saveRelation(TenantId tenantId, EntityRelation relation) { return relationRepository.save(new RelationEntity(relation)) != null; } @Override - public ListenableFuture saveRelationAsync(EntityRelation relation) { + public ListenableFuture saveRelationAsync(TenantId tenantId, EntityRelation relation) { return service.submit(() -> relationRepository.save(new RelationEntity(relation)) != null); } @Override - public boolean deleteRelation(EntityRelation relation) { + public boolean deleteRelation(TenantId tenantId, EntityRelation relation) { RelationCompositeKey key = new RelationCompositeKey(relation); return deleteRelationIfExists(key); } @Override - public ListenableFuture deleteRelationAsync(EntityRelation relation) { + public ListenableFuture deleteRelationAsync(TenantId tenantId, EntityRelation relation) { RelationCompositeKey key = new RelationCompositeKey(relation); return service.submit( () -> deleteRelationIfExists(key)); } @Override - public boolean deleteRelation(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public boolean deleteRelation(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { RelationCompositeKey key = getRelationCompositeKey(from, to, relationType, typeGroup); return deleteRelationIfExists(key); } @Override - public ListenableFuture deleteRelationAsync(EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { + public ListenableFuture deleteRelationAsync(TenantId tenantId, EntityId from, EntityId to, String relationType, RelationTypeGroup typeGroup) { RelationCompositeKey key = getRelationCompositeKey(from, to, relationType, typeGroup); return service.submit( () -> deleteRelationIfExists(key)); @@ -159,7 +160,7 @@ public class JpaRelationDao extends JpaAbstractDaoListeningExecutorService imple } @Override - public boolean deleteOutboundRelations(EntityId entity) { + public boolean deleteOutboundRelations(TenantId tenantId, EntityId entity) { boolean relationExistsBeforeDelete = relationRepository .findAllByFromIdAndFromType(UUIDConverter.fromTimeUUID(entity.getId()), entity.getEntityType().name()) .size() > 0; @@ -170,7 +171,7 @@ public class JpaRelationDao extends JpaAbstractDaoListeningExecutorService imple } @Override - public ListenableFuture deleteOutboundRelationsAsync(EntityId entity) { + public ListenableFuture deleteOutboundRelationsAsync(TenantId tenantId, EntityId entity) { return service.submit( () -> { boolean relationExistsBeforeDelete = relationRepository @@ -184,7 +185,7 @@ public class JpaRelationDao extends JpaAbstractDaoListeningExecutorService imple } @Override - public ListenableFuture> findRelations(EntityId from, String relationType, RelationTypeGroup typeGroup, EntityType childType, TimePageLink pageLink) { + public ListenableFuture> findRelations(TenantId tenantId, EntityId from, String relationType, RelationTypeGroup typeGroup, EntityType childType, TimePageLink pageLink) { Specification timeSearchSpec = JpaAbstractSearchTimeDao.getTimeSearchPageSpec(pageLink, "toId"); Specification fieldsSpec = getEntityFieldsSpec(from, relationType, typeGroup, childType); Sort.Direction sortDirection = pageLink.isAscOrder() ? Sort.Direction.ASC : Sort.Direction.DESC; diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/settings/JpaAdminSettingsDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/settings/JpaAdminSettingsDao.java index 4d200fff71..7a4e09b4a7 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/settings/JpaAdminSettingsDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/settings/JpaAdminSettingsDao.java @@ -20,6 +20,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.sql.AdminSettingsEntity; import org.thingsboard.server.dao.settings.AdminSettingsDao; @@ -45,7 +46,7 @@ public class JpaAdminSettingsDao extends JpaAbstractDao } @Override - public List findTenantsByRegion(String region, TextPageLink pageLink) { + public List findTenantsByRegion(TenantId tenantId, String region, TextPageLink pageLink) { return DaoUtil.convertDataList(tenantRepository .findByRegionNextPage( region, diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/timeseries/JpaTimeseriesDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/timeseries/JpaTimeseriesDao.java index 04227a3825..312014861f 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/timeseries/JpaTimeseriesDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/timeseries/JpaTimeseriesDao.java @@ -31,6 +31,7 @@ import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.UUIDConverter; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.Aggregation; import org.thingsboard.server.common.data.kv.BaseReadTsKvQuery; import org.thingsboard.server.common.data.kv.BasicTsKvEntry; @@ -110,10 +111,10 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp } @Override - public ListenableFuture> findAllAsync(EntityId entityId, List queries) { + public ListenableFuture> findAllAsync(TenantId tenantId, EntityId entityId, List queries) { List>> futures = queries .stream() - .map(query -> findAllAsync(entityId, query)) + .map(query -> findAllAsync(tenantId, entityId, query)) .collect(Collectors.toList()); return Futures.transform(Futures.allAsList(futures), new Function>, List>() { @Nullable @@ -129,7 +130,7 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp }, service); } - private ListenableFuture> findAllAsync(EntityId entityId, ReadTsKvQuery query) { + private ListenableFuture> findAllAsync(TenantId tenantId, EntityId entityId, ReadTsKvQuery query) { if (query.getAggregation() == Aggregation.NONE) { return findAllAsyncWithLimit(entityId, query); } else { @@ -251,7 +252,7 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp } @Override - public ListenableFuture findLatest(EntityId entityId, String key) { + public ListenableFuture findLatest(TenantId tenantId, EntityId entityId, String key) { TsKvLatestCompositeKey compositeKey = new TsKvLatestCompositeKey( entityId.getEntityType(), @@ -268,7 +269,7 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp } @Override - public ListenableFuture> findAllLatest(EntityId entityId) { + public ListenableFuture> findAllLatest(TenantId tenantId, EntityId entityId) { return Futures.immediateFuture( DaoUtil.convertDataList(Lists.newArrayList( tsKvLatestRepository.findAllByEntityTypeAndEntityId( @@ -277,7 +278,7 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp } @Override - public ListenableFuture save(EntityId entityId, TsKvEntry tsKvEntry, long ttl) { + public ListenableFuture save(TenantId tenantId, EntityId entityId, TsKvEntry tsKvEntry, long ttl) { TsKvEntity entity = new TsKvEntity(); entity.setEntityType(entityId.getEntityType()); entity.setEntityId(fromTimeUUID(entityId.getId())); @@ -295,12 +296,12 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp } @Override - public ListenableFuture savePartition(EntityId entityId, long tsKvEntryTs, String key, long ttl) { + public ListenableFuture savePartition(TenantId tenantId, EntityId entityId, long tsKvEntryTs, String key, long ttl) { return insertService.submit(() -> null); } @Override - public ListenableFuture saveLatest(EntityId entityId, TsKvEntry tsKvEntry) { + public ListenableFuture saveLatest(TenantId tenantId, EntityId entityId, TsKvEntry tsKvEntry) { TsKvLatestEntity latestEntity = new TsKvLatestEntity(); latestEntity.setEntityType(entityId.getEntityType()); latestEntity.setEntityId(fromTimeUUID(entityId.getId())); @@ -317,7 +318,7 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp } @Override - public ListenableFuture remove(EntityId entityId, DeleteTsKvQuery query) { + public ListenableFuture remove(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) { return service.submit(() -> { tsKvRepository.delete( fromTimeUUID(entityId.getId()), @@ -330,8 +331,8 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp } @Override - public ListenableFuture removeLatest(EntityId entityId, DeleteTsKvQuery query) { - ListenableFuture latestFuture = findLatest(entityId, query.getKey()); + public ListenableFuture removeLatest(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) { + ListenableFuture latestFuture = findLatest(tenantId, entityId, query.getKey()); ListenableFuture booleanFuture = Futures.transform(latestFuture, tsKvEntry -> { long ts = tsKvEntry.getTs(); @@ -359,7 +360,7 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp if (query.getRewriteLatestIfDeleted()) { ListenableFuture savedLatestFuture = Futures.transformAsync(booleanFuture, isRemove -> { if (isRemove) { - return getNewLatestEntryFuture(entityId, query); + return getNewLatestEntryFuture(tenantId, entityId, query); } return Futures.immediateFuture(null); }, service); @@ -382,16 +383,16 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp return resultFuture; } - private ListenableFuture getNewLatestEntryFuture(EntityId entityId, DeleteTsKvQuery query) { + private ListenableFuture getNewLatestEntryFuture(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) { long startTs = 0; long endTs = query.getStartTs() - 1; ReadTsKvQuery findNewLatestQuery = new BaseReadTsKvQuery(query.getKey(), startTs, endTs, endTs - startTs, 1, Aggregation.NONE, DESC_ORDER); - ListenableFuture> future = findAllAsync(entityId, findNewLatestQuery); + ListenableFuture> future = findAllAsync(tenantId, entityId, findNewLatestQuery); return Futures.transformAsync(future, entryList -> { if (entryList.size() == 1) { - return saveLatest(entityId, entryList.get(0)); + return saveLatest(tenantId, entityId, entryList.get(0)); } else { log.trace("Could not find new latest value for [{}], key - {}", entityId, query.getKey()); } @@ -400,7 +401,7 @@ public class JpaTimeseriesDao extends JpaAbstractDaoListeningExecutorService imp } @Override - public ListenableFuture removePartition(EntityId entityId, DeleteTsKvQuery query) { + public ListenableFuture removePartition(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) { return service.submit(() -> null); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/user/JpaUserCredentialsDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/user/JpaUserCredentialsDao.java index d81db664b1..25d650c420 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/user/JpaUserCredentialsDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/user/JpaUserCredentialsDao.java @@ -19,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.UUIDConverter; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.UserCredentials; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.sql.UserCredentialsEntity; @@ -49,17 +50,17 @@ public class JpaUserCredentialsDao extends JpaAbstractDao imple } @Override - public User findByEmail(String email) { + public User findByEmail(TenantId tenantId, String email) { return DaoUtil.getData(userRepository.findByEmail(email)); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/widget/JpaWidgetsBundleDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/widget/JpaWidgetsBundleDao.java index 12dea322fb..add162c533 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/widget/JpaWidgetsBundleDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/widget/JpaWidgetsBundleDao.java @@ -20,6 +20,7 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.UUIDConverter; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.widget.WidgetsBundle; import org.thingsboard.server.dao.DaoUtil; @@ -60,7 +61,7 @@ public class JpaWidgetsBundleDao extends JpaAbstractSearchTextDao findSystemWidgetsBundles(TextPageLink pageLink) { + public List findSystemWidgetsBundles(TenantId tenantId, TextPageLink pageLink) { return DaoUtil.convertDataList( widgetsBundleRepository .findSystemWidgetsBundles( diff --git a/dao/src/main/java/org/thingsboard/server/dao/tenant/CassandraTenantDao.java b/dao/src/main/java/org/thingsboard/server/dao/tenant/CassandraTenantDao.java index 1c3a7797b8..0599fb807c 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/tenant/CassandraTenantDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/tenant/CassandraTenantDao.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.tenant; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.nosql.TenantEntity; @@ -48,9 +49,9 @@ public class CassandraTenantDao extends CassandraAbstractSearchTextDao findTenantsByRegion(String region, TextPageLink pageLink) { + public List findTenantsByRegion(TenantId tenantId, String region, TextPageLink pageLink) { log.debug("Try to find tenants by region [{}] and pageLink [{}]", region, pageLink); - List tenantEntities = findPageWithTextSearch(TENANT_BY_REGION_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List tenantEntities = findPageWithTextSearch(tenantId, TENANT_BY_REGION_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(TENANT_REGION_PROPERTY, region)), pageLink); log.trace("Found tenants [{}] by region [{}] and pageLink [{}]", tenantEntities, region, pageLink); diff --git a/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantDao.java b/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantDao.java index 2f7a898c94..5ff2557ea0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantDao.java @@ -16,6 +16,7 @@ package org.thingsboard.server.dao.tenant; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.Dao; @@ -29,7 +30,7 @@ public interface TenantDao extends Dao { * @param tenant the tenant object * @return saved tenant object */ - Tenant save(Tenant tenant); + Tenant save(TenantId tenantId, Tenant tenant); /** * Find tenants by region and page link. @@ -38,6 +39,6 @@ public interface TenantDao extends Dao { * @param pageLink the page link * @return the list of tenant objects */ - List findTenantsByRegion(String region, TextPageLink pageLink); + List findTenantsByRegion(TenantId tenantId, String region, TextPageLink pageLink); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantService.java b/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantService.java index d421ce6bad..61aff46616 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantService.java @@ -25,7 +25,7 @@ public interface TenantService { Tenant findTenantById(TenantId tenantId); - ListenableFuture findTenantByIdAsync(TenantId customerId); + ListenableFuture findTenantByIdAsync(TenantId callerId, TenantId tenantId); Tenant saveTenant(Tenant tenant); diff --git a/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantServiceImpl.java index 189c7139ac..f18d645415 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/tenant/TenantServiceImpl.java @@ -21,6 +21,7 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageData; import org.thingsboard.server.common.data.page.TextPageLink; @@ -80,22 +81,22 @@ public class TenantServiceImpl extends AbstractEntityService implements TenantSe public Tenant findTenantById(TenantId tenantId) { log.trace("Executing findTenantById [{}]", tenantId); Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId); - return tenantDao.findById(tenantId.getId()); + return tenantDao.findById(tenantId, tenantId.getId()); } @Override - public ListenableFuture findTenantByIdAsync(TenantId tenantId) { + public ListenableFuture findTenantByIdAsync(TenantId callerId, TenantId tenantId) { log.trace("Executing TenantIdAsync [{}]", tenantId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); - return tenantDao.findByIdAsync(tenantId.getId()); + return tenantDao.findByIdAsync(callerId, tenantId.getId()); } @Override public Tenant saveTenant(Tenant tenant) { log.trace("Executing saveTenant [{}]", tenant); tenant.setRegion(DEFAULT_TENANT_REGION); - tenantValidator.validate(tenant); - return tenantDao.save(tenant); + tenantValidator.validate(tenant, Tenant::getId); + return tenantDao.save(tenant.getId(), tenant); } @Override @@ -110,28 +111,28 @@ public class TenantServiceImpl extends AbstractEntityService implements TenantSe deviceService.deleteDevicesByTenantId(tenantId); userService.deleteTenantAdmins(tenantId); ruleChainService.deleteRuleChainsByTenantId(tenantId); - tenantDao.removeById(tenantId.getId()); - deleteEntityRelations(tenantId); + tenantDao.removeById(tenantId, tenantId.getId()); + deleteEntityRelations(tenantId, tenantId); } @Override public TextPageData findTenants(TextPageLink pageLink) { log.trace("Executing findTenants pageLink [{}]", pageLink); Validator.validatePageLink(pageLink, "Incorrect page link " + pageLink); - List tenants = tenantDao.findTenantsByRegion(DEFAULT_TENANT_REGION, pageLink); + List tenants = tenantDao.findTenantsByRegion(new TenantId(EntityId.NULL_UUID), DEFAULT_TENANT_REGION, pageLink); return new TextPageData<>(tenants, pageLink); } @Override public void deleteTenants() { log.trace("Executing deleteTenants"); - tenantsRemover.removeEntities(DEFAULT_TENANT_REGION); + tenantsRemover.removeEntities(new TenantId(EntityId.NULL_UUID),DEFAULT_TENANT_REGION); } private DataValidator tenantValidator = new DataValidator() { @Override - protected void validateDataImpl(Tenant tenant) { + protected void validateDataImpl(TenantId tenantId, Tenant tenant) { if (StringUtils.isEmpty(tenant.getTitle())) { throw new DataValidationException("Tenant title should be specified!"); } @@ -145,12 +146,12 @@ public class TenantServiceImpl extends AbstractEntityService implements TenantSe new PaginatedRemover() { @Override - protected List findEntities(String region, TextPageLink pageLink) { - return tenantDao.findTenantsByRegion(region, pageLink); + protected List findEntities(TenantId tenantId, String region, TextPageLink pageLink) { + return tenantDao.findTenantsByRegion(tenantId, region, pageLink); } @Override - protected void removeEntity(Tenant entity) { + protected void removeEntity(TenantId tenantId, Tenant entity) { deleteTenant(new TenantId(entity.getUuidId())); } }; diff --git a/dao/src/main/java/org/thingsboard/server/dao/timeseries/BaseTimeseriesService.java b/dao/src/main/java/org/thingsboard/server/dao/timeseries/BaseTimeseriesService.java index 10064999e1..b2ff2ca898 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/timeseries/BaseTimeseriesService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/timeseries/BaseTimeseriesService.java @@ -26,6 +26,7 @@ import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.EntityViewId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.Aggregation; import org.thingsboard.server.common.data.kv.BaseReadTsKvQuery; import org.thingsboard.server.common.data.kv.DeleteTsKvQuery; @@ -62,27 +63,27 @@ public class BaseTimeseriesService implements TimeseriesService { private EntityViewService entityViewService; @Override - public ListenableFuture> findAll(EntityId entityId, List queries) { + public ListenableFuture> findAll(TenantId tenantId, EntityId entityId, List queries) { validate(entityId); queries.forEach(this::validate); if (entityId.getEntityType().equals(EntityType.ENTITY_VIEW)) { - EntityView entityView = entityViewService.findEntityViewById((EntityViewId) entityId); + EntityView entityView = entityViewService.findEntityViewById(tenantId, (EntityViewId) entityId); List filteredQueries = queries.stream() .filter(query -> entityView.getKeys().getTimeseries().isEmpty() || entityView.getKeys().getTimeseries().contains(query.getKey())) .collect(Collectors.toList()); - return timeseriesDao.findAllAsync(entityView.getEntityId(), updateQueriesForEntityView(entityView, filteredQueries)); + return timeseriesDao.findAllAsync(tenantId, entityView.getEntityId(), updateQueriesForEntityView(entityView, filteredQueries)); } - return timeseriesDao.findAllAsync(entityId, queries); + return timeseriesDao.findAllAsync(tenantId, entityId, queries); } @Override - public ListenableFuture> findLatest(EntityId entityId, Collection keys) { + public ListenableFuture> findLatest(TenantId tenantId, EntityId entityId, Collection keys) { validate(entityId); List> futures = Lists.newArrayListWithExpectedSize(keys.size()); keys.forEach(key -> Validator.validateString(key, "Incorrect key " + key)); if (entityId.getEntityType().equals(EntityType.ENTITY_VIEW)) { - EntityView entityView = entityViewService.findEntityViewById((EntityViewId) entityId); + EntityView entityView = entityViewService.findEntityViewById(tenantId, (EntityViewId) entityId); List filteredKeys = new ArrayList<>(keys); if (entityView.getKeys() != null && entityView.getKeys().getTimeseries() != null && !entityView.getKeys().getTimeseries().isEmpty()) { @@ -97,61 +98,61 @@ public class BaseTimeseriesService implements TimeseriesService { .collect(Collectors.toList()); if (queries.size() > 0) { - return timeseriesDao.findAllAsync(entityView.getEntityId(), queries); + return timeseriesDao.findAllAsync(tenantId, entityView.getEntityId(), queries); } else { return Futures.immediateFuture(new ArrayList<>()); } } - keys.forEach(key -> futures.add(timeseriesDao.findLatest(entityId, key))); + keys.forEach(key -> futures.add(timeseriesDao.findLatest(tenantId, entityId, key))); return Futures.allAsList(futures); } @Override - public ListenableFuture> findAllLatest(EntityId entityId) { + public ListenableFuture> findAllLatest(TenantId tenantId, EntityId entityId) { validate(entityId); if (entityId.getEntityType().equals(EntityType.ENTITY_VIEW)) { - EntityView entityView = entityViewService.findEntityViewById((EntityViewId) entityId); + EntityView entityView = entityViewService.findEntityViewById(tenantId, (EntityViewId) entityId); if (entityView.getKeys() != null && entityView.getKeys().getTimeseries() != null && !entityView.getKeys().getTimeseries().isEmpty()) { - return findLatest(entityId, entityView.getKeys().getTimeseries()); + return findLatest(tenantId, entityId, entityView.getKeys().getTimeseries()); } else { return Futures.immediateFuture(new ArrayList<>()); } } else { - return timeseriesDao.findAllLatest(entityId); + return timeseriesDao.findAllLatest(tenantId, entityId); } } @Override - public ListenableFuture> save(EntityId entityId, TsKvEntry tsKvEntry) { + public ListenableFuture> save(TenantId tenantId, EntityId entityId, TsKvEntry tsKvEntry) { validate(entityId); if (tsKvEntry == null) { throw new IncorrectParameterException("Key value entry can't be null"); } List> futures = Lists.newArrayListWithExpectedSize(INSERTS_PER_ENTRY); - saveAndRegisterFutures(futures, entityId, tsKvEntry, 0L); + saveAndRegisterFutures(tenantId, futures, entityId, tsKvEntry, 0L); return Futures.allAsList(futures); } @Override - public ListenableFuture> save(EntityId entityId, List tsKvEntries, long ttl) { + public ListenableFuture> save(TenantId tenantId, EntityId entityId, List tsKvEntries, long ttl) { List> futures = Lists.newArrayListWithExpectedSize(tsKvEntries.size() * INSERTS_PER_ENTRY); for (TsKvEntry tsKvEntry : tsKvEntries) { if (tsKvEntry == null) { throw new IncorrectParameterException("Key value entry can't be null"); } - saveAndRegisterFutures(futures, entityId, tsKvEntry, ttl); + saveAndRegisterFutures(tenantId, futures, entityId, tsKvEntry, ttl); } return Futures.allAsList(futures); } - private void saveAndRegisterFutures(List> futures, EntityId entityId, TsKvEntry tsKvEntry, long ttl) { + private void saveAndRegisterFutures(TenantId tenantId, List> futures, EntityId entityId, TsKvEntry tsKvEntry, long ttl) { if (entityId.getEntityType().equals(EntityType.ENTITY_VIEW)) { throw new IncorrectParameterException("Telemetry data can't be stored for entity view. Only read only"); } - futures.add(timeseriesDao.savePartition(entityId, tsKvEntry.getTs(), tsKvEntry.getKey(), ttl)); - futures.add(timeseriesDao.saveLatest(entityId, tsKvEntry)); - futures.add(timeseriesDao.save(entityId, tsKvEntry, ttl)); + futures.add(timeseriesDao.savePartition(tenantId, entityId, tsKvEntry.getTs(), tsKvEntry.getKey(), ttl)); + futures.add(timeseriesDao.saveLatest(tenantId, entityId, tsKvEntry)); + futures.add(timeseriesDao.save(tenantId, entityId, tsKvEntry, ttl)); } private List updateQueriesForEntityView(EntityView entityView, List queries) { @@ -174,20 +175,20 @@ public class BaseTimeseriesService implements TimeseriesService { } @Override - public ListenableFuture> remove(EntityId entityId, List deleteTsKvQueries) { + public ListenableFuture> remove(TenantId tenantId, EntityId entityId, List deleteTsKvQueries) { validate(entityId); deleteTsKvQueries.forEach(BaseTimeseriesService::validate); List> futures = Lists.newArrayListWithExpectedSize(deleteTsKvQueries.size() * DELETES_PER_ENTRY); for (DeleteTsKvQuery tsKvQuery : deleteTsKvQueries) { - deleteAndRegisterFutures(futures, entityId, tsKvQuery); + deleteAndRegisterFutures(tenantId, futures, entityId, tsKvQuery); } return Futures.allAsList(futures); } - private void deleteAndRegisterFutures(List> futures, EntityId entityId, DeleteTsKvQuery query) { - futures.add(timeseriesDao.remove(entityId, query)); - futures.add(timeseriesDao.removeLatest(entityId, query)); - futures.add(timeseriesDao.removePartition(entityId, query)); + private void deleteAndRegisterFutures(TenantId tenantId, List> futures, EntityId entityId, DeleteTsKvQuery query) { + futures.add(timeseriesDao.remove(tenantId, entityId, query)); + futures.add(timeseriesDao.removeLatest(tenantId, entityId, query)); + futures.add(timeseriesDao.removePartition(tenantId, entityId, query)); } private static void validate(EntityId entityId) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/timeseries/CassandraBaseTimeseriesDao.java b/dao/src/main/java/org/thingsboard/server/dao/timeseries/CassandraBaseTimeseriesDao.java index fdc69f9262..c8025e0a31 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/timeseries/CassandraBaseTimeseriesDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/timeseries/CassandraBaseTimeseriesDao.java @@ -34,6 +34,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.Aggregation; import org.thingsboard.server.common.data.kv.BaseReadTsKvQuery; import org.thingsboard.server.common.data.kv.BasicTsKvEntry; @@ -131,8 +132,8 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem } @Override - public ListenableFuture> findAllAsync(EntityId entityId, List queries) { - List>> futures = queries.stream().map(query -> findAllAsync(entityId, query)).collect(Collectors.toList()); + public ListenableFuture> findAllAsync(TenantId tenantId, EntityId entityId, List queries) { + List>> futures = queries.stream().map(query -> findAllAsync(tenantId, entityId, query)).collect(Collectors.toList()); return Futures.transform(Futures.allAsList(futures), new Function>, List>() { @Nullable @Override @@ -148,9 +149,9 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem } - private ListenableFuture> findAllAsync(EntityId entityId, ReadTsKvQuery query) { + private ListenableFuture> findAllAsync(TenantId tenantId, EntityId entityId, ReadTsKvQuery query) { if (query.getAggregation() == Aggregation.NONE) { - return findAllAsyncWithLimit(entityId, query); + return findAllAsyncWithLimit(tenantId, entityId, query); } else { long step = Math.max(query.getInterval(), MIN_AGGREGATION_STEP_MS); long stepTs = query.getStartTs(); @@ -159,7 +160,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem long startTs = stepTs; long endTs = stepTs + step; ReadTsKvQuery subQuery = new BaseReadTsKvQuery(query.getKey(), startTs, endTs, step, 1, query.getAggregation(), query.getOrderBy()); - futures.add(findAndAggregateAsync(entityId, subQuery, toPartitionTs(startTs), toPartitionTs(endTs))); + futures.add(findAndAggregateAsync(tenantId, entityId, subQuery, toPartitionTs(startTs), toPartitionTs(endTs))); stepTs = endTs; } ListenableFuture>> future = Futures.allAsList(futures); @@ -177,25 +178,25 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem return tsFormat.getTruncateUnit().equals(TsPartitionDate.EPOCH_START); } - private ListenableFuture> getPartitionsFuture(ReadTsKvQuery query, EntityId entityId, long minPartition, long maxPartition) { + private ListenableFuture> getPartitionsFuture(TenantId tenantId, ReadTsKvQuery query, EntityId entityId, long minPartition, long maxPartition) { if (isFixedPartitioning()) { //no need to fetch partitions from DB return Futures.immediateFuture(FIXED_PARTITION); } - ResultSetFuture partitionsFuture = fetchPartitions(entityId, query.getKey(), minPartition, maxPartition); + ResultSetFuture partitionsFuture = fetchPartitions(tenantId, entityId, query.getKey(), minPartition, maxPartition); return Futures.transform(partitionsFuture, getPartitionsArrayFunction(), readResultsProcessingExecutor); } - private ListenableFuture> findAllAsyncWithLimit(EntityId entityId, ReadTsKvQuery query) { + private ListenableFuture> findAllAsyncWithLimit(TenantId tenantId, EntityId entityId, ReadTsKvQuery query) { long minPartition = toPartitionTs(query.getStartTs()); long maxPartition = toPartitionTs(query.getEndTs()); - final ListenableFuture> partitionsListFuture = getPartitionsFuture(query, entityId, minPartition, maxPartition); + final ListenableFuture> partitionsListFuture = getPartitionsFuture(tenantId, query, entityId, minPartition, maxPartition); final SimpleListenableFuture> resultFuture = new SimpleListenableFuture<>(); Futures.addCallback(partitionsListFuture, new FutureCallback>() { @Override public void onSuccess(@Nullable List partitions) { TsKvQueryCursor cursor = new TsKvQueryCursor(entityId.getEntityType().name(), entityId.getId(), query, partitions); - findAllAsyncSequentiallyWithLimit(cursor, resultFuture); + findAllAsyncSequentiallyWithLimit(tenantId, cursor, resultFuture); } @Override @@ -212,7 +213,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem return tsFormat.truncatedTo(time).toInstant(ZoneOffset.UTC).toEpochMilli(); } - private void findAllAsyncSequentiallyWithLimit(final TsKvQueryCursor cursor, final SimpleListenableFuture> resultFuture) { + private void findAllAsyncSequentiallyWithLimit(TenantId tenantId, final TsKvQueryCursor cursor, final SimpleListenableFuture> resultFuture) { if (cursor.isFull() || !cursor.hasNextPartition()) { resultFuture.set(cursor.getData()); } else { @@ -226,11 +227,11 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem stmt.setLong(5, cursor.getEndTs()); stmt.setInt(6, cursor.getCurrentLimit()); - Futures.addCallback(executeAsyncRead(stmt), new FutureCallback() { + Futures.addCallback(executeAsyncRead(tenantId, stmt), new FutureCallback() { @Override public void onSuccess(@Nullable ResultSet result) { cursor.addData(convertResultToTsKvEntryList(result == null ? Collections.emptyList() : result.all())); - findAllAsyncSequentiallyWithLimit(cursor, resultFuture); + findAllAsyncSequentiallyWithLimit(tenantId, cursor, resultFuture); } @Override @@ -241,15 +242,15 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem } } - private ListenableFuture> findAndAggregateAsync(EntityId entityId, ReadTsKvQuery query, long minPartition, long maxPartition) { + private ListenableFuture> findAndAggregateAsync(TenantId tenantId, EntityId entityId, ReadTsKvQuery query, long minPartition, long maxPartition) { final Aggregation aggregation = query.getAggregation(); final String key = query.getKey(); final long startTs = query.getStartTs(); final long endTs = query.getEndTs(); final long ts = startTs + (endTs - startTs) / 2; - ListenableFuture> partitionsListFuture = getPartitionsFuture(query, entityId, minPartition, maxPartition); + ListenableFuture> partitionsListFuture = getPartitionsFuture(tenantId, query, entityId, minPartition, maxPartition); ListenableFuture> aggregationChunks = Futures.transformAsync(partitionsListFuture, - getFetchChunksAsyncFunction(entityId, key, aggregation, startTs, endTs), readResultsProcessingExecutor); + getFetchChunksAsyncFunction(tenantId, entityId, key, aggregation, startTs, endTs), readResultsProcessingExecutor); return Futures.transform(aggregationChunks, new AggregatePartitionsFunction(aggregation, key, ts), readResultsProcessingExecutor); } @@ -259,7 +260,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem .map(row -> row.getLong(ModelConstants.PARTITION_COLUMN)).collect(Collectors.toList()); } - private AsyncFunction, List> getFetchChunksAsyncFunction(EntityId entityId, String key, Aggregation aggregation, long startTs, long endTs) { + private AsyncFunction, List> getFetchChunksAsyncFunction(TenantId tenantId, EntityId entityId, String key, Aggregation aggregation, long startTs, long endTs) { return partitions -> { try { PreparedStatement proto = getFetchStmt(aggregation, DESC_ORDER); @@ -274,7 +275,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem stmt.setLong(4, startTs); stmt.setLong(5, endTs); log.debug(GENERATED_QUERY_FOR_ENTITY_TYPE_AND_ENTITY_ID, stmt, entityId.getEntityType(), entityId.getId()); - futures.add(executeAsyncRead(stmt)); + futures.add(executeAsyncRead(tenantId, stmt)); } return Futures.allAsList(futures); } catch (Throwable e) { @@ -285,26 +286,26 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem } @Override - public ListenableFuture findLatest(EntityId entityId, String key) { + public ListenableFuture findLatest(TenantId tenantId, EntityId entityId, String key) { BoundStatement stmt = getFindLatestStmt().bind(); stmt.setString(0, entityId.getEntityType().name()); stmt.setUUID(1, entityId.getId()); stmt.setString(2, key); log.debug(GENERATED_QUERY_FOR_ENTITY_TYPE_AND_ENTITY_ID, stmt, entityId.getEntityType(), entityId.getId()); - return getFuture(executeAsyncRead(stmt), rs -> convertResultToTsKvEntry(key, rs.one())); + return getFuture(executeAsyncRead(tenantId, stmt), rs -> convertResultToTsKvEntry(key, rs.one())); } @Override - public ListenableFuture> findAllLatest(EntityId entityId) { + public ListenableFuture> findAllLatest(TenantId tenantId, EntityId entityId) { BoundStatement stmt = getFindAllLatestStmt().bind(); stmt.setString(0, entityId.getEntityType().name()); stmt.setUUID(1, entityId.getId()); log.debug(GENERATED_QUERY_FOR_ENTITY_TYPE_AND_ENTITY_ID, stmt, entityId.getEntityType(), entityId.getId()); - return getFuture(executeAsyncRead(stmt), rs -> convertResultToTsKvEntryList(rs.all())); + return getFuture(executeAsyncRead(tenantId, stmt), rs -> convertResultToTsKvEntryList(rs.all())); } @Override - public ListenableFuture save(EntityId entityId, TsKvEntry tsKvEntry, long ttl) { + public ListenableFuture save(TenantId tenantId, EntityId entityId, TsKvEntry tsKvEntry, long ttl) { ttl = computeTtl(ttl); long partition = toPartitionTs(tsKvEntry.getTs()); DataType type = tsKvEntry.getDataType(); @@ -318,11 +319,11 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem if (ttl > 0) { stmt.setInt(6, (int) ttl); } - return getFuture(executeAsyncWrite(stmt), rs -> null); + return getFuture(executeAsyncWrite(tenantId, stmt), rs -> null); } @Override - public ListenableFuture savePartition(EntityId entityId, long tsKvEntryTs, String key, long ttl) { + public ListenableFuture savePartition(TenantId tenantId, EntityId entityId, long tsKvEntryTs, String key, long ttl) { if (isFixedPartitioning()) { return Futures.immediateFuture(null); } @@ -337,7 +338,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem if (ttl > 0) { stmt.setInt(4, (int) ttl); } - return getFuture(executeAsyncWrite(stmt), rs -> null); + return getFuture(executeAsyncWrite(tenantId, stmt), rs -> null); } private long computeTtl(long ttl) { @@ -352,7 +353,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem } @Override - public ListenableFuture saveLatest(EntityId entityId, TsKvEntry tsKvEntry) { + public ListenableFuture saveLatest(TenantId tenantId, EntityId entityId, TsKvEntry tsKvEntry) { BoundStatement stmt = getLatestStmt().bind() .setString(0, entityId.getEntityType().name()) .setUUID(1, entityId.getId()) @@ -362,15 +363,15 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem .set(5, tsKvEntry.getStrValue().orElse(null), String.class) .set(6, tsKvEntry.getLongValue().orElse(null), Long.class) .set(7, tsKvEntry.getDoubleValue().orElse(null), Double.class); - return getFuture(executeAsyncWrite(stmt), rs -> null); + return getFuture(executeAsyncWrite(tenantId, stmt), rs -> null); } @Override - public ListenableFuture remove(EntityId entityId, DeleteTsKvQuery query) { + public ListenableFuture remove(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) { long minPartition = toPartitionTs(query.getStartTs()); long maxPartition = toPartitionTs(query.getEndTs()); - ResultSetFuture partitionsFuture = fetchPartitions(entityId, query.getKey(), minPartition, maxPartition); + ResultSetFuture partitionsFuture = fetchPartitions(tenantId, entityId, query.getKey(), minPartition, maxPartition); final SimpleListenableFuture resultFuture = new SimpleListenableFuture<>(); final ListenableFuture> partitionsListFuture = Futures.transform(partitionsFuture, getPartitionsArrayFunction(), readResultsProcessingExecutor); @@ -379,7 +380,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem @Override public void onSuccess(@Nullable List partitions) { QueryCursor cursor = new QueryCursor(entityId.getEntityType().name(), entityId.getId(), query, partitions); - deleteAsync(cursor, resultFuture); + deleteAsync(tenantId, cursor, resultFuture); } @Override @@ -390,7 +391,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem return resultFuture; } - private void deleteAsync(final QueryCursor cursor, final SimpleListenableFuture resultFuture) { + private void deleteAsync(TenantId tenantId, final QueryCursor cursor, final SimpleListenableFuture resultFuture) { if (!cursor.hasNextPartition()) { resultFuture.set(null); } else { @@ -403,10 +404,10 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem stmt.setLong(4, cursor.getStartTs()); stmt.setLong(5, cursor.getEndTs()); - Futures.addCallback(executeAsyncWrite(stmt), new FutureCallback() { + Futures.addCallback(executeAsyncWrite(tenantId, stmt), new FutureCallback() { @Override public void onSuccess(@Nullable ResultSet result) { - deleteAsync(cursor, resultFuture); + deleteAsync(tenantId, cursor, resultFuture); } @Override @@ -431,8 +432,8 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem } @Override - public ListenableFuture removeLatest(EntityId entityId, DeleteTsKvQuery query) { - ListenableFuture latestEntryFuture = findLatest(entityId, query.getKey()); + public ListenableFuture removeLatest(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) { + ListenableFuture latestEntryFuture = findLatest(tenantId, entityId, query.getKey()); ListenableFuture booleanFuture = Futures.transform(latestEntryFuture, latestEntry -> { long ts = latestEntry.getTs(); @@ -446,7 +447,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem ListenableFuture removedLatestFuture = Futures.transformAsync(booleanFuture, isRemove -> { if (isRemove) { - return deleteLatest(entityId, query.getKey()); + return deleteLatest(tenantId, entityId, query.getKey()); } return Futures.immediateFuture(null); }, readResultsProcessingExecutor); @@ -458,7 +459,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem if (query.getRewriteLatestIfDeleted()) { ListenableFuture savedLatestFuture = Futures.transformAsync(booleanFuture, isRemove -> { if (isRemove) { - return getNewLatestEntryFuture(entityId, query); + return getNewLatestEntryFuture(tenantId, entityId, query); } return Futures.immediateFuture(null); }, readResultsProcessingExecutor); @@ -481,16 +482,16 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem return resultFuture; } - private ListenableFuture getNewLatestEntryFuture(EntityId entityId, DeleteTsKvQuery query) { + private ListenableFuture getNewLatestEntryFuture(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) { long startTs = 0; long endTs = query.getStartTs() - 1; ReadTsKvQuery findNewLatestQuery = new BaseReadTsKvQuery(query.getKey(), startTs, endTs, endTs - startTs, 1, Aggregation.NONE, DESC_ORDER); - ListenableFuture> future = findAllAsync(entityId, findNewLatestQuery); + ListenableFuture> future = findAllAsync(tenantId, entityId, findNewLatestQuery); return Futures.transformAsync(future, entryList -> { if (entryList.size() == 1) { - return saveLatest(entityId, entryList.get(0)); + return saveLatest(tenantId, entityId, entryList.get(0)); } else { log.trace("Could not find new latest value for [{}], key - {}", entityId, query.getKey()); } @@ -498,23 +499,23 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem }, readResultsProcessingExecutor); } - private ListenableFuture deleteLatest(EntityId entityId, String key) { + private ListenableFuture deleteLatest(TenantId tenantId, EntityId entityId, String key) { Statement delete = QueryBuilder.delete().all().from(ModelConstants.TS_KV_LATEST_CF) .where(eq(ModelConstants.ENTITY_TYPE_COLUMN, entityId.getEntityType())) .and(eq(ModelConstants.ENTITY_ID_COLUMN, entityId.getId())) .and(eq(ModelConstants.KEY_COLUMN, key)); log.debug("Remove request: {}", delete.toString()); - return getFuture(executeAsyncWrite(delete), rs -> null); + return getFuture(executeAsyncWrite(tenantId, delete), rs -> null); } @Override - public ListenableFuture removePartition(EntityId entityId, DeleteTsKvQuery query) { + public ListenableFuture removePartition(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query) { long minPartition = toPartitionTs(query.getStartTs()); long maxPartition = toPartitionTs(query.getEndTs()); if (minPartition == maxPartition) { return Futures.immediateFuture(null); } else { - ResultSetFuture partitionsFuture = fetchPartitions(entityId, query.getKey(), minPartition, maxPartition); + ResultSetFuture partitionsFuture = fetchPartitions(tenantId, entityId, query.getKey(), minPartition, maxPartition); final SimpleListenableFuture resultFuture = new SimpleListenableFuture<>(); final ListenableFuture> partitionsListFuture = Futures.transform(partitionsFuture, getPartitionsArrayFunction(), readResultsProcessingExecutor); @@ -531,7 +532,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem partitionsToDelete.add(partitions.get(i)); } QueryCursor cursor = new QueryCursor(entityId.getEntityType().name(), entityId.getId(), query, partitionsToDelete); - deletePartitionAsync(cursor, resultFuture); + deletePartitionAsync(tenantId, cursor, resultFuture); } @Override @@ -543,7 +544,7 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem } } - private void deletePartitionAsync(final QueryCursor cursor, final SimpleListenableFuture resultFuture) { + private void deletePartitionAsync(TenantId tenantId, final QueryCursor cursor, final SimpleListenableFuture resultFuture) { if (!cursor.hasNextPartition()) { resultFuture.set(null); } else { @@ -554,10 +555,10 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem stmt.setLong(2, cursor.getNextPartition()); stmt.setString(3, cursor.getKey()); - Futures.addCallback(executeAsyncWrite(stmt), new FutureCallback() { + Futures.addCallback(executeAsyncWrite(tenantId, stmt), new FutureCallback() { @Override public void onSuccess(@Nullable ResultSet result) { - deletePartitionAsync(cursor, resultFuture); + deletePartitionAsync(tenantId, cursor, resultFuture); } @Override @@ -632,12 +633,12 @@ public class CassandraBaseTimeseriesDao extends CassandraAbstractAsyncDao implem * Select existing partitions from the table * {@link ModelConstants#TS_KV_PARTITIONS_CF} for the given entity */ - private ResultSetFuture fetchPartitions(EntityId entityId, String key, long minPartition, long maxPartition) { + private ResultSetFuture fetchPartitions(TenantId tenantId, EntityId entityId, String key, long minPartition, long maxPartition) { Select.Where select = QueryBuilder.select(ModelConstants.PARTITION_COLUMN).from(ModelConstants.TS_KV_PARTITIONS_CF).where(eq(ModelConstants.ENTITY_TYPE_COLUMN, entityId.getEntityType().name())) .and(eq(ModelConstants.ENTITY_ID_COLUMN, entityId.getId())).and(eq(ModelConstants.KEY_COLUMN, key)); select.and(QueryBuilder.gte(ModelConstants.PARTITION_COLUMN, minPartition)); select.and(QueryBuilder.lte(ModelConstants.PARTITION_COLUMN, maxPartition)); - return executeAsyncRead(select); + return executeAsyncRead(tenantId, select); } private PreparedStatement getSaveStmt(DataType dataType) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/timeseries/TimeseriesDao.java b/dao/src/main/java/org/thingsboard/server/dao/timeseries/TimeseriesDao.java index a8cb547c3b..a7ccfaf205 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/timeseries/TimeseriesDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/timeseries/TimeseriesDao.java @@ -17,6 +17,7 @@ package org.thingsboard.server.dao.timeseries; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.DeleteTsKvQuery; import org.thingsboard.server.common.data.kv.ReadTsKvQuery; import org.thingsboard.server.common.data.kv.TsKvEntry; @@ -28,21 +29,21 @@ import java.util.List; */ public interface TimeseriesDao { - ListenableFuture> findAllAsync(EntityId entityId, List queries); + ListenableFuture> findAllAsync(TenantId tenantId, EntityId entityId, List queries); - ListenableFuture findLatest(EntityId entityId, String key); + ListenableFuture findLatest(TenantId tenantId, EntityId entityId, String key); - ListenableFuture> findAllLatest(EntityId entityId); + ListenableFuture> findAllLatest(TenantId tenantId, EntityId entityId); - ListenableFuture save(EntityId entityId, TsKvEntry tsKvEntry, long ttl); + ListenableFuture save(TenantId tenantId, EntityId entityId, TsKvEntry tsKvEntry, long ttl); - ListenableFuture savePartition(EntityId entityId, long tsKvEntryTs, String key, long ttl); + ListenableFuture savePartition(TenantId tenantId, EntityId entityId, long tsKvEntryTs, String key, long ttl); - ListenableFuture saveLatest(EntityId entityId, TsKvEntry tsKvEntry); + ListenableFuture saveLatest(TenantId tenantId, EntityId entityId, TsKvEntry tsKvEntry); - ListenableFuture remove(EntityId entityId, DeleteTsKvQuery query); + ListenableFuture remove(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query); - ListenableFuture removeLatest(EntityId entityId, DeleteTsKvQuery query); + ListenableFuture removeLatest(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query); - ListenableFuture removePartition(EntityId entityId, DeleteTsKvQuery query); + ListenableFuture removePartition(TenantId tenantId, EntityId entityId, DeleteTsKvQuery query); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/timeseries/TimeseriesService.java b/dao/src/main/java/org/thingsboard/server/dao/timeseries/TimeseriesService.java index c5076d2774..6cfb9dd7a0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/timeseries/TimeseriesService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/timeseries/TimeseriesService.java @@ -17,6 +17,7 @@ package org.thingsboard.server.dao.timeseries; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.DeleteTsKvQuery; import org.thingsboard.server.common.data.kv.ReadTsKvQuery; import org.thingsboard.server.common.data.kv.TsKvEntry; @@ -29,15 +30,15 @@ import java.util.List; */ public interface TimeseriesService { - ListenableFuture> findAll(EntityId entityId, List queries); + ListenableFuture> findAll(TenantId tenantId, EntityId entityId, List queries); - ListenableFuture> findLatest(EntityId entityId, Collection keys); + ListenableFuture> findLatest(TenantId tenantId, EntityId entityId, Collection keys); - ListenableFuture> findAllLatest(EntityId entityId); + ListenableFuture> findAllLatest(TenantId tenantId, EntityId entityId); - ListenableFuture> save(EntityId entityId, TsKvEntry tsKvEntry); + ListenableFuture> save(TenantId tenantId, EntityId entityId, TsKvEntry tsKvEntry); - ListenableFuture> save(EntityId entityId, List tsKvEntry, long ttl); + ListenableFuture> save(TenantId tenantId, EntityId entityId, List tsKvEntry, long ttl); - ListenableFuture> remove(EntityId entityId, List queries); + ListenableFuture> remove(TenantId tenantId, EntityId entityId, List queries); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/user/CassandraUserCredentialsDao.java b/dao/src/main/java/org/thingsboard/server/dao/user/CassandraUserCredentialsDao.java index a5a86318d1..317d272c11 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/user/CassandraUserCredentialsDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/user/CassandraUserCredentialsDao.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.user; import com.datastax.driver.core.querybuilder.Select.Where; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.UserCredentials; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.ModelConstants; @@ -48,33 +49,33 @@ public class CassandraUserCredentialsDao extends CassandraAbstractModelDao findTenantAdmins(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find tenant admin users by tenantId [{}] and pageLink [{}]", tenantId, pageLink); - List userEntities = findPageWithTextSearch(ModelConstants.USER_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List userEntities = findPageWithTextSearch(new TenantId(tenantId), + ModelConstants.USER_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(ModelConstants.USER_TENANT_ID_PROPERTY, tenantId), eq(ModelConstants.USER_CUSTOMER_ID_PROPERTY, ModelConstants.NULL_UUID), eq(ModelConstants.USER_AUTHORITY_PROPERTY, Authority.TENANT_ADMIN.name())), @@ -74,7 +76,8 @@ public class CassandraUserDao extends CassandraAbstractSearchTextDao findCustomerUsers(UUID tenantId, UUID customerId, TextPageLink pageLink) { log.debug("Try to find customer users by tenantId [{}], customerId [{}] and pageLink [{}]", tenantId, customerId, pageLink); - List userEntities = findPageWithTextSearch(ModelConstants.USER_BY_CUSTOMER_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List userEntities = findPageWithTextSearch(new TenantId(tenantId), + ModelConstants.USER_BY_CUSTOMER_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(ModelConstants.USER_TENANT_ID_PROPERTY, tenantId), eq(ModelConstants.USER_CUSTOMER_ID_PROPERTY, customerId), eq(ModelConstants.USER_AUTHORITY_PROPERTY, Authority.CUSTOMER_USER.name())), diff --git a/dao/src/main/java/org/thingsboard/server/dao/user/UserCredentialsDao.java b/dao/src/main/java/org/thingsboard/server/dao/user/UserCredentialsDao.java index f1857f4ac9..112ecd86a6 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/user/UserCredentialsDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/user/UserCredentialsDao.java @@ -15,6 +15,7 @@ */ package org.thingsboard.server.dao.user; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.UserCredentials; import org.thingsboard.server.dao.Dao; @@ -31,7 +32,7 @@ public interface UserCredentialsDao extends Dao { * @param userCredentials the user credentials object * @return saved user credentials object */ - UserCredentials save(UserCredentials userCredentials); + UserCredentials save(TenantId tenantId, UserCredentials userCredentials); /** * Find user credentials by user id. @@ -39,7 +40,7 @@ public interface UserCredentialsDao extends Dao { * @param userId the user id * @return the user credentials object */ - UserCredentials findByUserId(UUID userId); + UserCredentials findByUserId(TenantId tenantId, UUID userId); /** * Find user credentials by activate token. @@ -47,7 +48,7 @@ public interface UserCredentialsDao extends Dao { * @param activateToken the activate token * @return the user credentials object */ - UserCredentials findByActivateToken(String activateToken); + UserCredentials findByActivateToken(TenantId tenantId, String activateToken); /** * Find user credentials by reset token. @@ -55,6 +56,6 @@ public interface UserCredentialsDao extends Dao { * @param resetToken the reset token * @return the user credentials object */ - UserCredentials findByResetToken(String resetToken); + UserCredentials findByResetToken(TenantId tenantId, String resetToken); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/user/UserDao.java b/dao/src/main/java/org/thingsboard/server/dao/user/UserDao.java index 55097381c3..bf23714d63 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/user/UserDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/user/UserDao.java @@ -16,6 +16,7 @@ package org.thingsboard.server.dao.user; import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.Dao; @@ -30,7 +31,7 @@ public interface UserDao extends Dao { * @param user the user object * @return saved user entity */ - User save(User user); + User save(TenantId tenantId, User user); /** * Find user by email. @@ -38,7 +39,7 @@ public interface UserDao extends Dao { * @param email the email * @return the user entity */ - User findByEmail(String email); + User findByEmail(TenantId tenantId, String email); /** * Find tenant admin users by tenantId and page link. diff --git a/dao/src/main/java/org/thingsboard/server/dao/user/UserService.java b/dao/src/main/java/org/thingsboard/server/dao/user/UserService.java index 5818588b83..ad460c2f6e 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/user/UserService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/user/UserService.java @@ -26,27 +26,27 @@ import org.thingsboard.server.common.data.security.UserCredentials; public interface UserService { - User findUserById(UserId userId); + User findUserById(TenantId tenantId, UserId userId); - ListenableFuture findUserByIdAsync(UserId userId); + ListenableFuture findUserByIdAsync(TenantId tenantId, UserId userId); - User findUserByEmail(String email); + User findUserByEmail(TenantId tenantId, String email); User saveUser(User user); - UserCredentials findUserCredentialsByUserId(UserId userId); + UserCredentials findUserCredentialsByUserId(TenantId tenantId, UserId userId); - UserCredentials findUserCredentialsByActivateToken(String activateToken); + UserCredentials findUserCredentialsByActivateToken(TenantId tenantId, String activateToken); - UserCredentials findUserCredentialsByResetToken(String resetToken); + UserCredentials findUserCredentialsByResetToken(TenantId tenantId, String resetToken); - UserCredentials saveUserCredentials(UserCredentials userCredentials); + UserCredentials saveUserCredentials(TenantId tenantId, UserCredentials userCredentials); - UserCredentials activateUserCredentials(String activateToken, String password); + UserCredentials activateUserCredentials(TenantId tenantId, String activateToken, String password); - UserCredentials requestPasswordReset(String email); + UserCredentials requestPasswordReset(TenantId tenantId, String email); - void deleteUser(UserId userId); + void deleteUser(TenantId tenantId, UserId userId); TextPageData findTenantAdmins(TenantId tenantId, TextPageLink pageLink); diff --git a/dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java index e1bd4e0c65..8e283b59a2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java @@ -56,86 +56,86 @@ public class UserServiceImpl extends AbstractEntityService implements UserServic @Autowired private UserDao userDao; - + @Autowired private UserCredentialsDao userCredentialsDao; - + @Autowired private TenantDao tenantDao; - + @Autowired private CustomerDao customerDao; - - @Override - public User findUserByEmail(String email) { - log.trace("Executing findUserByEmail [{}]", email); - validateString(email, "Incorrect email " + email); - return userDao.findByEmail(email); - } - - @Override - public User findUserById(UserId userId) { - log.trace("Executing findUserById [{}]", userId); - validateId(userId, INCORRECT_USER_ID + userId); - return userDao.findById(userId.getId()); - } @Override - public ListenableFuture findUserByIdAsync(UserId userId) { + public User findUserByEmail(TenantId tenantId, String email) { + log.trace("Executing findUserByEmail [{}]", email); + validateString(email, "Incorrect email " + email); + return userDao.findByEmail(tenantId, email); + } + + @Override + public User findUserById(TenantId tenantId, UserId userId) { + log.trace("Executing findUserById [{}]", userId); + validateId(userId, INCORRECT_USER_ID + userId); + return userDao.findById(tenantId, userId.getId()); + } + + @Override + public ListenableFuture findUserByIdAsync(TenantId tenantId, UserId userId) { log.trace("Executing findUserByIdAsync [{}]", userId); validateId(userId, INCORRECT_USER_ID + userId); - return userDao.findByIdAsync(userId.getId()); + return userDao.findByIdAsync(tenantId, userId.getId()); } @Override public User saveUser(User user) { log.trace("Executing saveUser [{}]", user); - userValidator.validate(user); - User savedUser = userDao.save(user); + userValidator.validate(user, User::getTenantId); + User savedUser = userDao.save(user.getTenantId(), user); if (user.getId() == null) { UserCredentials userCredentials = new UserCredentials(); userCredentials.setEnabled(false); userCredentials.setActivateToken(RandomStringUtils.randomAlphanumeric(DEFAULT_TOKEN_LENGTH)); userCredentials.setUserId(new UserId(savedUser.getUuidId())); - userCredentialsDao.save(userCredentials); - } + userCredentialsDao.save(user.getTenantId(), userCredentials); + } return savedUser; } - + @Override - public UserCredentials findUserCredentialsByUserId(UserId userId) { + public UserCredentials findUserCredentialsByUserId(TenantId tenantId, UserId userId) { log.trace("Executing findUserCredentialsByUserId [{}]", userId); validateId(userId, INCORRECT_USER_ID + userId); - return userCredentialsDao.findByUserId(userId.getId()); + return userCredentialsDao.findByUserId(tenantId, userId.getId()); } @Override - public UserCredentials findUserCredentialsByActivateToken(String activateToken) { + public UserCredentials findUserCredentialsByActivateToken(TenantId tenantId, String activateToken) { log.trace("Executing findUserCredentialsByActivateToken [{}]", activateToken); validateString(activateToken, "Incorrect activateToken " + activateToken); - return userCredentialsDao.findByActivateToken(activateToken); + return userCredentialsDao.findByActivateToken(tenantId, activateToken); } @Override - public UserCredentials findUserCredentialsByResetToken(String resetToken) { + public UserCredentials findUserCredentialsByResetToken(TenantId tenantId, String resetToken) { log.trace("Executing findUserCredentialsByResetToken [{}]", resetToken); validateString(resetToken, "Incorrect resetToken " + resetToken); - return userCredentialsDao.findByResetToken(resetToken); + return userCredentialsDao.findByResetToken(tenantId, resetToken); } @Override - public UserCredentials saveUserCredentials(UserCredentials userCredentials) { + public UserCredentials saveUserCredentials(TenantId tenantId, UserCredentials userCredentials) { log.trace("Executing saveUserCredentials [{}]", userCredentials); - userCredentialsValidator.validate(userCredentials); - return userCredentialsDao.save(userCredentials); + userCredentialsValidator.validate(userCredentials, data -> tenantId); + return userCredentialsDao.save(tenantId, userCredentials); } - + @Override - public UserCredentials activateUserCredentials(String activateToken, String password) { + public UserCredentials activateUserCredentials(TenantId tenantId, String activateToken, String password) { log.trace("Executing activateUserCredentials activateToken [{}], password [{}]", activateToken, password); validateString(activateToken, "Incorrect activateToken " + activateToken); validateString(password, "Incorrect password " + password); - UserCredentials userCredentials = userCredentialsDao.findByActivateToken(activateToken); + UserCredentials userCredentials = userCredentialsDao.findByActivateToken(tenantId, activateToken); if (userCredentials == null) { throw new IncorrectParameterException(String.format("Unable to find user credentials by activateToken [%s]", activateToken)); } @@ -145,35 +145,35 @@ public class UserServiceImpl extends AbstractEntityService implements UserServic userCredentials.setEnabled(true); userCredentials.setActivateToken(null); userCredentials.setPassword(password); - - return saveUserCredentials(userCredentials); + + return saveUserCredentials(tenantId, userCredentials); } @Override - public UserCredentials requestPasswordReset(String email) { + public UserCredentials requestPasswordReset(TenantId tenantId, String email) { log.trace("Executing requestPasswordReset email [{}]", email); validateString(email, "Incorrect email " + email); - User user = userDao.findByEmail(email); + User user = userDao.findByEmail(tenantId, email); if (user == null) { throw new IncorrectParameterException(String.format("Unable to find user by email [%s]", email)); } - UserCredentials userCredentials = userCredentialsDao.findByUserId(user.getUuidId()); + UserCredentials userCredentials = userCredentialsDao.findByUserId(tenantId, user.getUuidId()); if (!userCredentials.isEnabled()) { throw new IncorrectParameterException("Unable to reset password for inactive user"); } userCredentials.setResetToken(RandomStringUtils.randomAlphanumeric(DEFAULT_TOKEN_LENGTH)); - return saveUserCredentials(userCredentials); + return saveUserCredentials(tenantId, userCredentials); } @Override - public void deleteUser(UserId userId) { + public void deleteUser(TenantId tenantId, UserId userId) { log.trace("Executing deleteUser [{}]", userId); validateId(userId, INCORRECT_USER_ID + userId); - UserCredentials userCredentials = userCredentialsDao.findByUserId(userId.getId()); - userCredentialsDao.removeById(userCredentials.getUuidId()); - deleteEntityRelations(userId); - userDao.removeById(userId.getId()); + UserCredentials userCredentials = userCredentialsDao.findByUserId(tenantId, userId.getId()); + userCredentialsDao.removeById(tenantId, userCredentials.getUuidId()); + deleteEntityRelations(tenantId, userId); + userDao.removeById(tenantId, userId.getId()); } @Override @@ -189,7 +189,7 @@ public class UserServiceImpl extends AbstractEntityService implements UserServic public void deleteTenantAdmins(TenantId tenantId) { log.trace("Executing deleteTenantAdmins, tenantId [{}]", tenantId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); - tenantAdminsRemover.removeEntities(tenantId); + tenantAdminsRemover.removeEntities(tenantId, tenantId); } @Override @@ -207,19 +207,19 @@ public class UserServiceImpl extends AbstractEntityService implements UserServic log.trace("Executing deleteCustomerUsers, customerId [{}]", customerId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); validateId(customerId, "Incorrect customerId " + customerId); - new CustomerUsersRemover(tenantId).removeEntities(customerId); + customerUsersRemover.removeEntities(tenantId, customerId); } private DataValidator userValidator = new DataValidator() { @Override - protected void validateDataImpl(User user) { + protected void validateDataImpl(TenantId requestTenantId, User user) { if (StringUtils.isEmpty(user.getEmail())) { throw new DataValidationException("User email should be specified!"); } - + validateEmail(user.getEmail()); - + Authority authority = user.getAuthority(); if (authority == null) { throw new DataValidationException("User authority isn't defined!"); @@ -234,12 +234,12 @@ public class UserServiceImpl extends AbstractEntityService implements UserServic customerId = new CustomerId(ModelConstants.NULL_UUID); user.setCustomerId(customerId); } - + switch (authority) { case SYS_ADMIN: if (!tenantId.getId().equals(ModelConstants.NULL_UUID) || !customerId.getId().equals(ModelConstants.NULL_UUID)) { - throw new DataValidationException("System administrator can't be assigned neither to tenant nor to customer!"); + throw new DataValidationException("System administrator can't be assigned neither to tenant nor to customer!"); } break; case TENANT_ADMIN: @@ -251,46 +251,46 @@ public class UserServiceImpl extends AbstractEntityService implements UserServic break; case CUSTOMER_USER: if (tenantId.getId().equals(ModelConstants.NULL_UUID) - || customerId.getId().equals(ModelConstants.NULL_UUID) ) { + || customerId.getId().equals(ModelConstants.NULL_UUID)) { throw new DataValidationException("Customer user should be assigned to customer!"); } break; default: break; } - - User existentUserWithEmail = findUserByEmail(user.getEmail()); + + User existentUserWithEmail = findUserByEmail(tenantId, user.getEmail()); if (existentUserWithEmail != null && !isSameData(existentUserWithEmail, user)) { throw new DataValidationException("User with email '" + user.getEmail() + "' " + " already present in database!"); } if (!tenantId.getId().equals(ModelConstants.NULL_UUID)) { - Tenant tenant = tenantDao.findById(user.getTenantId().getId()); + Tenant tenant = tenantDao.findById(tenantId, user.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("User is referencing to non-existent tenant!"); } } if (!customerId.getId().equals(ModelConstants.NULL_UUID)) { - Customer customer = customerDao.findById(user.getCustomerId().getId()); + Customer customer = customerDao.findById(tenantId, user.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("User is referencing to non-existent customer!"); } else if (!customer.getTenantId().getId().equals(tenantId.getId())) { throw new DataValidationException("User can't be assigned to customer from different tenant!"); } } - } - }; - - private DataValidator userCredentialsValidator = + } + }; + + private DataValidator userCredentialsValidator = new DataValidator() { - + @Override - protected void validateCreate(UserCredentials userCredentials) { + protected void validateCreate(TenantId tenantId, UserCredentials userCredentials) { throw new IncorrectParameterException("Creation of new user credentials is prohibited."); } - + @Override - protected void validateDataImpl(UserCredentials userCredentials) { + protected void validateDataImpl(TenantId tenantId, UserCredentials userCredentials) { if (userCredentials.getUserId() == null) { throw new DataValidationException("User credentials should be assigned to user!"); } @@ -302,50 +302,40 @@ public class UserServiceImpl extends AbstractEntityService implements UserServic throw new DataValidationException("Enabled user credentials can't have activate token!"); } } - UserCredentials existingUserCredentialsEntity = userCredentialsDao.findById(userCredentials.getId().getId()); + UserCredentials existingUserCredentialsEntity = userCredentialsDao.findById(tenantId, userCredentials.getId().getId()); if (existingUserCredentialsEntity == null) { throw new DataValidationException("Unable to update non-existent user credentials!"); } - User user = findUserById(userCredentials.getUserId()); + User user = findUserById(tenantId, userCredentials.getUserId()); if (user == null) { throw new DataValidationException("Can't assign user credentials to non-existent user!"); } } - }; - - private PaginatedRemover tenantAdminsRemover = - new PaginatedRemover() { - + }; + + private PaginatedRemover tenantAdminsRemover = new PaginatedRemover() { @Override - protected List findEntities(TenantId id, TextPageLink pageLink) { + protected List findEntities(TenantId tenantId, TenantId id, TextPageLink pageLink) { return userDao.findTenantAdmins(id.getId(), pageLink); } @Override - protected void removeEntity(User entity) { - deleteUser(new UserId(entity.getUuidId())); + protected void removeEntity(TenantId tenantId, User entity) { + deleteUser(tenantId, new UserId(entity.getUuidId())); } }; - - private class CustomerUsersRemover extends PaginatedRemover { - - private TenantId tenantId; - - CustomerUsersRemover(TenantId tenantId) { - this.tenantId = tenantId; - } + private PaginatedRemover customerUsersRemover = new PaginatedRemover() { @Override - protected List findEntities(CustomerId id, TextPageLink pageLink) { + protected List findEntities(TenantId tenantId, CustomerId id, TextPageLink pageLink) { return userDao.findCustomerUsers(tenantId.getId(), id.getId(), pageLink); - + } @Override - protected void removeEntity(User entity) { - deleteUser(new UserId(entity.getUuidId())); + protected void removeEntity(TenantId tenantId, User entity) { + deleteUser(tenantId, new UserId(entity.getUuidId())); } - - } - + }; + } diff --git a/dao/src/main/java/org/thingsboard/server/dao/util/AbstractBufferedRateExecutor.java b/dao/src/main/java/org/thingsboard/server/dao/util/AbstractBufferedRateExecutor.java index 96d3870dcd..c4c9b60504 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/util/AbstractBufferedRateExecutor.java +++ b/dao/src/main/java/org/thingsboard/server/dao/util/AbstractBufferedRateExecutor.java @@ -20,10 +20,15 @@ import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import lombok.extern.slf4j.Slf4j; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.tools.TbRateLimits; import javax.annotation.Nullable; import java.util.UUID; import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; @@ -45,6 +50,9 @@ public abstract class AbstractBufferedRateExecutor perTenantLimits = new ConcurrentHashMap<>(); protected final AtomicInteger concurrencyLevel = new AtomicInteger(); protected final AtomicInteger totalAdded = new AtomicInteger(); @@ -53,8 +61,10 @@ public abstract class AbstractBufferedRateExecutor settableFuture = create(); F result = wrap(task, settableFuture); - try { - totalAdded.incrementAndGet(); - queue.add(new AsyncTaskContext<>(UUID.randomUUID(), task, settableFuture, System.currentTimeMillis())); - } catch (IllegalStateException e) { - totalRejected.incrementAndGet(); - settableFuture.setException(e); + boolean perTenantLimitReached = false; + if (perTenantLimitsEnabled) { + if (task.getTenantId() == null) { + log.info("Invalid task received: {}", task); + } else if (!task.getTenantId().isNullUid()) { + TbRateLimits rateLimits = perTenantLimits.computeIfAbsent(task.getTenantId(), id -> new TbRateLimits(perTenantLimitsConfiguration)); + if (!rateLimits.tryConsume()) { + totalRateLimited.incrementAndGet(); + settableFuture.setException(new TenantRateLimitException()); + perTenantLimitReached = true; + } + } + } + if (!perTenantLimitReached) { + try { + totalAdded.incrementAndGet(); + queue.add(new AsyncTaskContext<>(UUID.randomUUID(), task, settableFuture, System.currentTimeMillis())); + } catch (IllegalStateException e) { + totalRejected.incrementAndGet(); + settableFuture.setException(e); + } } return result; } diff --git a/dao/src/main/java/org/thingsboard/server/dao/util/AsyncTask.java b/dao/src/main/java/org/thingsboard/server/dao/util/AsyncTask.java index 672e4f4656..9e53e9850d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/util/AsyncTask.java +++ b/dao/src/main/java/org/thingsboard/server/dao/util/AsyncTask.java @@ -15,8 +15,13 @@ */ package org.thingsboard.server.dao.util; +import org.thingsboard.server.common.data.id.TenantId; + /** * Created by ashvayka on 24.10.18. */ public interface AsyncTask { + + TenantId getTenantId(); + } diff --git a/dao/src/main/java/org/thingsboard/server/dao/util/TenantRateLimitException.java b/dao/src/main/java/org/thingsboard/server/dao/util/TenantRateLimitException.java new file mode 100644 index 0000000000..bbfc124085 --- /dev/null +++ b/dao/src/main/java/org/thingsboard/server/dao/util/TenantRateLimitException.java @@ -0,0 +1,19 @@ +/** + * Copyright © 2016-2018 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.dao.util; + +public class TenantRateLimitException extends Exception { +} diff --git a/dao/src/main/java/org/thingsboard/server/dao/widget/CassandraWidgetTypeDao.java b/dao/src/main/java/org/thingsboard/server/dao/widget/CassandraWidgetTypeDao.java index e31809f64a..0d7fa43921 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/widget/CassandraWidgetTypeDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/widget/CassandraWidgetTypeDao.java @@ -18,6 +18,7 @@ package org.thingsboard.server.dao.widget; import com.datastax.driver.core.querybuilder.Select.Where; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.widget.WidgetType; import org.thingsboard.server.dao.DaoUtil; import org.thingsboard.server.dao.model.nosql.WidgetTypeEntity; @@ -57,7 +58,7 @@ public class CassandraWidgetTypeDao extends CassandraAbstractModelDao widgetTypesEntities = findListByStatement(query); + List widgetTypesEntities = findListByStatement(new TenantId(tenantId), query); log.trace("Found widget types [{}] by tenantId [{}] and bundleAlias [{}]", widgetTypesEntities, tenantId, bundleAlias); return DaoUtil.convertDataList(widgetTypesEntities); } @@ -71,7 +72,7 @@ public class CassandraWidgetTypeDao extends CassandraAbstractModelDao findSystemWidgetsBundles(TextPageLink pageLink) { + public List findSystemWidgetsBundles(TenantId tenantId, TextPageLink pageLink) { log.debug("Try to find system widgets bundles by pageLink [{}]", pageLink); - List widgetsBundlesEntities = findPageWithTextSearch(WIDGETS_BUNDLE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List widgetsBundlesEntities = findPageWithTextSearch(tenantId, WIDGETS_BUNDLE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(WIDGETS_BUNDLE_TENANT_ID_PROPERTY, NULL_UUID)), pageLink); log.trace("Found system widgets bundles [{}] by pageLink [{}]", widgetsBundlesEntities, pageLink); @@ -81,7 +83,7 @@ public class CassandraWidgetsBundleDao extends CassandraAbstractSearchTextDao findTenantWidgetsBundlesByTenantId(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find tenant widgets bundles by tenantId [{}] and pageLink [{}]", tenantId, pageLink); - List widgetsBundlesEntities = findPageWithTextSearch(WIDGETS_BUNDLE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List widgetsBundlesEntities = findPageWithTextSearch(new TenantId(tenantId), WIDGETS_BUNDLE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(eq(WIDGETS_BUNDLE_TENANT_ID_PROPERTY, tenantId)), pageLink); log.trace("Found tenant widgets bundles [{}] by tenantId [{}] and pageLink [{}]", widgetsBundlesEntities, tenantId, pageLink); @@ -91,7 +93,7 @@ public class CassandraWidgetsBundleDao extends CassandraAbstractSearchTextDao findAllTenantWidgetsBundlesByTenantId(UUID tenantId, TextPageLink pageLink) { log.debug("Try to find all tenant widgets bundles by tenantId [{}] and pageLink [{}]", tenantId, pageLink); - List widgetsBundlesEntities = findPageWithTextSearch(WIDGETS_BUNDLE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, + List widgetsBundlesEntities = findPageWithTextSearch(new TenantId(tenantId), WIDGETS_BUNDLE_BY_TENANT_AND_SEARCH_TEXT_COLUMN_FAMILY_NAME, Arrays.asList(in(WIDGETS_BUNDLE_TENANT_ID_PROPERTY, Arrays.asList(NULL_UUID, tenantId))), pageLink); log.trace("Found all tenant widgets bundles [{}] by tenantId [{}] and pageLink [{}]", widgetsBundlesEntities, tenantId, pageLink); diff --git a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeDao.java b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeDao.java index de5028b9b9..e25e84b651 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeDao.java @@ -15,6 +15,7 @@ */ package org.thingsboard.server.dao.widget; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.widget.WidgetType; import org.thingsboard.server.dao.Dao; @@ -32,7 +33,7 @@ public interface WidgetTypeDao extends Dao { * @param widgetType the widget type object * @return saved widget type object */ - WidgetType save(WidgetType widgetType); + WidgetType save(TenantId tenantId, WidgetType widgetType); /** * Find widget types by tenantId and bundleAlias. diff --git a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeService.java b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeService.java index 5d71ddde73..a3145921d9 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeService.java @@ -23,11 +23,11 @@ import java.util.List; public interface WidgetTypeService { - WidgetType findWidgetTypeById(WidgetTypeId widgetTypeId); + WidgetType findWidgetTypeById(TenantId tenantId, WidgetTypeId widgetTypeId); WidgetType saveWidgetType(WidgetType widgetType); - void deleteWidgetType(WidgetTypeId widgetTypeId); + void deleteWidgetType(TenantId tenantId, WidgetTypeId widgetTypeId); List findWidgetTypesByTenantIdAndBundleAlias(TenantId tenantId, String bundleAlias); diff --git a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeServiceImpl.java index 1cbe59e64e..37f2b11ff0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetTypeServiceImpl.java @@ -48,24 +48,24 @@ public class WidgetTypeServiceImpl implements WidgetTypeService { private WidgetsBundleDao widgetsBundleService; @Override - public WidgetType findWidgetTypeById(WidgetTypeId widgetTypeId) { + public WidgetType findWidgetTypeById(TenantId tenantId, WidgetTypeId widgetTypeId) { log.trace("Executing findWidgetTypeById [{}]", widgetTypeId); Validator.validateId(widgetTypeId, "Incorrect widgetTypeId " + widgetTypeId); - return widgetTypeDao.findById(widgetTypeId.getId()); + return widgetTypeDao.findById(tenantId, widgetTypeId.getId()); } @Override public WidgetType saveWidgetType(WidgetType widgetType) { log.trace("Executing saveWidgetType [{}]", widgetType); - widgetTypeValidator.validate(widgetType); - return widgetTypeDao.save(widgetType); + widgetTypeValidator.validate(widgetType, WidgetType::getTenantId); + return widgetTypeDao.save(widgetType.getTenantId(), widgetType); } @Override - public void deleteWidgetType(WidgetTypeId widgetTypeId) { + public void deleteWidgetType(TenantId tenantId, WidgetTypeId widgetTypeId) { log.trace("Executing deleteWidgetType [{}]", widgetTypeId); Validator.validateId(widgetTypeId, "Incorrect widgetTypeId " + widgetTypeId); - widgetTypeDao.removeById(widgetTypeId.getId()); + widgetTypeDao.removeById(tenantId, widgetTypeId.getId()); } @Override @@ -92,14 +92,14 @@ public class WidgetTypeServiceImpl implements WidgetTypeService { Validator.validateString(bundleAlias, INCORRECT_BUNDLE_ALIAS + bundleAlias); List widgetTypes = widgetTypeDao.findWidgetTypesByTenantIdAndBundleAlias(tenantId.getId(), bundleAlias); for (WidgetType widgetType : widgetTypes) { - deleteWidgetType(new WidgetTypeId(widgetType.getUuidId())); + deleteWidgetType(tenantId, new WidgetTypeId(widgetType.getUuidId())); } } private DataValidator widgetTypeValidator = new DataValidator() { @Override - protected void validateDataImpl(WidgetType widgetType) { + protected void validateDataImpl(TenantId tenantId, WidgetType widgetType) { if (StringUtils.isEmpty(widgetType.getName())) { throw new DataValidationException("Widgets type name should be specified!"); } @@ -113,7 +113,7 @@ public class WidgetTypeServiceImpl implements WidgetTypeService { widgetType.setTenantId(new TenantId(ModelConstants.NULL_UUID)); } if (!widgetType.getTenantId().getId().equals(ModelConstants.NULL_UUID)) { - Tenant tenant = tenantDao.findById(widgetType.getTenantId().getId()); + Tenant tenant = tenantDao.findById(tenantId, widgetType.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("Widget type is referencing to non-existent tenant!"); } @@ -121,7 +121,7 @@ public class WidgetTypeServiceImpl implements WidgetTypeService { } @Override - protected void validateCreate(WidgetType widgetType) { + protected void validateCreate(TenantId tenantId, WidgetType widgetType) { WidgetsBundle widgetsBundle = widgetsBundleService.findWidgetsBundleByTenantIdAndAlias(widgetType.getTenantId().getId(), widgetType.getBundleAlias()); if (widgetsBundle == null) { throw new DataValidationException("Widget type is referencing to non-existent widgets bundle!"); @@ -138,13 +138,13 @@ public class WidgetTypeServiceImpl implements WidgetTypeService { if (withSameAlias != null) { alias = originalAlias + (++c); } - } while(withSameAlias != null); + } while (withSameAlias != null); widgetType.setAlias(alias); } @Override - protected void validateUpdate(WidgetType widgetType) { - WidgetType storedWidgetType = widgetTypeDao.findById(widgetType.getId().getId()); + protected void validateUpdate(TenantId tenantId, WidgetType widgetType) { + WidgetType storedWidgetType = widgetTypeDao.findById(tenantId, widgetType.getId().getId()); if (!storedWidgetType.getTenantId().getId().equals(widgetType.getTenantId().getId())) { throw new DataValidationException("Can't move existing widget type to different tenant!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleDao.java b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleDao.java index f1b887f21c..7c069d7757 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleDao.java @@ -15,6 +15,7 @@ */ package org.thingsboard.server.dao.widget; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.widget.WidgetsBundle; import org.thingsboard.server.dao.Dao; @@ -30,10 +31,11 @@ public interface WidgetsBundleDao extends Dao { /** * Save or update widgets bundle object * + * @param tenantId the tenantId * @param widgetsBundle the widgets bundle object * @return saved widgets bundle object */ - WidgetsBundle save(WidgetsBundle widgetsBundle); + WidgetsBundle save(TenantId tenantId, WidgetsBundle widgetsBundle); /** * Find widgets bundle by tenantId and alias. @@ -50,7 +52,7 @@ public interface WidgetsBundleDao extends Dao { * @param pageLink the page link * @return the list of widgets bundles objects */ - List findSystemWidgetsBundles(TextPageLink pageLink); + List findSystemWidgetsBundles(TenantId tenantId, TextPageLink pageLink); /** * Find tenant widgets bundles by tenantId and page link. diff --git a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleService.java b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleService.java index 3314d87a0e..499ab7042f 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleService.java @@ -25,17 +25,17 @@ import java.util.List; public interface WidgetsBundleService { - WidgetsBundle findWidgetsBundleById(WidgetsBundleId widgetsBundleId); + WidgetsBundle findWidgetsBundleById(TenantId tenantId, WidgetsBundleId widgetsBundleId); WidgetsBundle saveWidgetsBundle(WidgetsBundle widgetsBundle); - void deleteWidgetsBundle(WidgetsBundleId widgetsBundleId); + void deleteWidgetsBundle(TenantId tenantId, WidgetsBundleId widgetsBundleId); WidgetsBundle findWidgetsBundleByTenantIdAndAlias(TenantId tenantId, String alias); - TextPageData findSystemWidgetsBundlesByPageLink(TextPageLink pageLink); + TextPageData findSystemWidgetsBundlesByPageLink(TenantId tenantId, TextPageLink pageLink); - List findSystemWidgetsBundles(); + List findSystemWidgetsBundles(TenantId tenantId); TextPageData findTenantWidgetsBundlesByTenantId(TenantId tenantId, TextPageLink pageLink); diff --git a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleServiceImpl.java index 1ae541c188..fb7a86f143 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/widget/WidgetsBundleServiceImpl.java @@ -54,29 +54,29 @@ public class WidgetsBundleServiceImpl implements WidgetsBundleService { private WidgetTypeService widgetTypeService; @Override - public WidgetsBundle findWidgetsBundleById(WidgetsBundleId widgetsBundleId) { + public WidgetsBundle findWidgetsBundleById(TenantId tenantId, WidgetsBundleId widgetsBundleId) { log.trace("Executing findWidgetsBundleById [{}]", widgetsBundleId); Validator.validateId(widgetsBundleId, "Incorrect widgetsBundleId " + widgetsBundleId); - return widgetsBundleDao.findById(widgetsBundleId.getId()); + return widgetsBundleDao.findById(tenantId, widgetsBundleId.getId()); } @Override public WidgetsBundle saveWidgetsBundle(WidgetsBundle widgetsBundle) { log.trace("Executing saveWidgetsBundle [{}]", widgetsBundle); - widgetsBundleValidator.validate(widgetsBundle); - return widgetsBundleDao.save(widgetsBundle); + widgetsBundleValidator.validate(widgetsBundle, WidgetsBundle::getTenantId); + return widgetsBundleDao.save(widgetsBundle.getTenantId(), widgetsBundle); } @Override - public void deleteWidgetsBundle(WidgetsBundleId widgetsBundleId) { + public void deleteWidgetsBundle(TenantId tenantId, WidgetsBundleId widgetsBundleId) { log.trace("Executing deleteWidgetsBundle [{}]", widgetsBundleId); Validator.validateId(widgetsBundleId, "Incorrect widgetsBundleId " + widgetsBundleId); - WidgetsBundle widgetsBundle = findWidgetsBundleById(widgetsBundleId); + WidgetsBundle widgetsBundle = findWidgetsBundleById(tenantId, widgetsBundleId); if (widgetsBundle == null) { throw new IncorrectParameterException("Unable to delete non-existent widgets bundle."); } widgetTypeService.deleteWidgetTypesByTenantIdAndBundleAlias(widgetsBundle.getTenantId(), widgetsBundle.getAlias()); - widgetsBundleDao.removeById(widgetsBundleId.getId()); + widgetsBundleDao.removeById(tenantId, widgetsBundleId.getId()); } @Override @@ -88,20 +88,20 @@ public class WidgetsBundleServiceImpl implements WidgetsBundleService { } @Override - public TextPageData findSystemWidgetsBundlesByPageLink(TextPageLink pageLink) { + public TextPageData findSystemWidgetsBundlesByPageLink(TenantId tenantId, TextPageLink pageLink) { log.trace("Executing findSystemWidgetsBundles, pageLink [{}]", pageLink); Validator.validatePageLink(pageLink, INCORRECT_PAGE_LINK + pageLink); - return new TextPageData<>(widgetsBundleDao.findSystemWidgetsBundles(pageLink), pageLink); + return new TextPageData<>(widgetsBundleDao.findSystemWidgetsBundles(tenantId, pageLink), pageLink); } @Override - public List findSystemWidgetsBundles() { + public List findSystemWidgetsBundles(TenantId tenantId) { log.trace("Executing findSystemWidgetsBundles"); List widgetsBundles = new ArrayList<>(); TextPageLink pageLink = new TextPageLink(DEFAULT_WIDGETS_BUNDLE_LIMIT); TextPageData pageData; do { - pageData = findSystemWidgetsBundlesByPageLink(pageLink); + pageData = findSystemWidgetsBundlesByPageLink(tenantId, pageLink); widgetsBundles.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); @@ -147,14 +147,14 @@ public class WidgetsBundleServiceImpl implements WidgetsBundleService { public void deleteWidgetsBundlesByTenantId(TenantId tenantId) { log.trace("Executing deleteWidgetsBundlesByTenantId, tenantId [{}]", tenantId); Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId); - tenantWidgetsBundleRemover.removeEntities(tenantId); + tenantWidgetsBundleRemover.removeEntities(tenantId, tenantId); } private DataValidator widgetsBundleValidator = new DataValidator() { @Override - protected void validateDataImpl(WidgetsBundle widgetsBundle) { + protected void validateDataImpl(TenantId tenantId, WidgetsBundle widgetsBundle) { if (StringUtils.isEmpty(widgetsBundle.getTitle())) { throw new DataValidationException("Widgets bundle title should be specified!"); } @@ -162,7 +162,7 @@ public class WidgetsBundleServiceImpl implements WidgetsBundleService { widgetsBundle.setTenantId(new TenantId(ModelConstants.NULL_UUID)); } if (!widgetsBundle.getTenantId().getId().equals(ModelConstants.NULL_UUID)) { - Tenant tenant = tenantDao.findById(widgetsBundle.getTenantId().getId()); + Tenant tenant = tenantDao.findById(tenantId, widgetsBundle.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("Widgets bundle is referencing to non-existent tenant!"); } @@ -170,7 +170,7 @@ public class WidgetsBundleServiceImpl implements WidgetsBundleService { } @Override - protected void validateCreate(WidgetsBundle widgetsBundle) { + protected void validateCreate(TenantId tenantId, WidgetsBundle widgetsBundle) { String alias = widgetsBundle.getAlias(); if (alias == null || alias.trim().isEmpty()) { alias = widgetsBundle.getTitle().toLowerCase().replaceAll("\\W+", "_"); @@ -188,8 +188,8 @@ public class WidgetsBundleServiceImpl implements WidgetsBundleService { } @Override - protected void validateUpdate(WidgetsBundle widgetsBundle) { - WidgetsBundle storedWidgetsBundle = widgetsBundleDao.findById(widgetsBundle.getId().getId()); + protected void validateUpdate(TenantId tenantId, WidgetsBundle widgetsBundle) { + WidgetsBundle storedWidgetsBundle = widgetsBundleDao.findById(tenantId, widgetsBundle.getId().getId()); if (!storedWidgetsBundle.getTenantId().getId().equals(widgetsBundle.getTenantId().getId())) { throw new DataValidationException("Can't move existing widgets bundle to different tenant!"); } @@ -204,13 +204,13 @@ public class WidgetsBundleServiceImpl implements WidgetsBundleService { new PaginatedRemover() { @Override - protected List findEntities(TenantId id, TextPageLink pageLink) { + protected List findEntities(TenantId tenantId, TenantId id, TextPageLink pageLink) { return widgetsBundleDao.findTenantWidgetsBundlesByTenantId(id.getId(), pageLink); } @Override - protected void removeEntity(WidgetsBundle entity) { - deleteWidgetsBundle(new WidgetsBundleId(entity.getUuidId())); + protected void removeEntity(TenantId tenantId, WidgetsBundle entity) { + deleteWidgetsBundle(tenantId, new WidgetsBundleId(entity.getUuidId())); } }; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/AbstractServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/AbstractServiceTest.java index f49c357caa..ac3bcdd906 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/AbstractServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/AbstractServiceTest.java @@ -71,6 +71,8 @@ public abstract class AbstractServiceTest { protected ObjectMapper mapper = new ObjectMapper(); + public static final TenantId SYSTEM_TENANT_ID = new TenantId(EntityId.NULL_UUID); + @Autowired protected UserService userService; @@ -142,25 +144,25 @@ public abstract class AbstractServiceTest { event.setBody(readFromResource("TestJsonData.json")); return event; } - - private ComponentDescriptor getOrCreateDescriptor(ComponentScope scope, ComponentType type, String clazz, String configurationDescriptorResource) throws IOException { - return getOrCreateDescriptor(scope, type, clazz, configurationDescriptorResource, null); - } - - private ComponentDescriptor getOrCreateDescriptor(ComponentScope scope, ComponentType type, String clazz, String configurationDescriptorResource, String actions) throws IOException { - ComponentDescriptor descriptor = componentDescriptorService.findByClazz(clazz); - if (descriptor == null) { - descriptor = new ComponentDescriptor(); - descriptor.setName("test"); - descriptor.setClazz(clazz); - descriptor.setScope(scope); - descriptor.setType(type); - descriptor.setActions(actions); - descriptor.setConfigurationDescriptor(readFromResource(configurationDescriptorResource)); - componentDescriptorService.saveComponent(descriptor); - } - return descriptor; - } +// +// private ComponentDescriptor getOrCreateDescriptor(ComponentScope scope, ComponentType type, String clazz, String configurationDescriptorResource) throws IOException { +// return getOrCreateDescriptor(scope, type, clazz, configurationDescriptorResource, null); +// } +// +// private ComponentDescriptor getOrCreateDescriptor(ComponentScope scope, ComponentType type, String clazz, String configurationDescriptorResource, String actions) throws IOException { +// ComponentDescriptor descriptor = componentDescriptorService.findByClazz(clazz); +// if (descriptor == null) { +// descriptor = new ComponentDescriptor(); +// descriptor.setName("test"); +// descriptor.setClazz(clazz); +// descriptor.setScope(scope); +// descriptor.setType(type); +// descriptor.setActions(actions); +// descriptor.setConfigurationDescriptor(readFromResource(configurationDescriptorResource)); +// componentDescriptorService.saveComponent(descriptor); +// } +// return descriptor; +// } public JsonNode readFromResource(String resourceName) throws IOException { return mapper.readTree(this.getClass().getClassLoader().getResourceAsStream(resourceName)); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseAdminSettingsServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseAdminSettingsServiceTest.java index 41ba94f049..ac3dff66f4 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseAdminSettingsServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseAdminSettingsServiceTest.java @@ -26,63 +26,63 @@ public abstract class BaseAdminSettingsServiceTest extends AbstractServiceTest { @Test public void testFindAdminSettingsByKey() { - AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey("general"); + AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "general"); Assert.assertNotNull(adminSettings); - adminSettings = adminSettingsService.findAdminSettingsByKey("mail"); + adminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "mail"); Assert.assertNotNull(adminSettings); - adminSettings = adminSettingsService.findAdminSettingsByKey("unknown"); + adminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "unknown"); Assert.assertNull(adminSettings); } @Test public void testFindAdminSettingsById() { - AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey("general"); - AdminSettings foundAdminSettings = adminSettingsService.findAdminSettingsById(adminSettings.getId()); + AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "general"); + AdminSettings foundAdminSettings = adminSettingsService.findAdminSettingsById(SYSTEM_TENANT_ID, adminSettings.getId()); Assert.assertNotNull(foundAdminSettings); Assert.assertEquals(adminSettings, foundAdminSettings); } @Test - public void testSaveAdminSettings() throws Exception { - AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey("general"); + public void testSaveAdminSettings() { + AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "general"); JsonNode json = adminSettings.getJsonValue(); ((ObjectNode) json).put("baseUrl", "http://myhost.org"); adminSettings.setJsonValue(json); - adminSettingsService.saveAdminSettings(adminSettings); - AdminSettings savedAdminSettings = adminSettingsService.findAdminSettingsByKey("general"); + adminSettingsService.saveAdminSettings(SYSTEM_TENANT_ID, adminSettings); + AdminSettings savedAdminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "general"); Assert.assertNotNull(savedAdminSettings); Assert.assertEquals(adminSettings.getJsonValue(), savedAdminSettings.getJsonValue()); } @Test(expected = DataValidationException.class) public void testSaveAdminSettingsWithEmptyKey() { - AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey("mail"); + AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "mail"); adminSettings.setKey(null); - adminSettingsService.saveAdminSettings(adminSettings); + adminSettingsService.saveAdminSettings(SYSTEM_TENANT_ID, adminSettings); } @Test(expected = DataValidationException.class) public void testChangeAdminSettingsKey() { - AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey("mail"); + AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "mail"); adminSettings.setKey("newKey"); - adminSettingsService.saveAdminSettings(adminSettings); + adminSettingsService.saveAdminSettings(SYSTEM_TENANT_ID, adminSettings); } @Test(expected = DataValidationException.class) - public void testSaveAdminSettingsWithNewJsonStructure() throws Exception { - AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey("mail"); + public void testSaveAdminSettingsWithNewJsonStructure() { + AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "mail"); JsonNode json = adminSettings.getJsonValue(); ((ObjectNode) json).put("newKey", "my new value"); adminSettings.setJsonValue(json); - adminSettingsService.saveAdminSettings(adminSettings); + adminSettingsService.saveAdminSettings(SYSTEM_TENANT_ID, adminSettings); } @Test(expected = DataValidationException.class) - public void testSaveAdminSettingsWithNonTextValue() throws Exception { - AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey("mail"); + public void testSaveAdminSettingsWithNonTextValue() { + AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(SYSTEM_TENANT_ID, "mail"); JsonNode json = adminSettings.getJsonValue(); ((ObjectNode) json).put("timeout", 10000L); adminSettings.setJsonValue(json); - adminSettingsService.saveAdminSettings(adminSettings); + adminSettingsService.saveAdminSettings(SYSTEM_TENANT_ID, adminSettings); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseAlarmServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseAlarmServiceTest.java index 03099e9b75..8c4437416e 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseAlarmServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseAlarmServiceTest.java @@ -61,7 +61,7 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { EntityRelation relation = new EntityRelation(parentId, childId, EntityRelation.CONTAINS_TYPE); - Assert.assertTrue(relationService.saveRelationAsync(relation).get()); + Assert.assertTrue(relationService.saveRelationAsync(tenantId, relation).get()); long ts = System.currentTimeMillis(); Alarm alarm = Alarm.builder().tenantId(tenantId).originator(childId) @@ -87,7 +87,7 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { Assert.assertEquals(0L, created.getAckTs()); Assert.assertEquals(0L, created.getClearTs()); - Alarm fetched = alarmService.findAlarmByIdAsync(created.getId()).get(); + Alarm fetched = alarmService.findAlarmByIdAsync(tenantId, created.getId()).get(); Assert.assertEquals(created, fetched); } @@ -98,7 +98,7 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { EntityRelation relation = new EntityRelation(parentId, childId, EntityRelation.CONTAINS_TYPE); - Assert.assertTrue(relationService.saveRelationAsync(relation).get()); + Assert.assertTrue(relationService.saveRelationAsync(tenantId, relation).get()); long ts = System.currentTimeMillis(); Alarm alarm = Alarm.builder().tenantId(tenantId).originator(childId) @@ -110,7 +110,7 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { Alarm created = alarmService.createOrUpdateAlarm(alarm); // Check child relation - TimePageData alarms = alarmService.findAlarms(AlarmQuery.builder() + TimePageData alarms = alarmService.findAlarms(tenantId, AlarmQuery.builder() .affectedEntityId(childId) .status(AlarmStatus.ACTIVE_UNACK).pageLink( new TimePageLink(1, 0L, System.currentTimeMillis(), false) @@ -120,7 +120,7 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { Assert.assertEquals(created, alarms.getData().get(0)); // Check parent relation - alarms = alarmService.findAlarms(AlarmQuery.builder() + alarms = alarmService.findAlarms(tenantId, AlarmQuery.builder() .affectedEntityId(parentId) .status(AlarmStatus.ACTIVE_UNACK).pageLink( new TimePageLink(1, 0L, System.currentTimeMillis(), false) @@ -132,7 +132,7 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { created = alarmService.createOrUpdateAlarm(created); // Check child relation - alarms = alarmService.findAlarms(AlarmQuery.builder() + alarms = alarmService.findAlarms(tenantId, AlarmQuery.builder() .affectedEntityId(childId) .status(AlarmStatus.ACTIVE_UNACK).pageLink( new TimePageLink(1, 0L, System.currentTimeMillis(), false) @@ -142,7 +142,7 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { Assert.assertEquals(created, alarms.getData().get(0)); // Check parent relation - alarms = alarmService.findAlarms(AlarmQuery.builder() + alarms = alarmService.findAlarms(tenantId, AlarmQuery.builder() .affectedEntityId(parentId) .status(AlarmStatus.ACTIVE_UNACK).pageLink( new TimePageLink(1, 0L, System.currentTimeMillis(), false) @@ -151,10 +151,10 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { Assert.assertEquals(1, alarms.getData().size()); Assert.assertEquals(created, alarms.getData().get(0)); - alarmService.ackAlarm(created.getId(), System.currentTimeMillis()).get(); - created = alarmService.findAlarmByIdAsync(created.getId()).get(); + alarmService.ackAlarm(tenantId, created.getId(), System.currentTimeMillis()).get(); + created = alarmService.findAlarmByIdAsync(tenantId, created.getId()).get(); - alarms = alarmService.findAlarms(AlarmQuery.builder() + alarms = alarmService.findAlarms(tenantId, AlarmQuery.builder() .affectedEntityId(childId) .status(AlarmStatus.ACTIVE_ACK).pageLink( new TimePageLink(1, 0L, System.currentTimeMillis(), false) @@ -164,7 +164,7 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { Assert.assertEquals(created, alarms.getData().get(0)); // Check not existing relation - alarms = alarmService.findAlarms(AlarmQuery.builder() + alarms = alarmService.findAlarms(tenantId, AlarmQuery.builder() .affectedEntityId(childId) .status(AlarmStatus.ACTIVE_UNACK).pageLink( new TimePageLink(1, 0L, System.currentTimeMillis(), false) @@ -172,10 +172,10 @@ public abstract class BaseAlarmServiceTest extends AbstractServiceTest { Assert.assertNotNull(alarms.getData()); Assert.assertEquals(0, alarms.getData().size()); - alarmService.clearAlarm(created.getId(), null, System.currentTimeMillis()).get(); - created = alarmService.findAlarmByIdAsync(created.getId()).get(); + alarmService.clearAlarm(tenantId, created.getId(), null, System.currentTimeMillis()).get(); + created = alarmService.findAlarmByIdAsync(tenantId, created.getId()).get(); - alarms = alarmService.findAlarms(AlarmQuery.builder() + alarms = alarmService.findAlarms(tenantId, AlarmQuery.builder() .affectedEntityId(childId) .status(AlarmStatus.CLEARED_ACK).pageLink( new TimePageLink(1, 0L, System.currentTimeMillis(), false) diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseAssetServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseAssetServiceTest.java index a807d78943..a38f0f227b 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseAssetServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseAssetServiceTest.java @@ -76,10 +76,10 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { savedAsset.setName("My new asset"); assetService.saveAsset(savedAsset); - Asset foundAsset = assetService.findAssetById(savedAsset.getId()); + Asset foundAsset = assetService.findAssetById(tenantId, savedAsset.getId()); Assert.assertEquals(foundAsset.getName(), savedAsset.getName()); - assetService.deleteAsset(savedAsset.getId()); + assetService.deleteAsset(tenantId, savedAsset.getId()); } @Test(expected = DataValidationException.class) @@ -115,9 +115,9 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { asset.setTenantId(tenantId); asset = assetService.saveAsset(asset); try { - assetService.assignAssetToCustomer(asset.getId(), new CustomerId(UUIDs.timeBased())); + assetService.assignAssetToCustomer(tenantId, asset.getId(), new CustomerId(UUIDs.timeBased())); } finally { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); } } @@ -136,9 +136,9 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { customer.setTitle("Test different customer"); customer = customerService.saveCustomer(customer); try { - assetService.assignAssetToCustomer(asset.getId(), customer.getId()); + assetService.assignAssetToCustomer(tenantId, asset.getId(), customer.getId()); } finally { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); tenantService.deleteTenant(tenant.getId()); } } @@ -150,10 +150,10 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { asset.setName("My asset"); asset.setType("default"); Asset savedAsset = assetService.saveAsset(asset); - Asset foundAsset = assetService.findAssetById(savedAsset.getId()); + Asset foundAsset = assetService.findAssetById(tenantId, savedAsset.getId()); Assert.assertNotNull(foundAsset); Assert.assertEquals(savedAsset, foundAsset); - assetService.deleteAsset(savedAsset.getId()); + assetService.deleteAsset(tenantId, savedAsset.getId()); } @Test @@ -188,7 +188,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { Assert.assertEquals("typeB", assetTypes.get(1).getType()); Assert.assertEquals("typeC", assetTypes.get(2).getType()); } finally { - assets.forEach((asset) -> { assetService.deleteAsset(asset.getId()); }); + assets.forEach((asset) -> { assetService.deleteAsset(tenantId, asset.getId()); }); } } @@ -199,10 +199,10 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { asset.setName("My asset"); asset.setType("default"); Asset savedAsset = assetService.saveAsset(asset); - Asset foundAsset = assetService.findAssetById(savedAsset.getId()); + Asset foundAsset = assetService.findAssetById(tenantId, savedAsset.getId()); Assert.assertNotNull(foundAsset); - assetService.deleteAsset(savedAsset.getId()); - foundAsset = assetService.findAssetById(savedAsset.getId()); + assetService.deleteAsset(tenantId, savedAsset.getId()); + foundAsset = assetService.findAssetById(tenantId, savedAsset.getId()); Assert.assertNull(foundAsset); } @@ -308,7 +308,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { Assert.assertEquals(assetsTitle2, loadedAssetsTitle2); for (Asset asset : loadedAssetsTitle1) { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); } pageLink = new TextPageLink(4, title1); @@ -317,7 +317,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (Asset asset : loadedAssetsTitle2) { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); } pageLink = new TextPageLink(4, title2); @@ -387,7 +387,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { Assert.assertEquals(assetsType2, loadedAssetsType2); for (Asset asset : loadedAssetsType1) { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); } pageLink = new TextPageLink(4); @@ -396,7 +396,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (Asset asset : loadedAssetsType2) { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); } pageLink = new TextPageLink(4); @@ -426,7 +426,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { asset.setName("Asset"+i); asset.setType("default"); asset = assetService.saveAsset(asset); - assets.add(assetService.assignAssetToCustomer(asset.getId(), customerId)); + assets.add(assetService.assignAssetToCustomer(tenantId, asset.getId(), customerId)); } List loadedAssets = new ArrayList<>(); @@ -475,7 +475,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { asset.setName(name); asset.setType("default"); asset = assetService.saveAsset(asset); - assetsTitle1.add(assetService.assignAssetToCustomer(asset.getId(), customerId)); + assetsTitle1.add(assetService.assignAssetToCustomer(tenantId, asset.getId(), customerId)); } String title2 = "Asset title 2"; List assetsTitle2 = new ArrayList<>(); @@ -488,7 +488,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { asset.setName(name); asset.setType("default"); asset = assetService.saveAsset(asset); - assetsTitle2.add(assetService.assignAssetToCustomer(asset.getId(), customerId)); + assetsTitle2.add(assetService.assignAssetToCustomer(tenantId, asset.getId(), customerId)); } List loadedAssetsTitle1 = new ArrayList<>(); @@ -523,7 +523,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { Assert.assertEquals(assetsTitle2, loadedAssetsTitle2); for (Asset asset : loadedAssetsTitle1) { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); } pageLink = new TextPageLink(4, title1); @@ -532,14 +532,14 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (Asset asset : loadedAssetsTitle2) { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); } pageLink = new TextPageLink(4, title2); pageData = assetService.findAssetsByTenantIdAndCustomerId(tenantId, customerId, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - customerService.deleteCustomer(customerId); + customerService.deleteCustomer(tenantId, customerId); } @Test @@ -563,7 +563,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { asset.setName(name); asset.setType(type1); asset = assetService.saveAsset(asset); - assetsType1.add(assetService.assignAssetToCustomer(asset.getId(), customerId)); + assetsType1.add(assetService.assignAssetToCustomer(tenantId, asset.getId(), customerId)); } String title2 = "Asset title 2"; String type2 = "typeD"; @@ -577,7 +577,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { asset.setName(name); asset.setType(type2); asset = assetService.saveAsset(asset); - assetsType2.add(assetService.assignAssetToCustomer(asset.getId(), customerId)); + assetsType2.add(assetService.assignAssetToCustomer(tenantId, asset.getId(), customerId)); } List loadedAssetsType1 = new ArrayList<>(); @@ -612,7 +612,7 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { Assert.assertEquals(assetsType2, loadedAssetsType2); for (Asset asset : loadedAssetsType1) { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); } pageLink = new TextPageLink(4); @@ -621,14 +621,14 @@ public abstract class BaseAssetServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (Asset asset : loadedAssetsType2) { - assetService.deleteAsset(asset.getId()); + assetService.deleteAsset(tenantId, asset.getId()); } pageLink = new TextPageLink(4); pageData = assetService.findAssetsByTenantIdAndCustomerIdAndType(tenantId, customerId, type2, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - customerService.deleteCustomer(customerId); + customerService.deleteCustomer(tenantId, customerId); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseCustomerServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseCustomerServiceTest.java index 8a781b84cc..80e1b538b6 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseCustomerServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseCustomerServiceTest.java @@ -69,10 +69,10 @@ public abstract class BaseCustomerServiceTest extends AbstractServiceTest { savedCustomer.setTitle("My new customer"); customerService.saveCustomer(savedCustomer); - Customer foundCustomer = customerService.findCustomerById(savedCustomer.getId()); + Customer foundCustomer = customerService.findCustomerById(tenantId, savedCustomer.getId()); Assert.assertEquals(foundCustomer.getTitle(), savedCustomer.getTitle()); - customerService.deleteCustomer(savedCustomer.getId()); + customerService.deleteCustomer(tenantId, savedCustomer.getId()); } @Test @@ -81,10 +81,10 @@ public abstract class BaseCustomerServiceTest extends AbstractServiceTest { customer.setTenantId(tenantId); customer.setTitle("My customer"); Customer savedCustomer = customerService.saveCustomer(customer); - Customer foundCustomer = customerService.findCustomerById(savedCustomer.getId()); + Customer foundCustomer = customerService.findCustomerById(tenantId, savedCustomer.getId()); Assert.assertNotNull(foundCustomer); Assert.assertEquals(savedCustomer, foundCustomer); - customerService.deleteCustomer(savedCustomer.getId()); + customerService.deleteCustomer(tenantId, savedCustomer.getId()); } @Test(expected = DataValidationException.class) @@ -124,8 +124,8 @@ public abstract class BaseCustomerServiceTest extends AbstractServiceTest { customer.setTitle("My customer"); customer.setTenantId(tenantId); Customer savedCustomer = customerService.saveCustomer(customer); - customerService.deleteCustomer(savedCustomer.getId()); - Customer foundCustomer = customerService.findCustomerById(savedCustomer.getId()); + customerService.deleteCustomer(tenantId, savedCustomer.getId()); + Customer foundCustomer = customerService.findCustomerById(tenantId, savedCustomer.getId()); Assert.assertNull(foundCustomer); } @@ -228,7 +228,7 @@ public abstract class BaseCustomerServiceTest extends AbstractServiceTest { Assert.assertEquals(customersTitle2, loadedCustomersTitle2); for (Customer customer : loadedCustomersTitle1) { - customerService.deleteCustomer(customer.getId()); + customerService.deleteCustomer(tenantId, customer.getId()); } pageLink = new TextPageLink(4, title1); @@ -237,7 +237,7 @@ public abstract class BaseCustomerServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (Customer customer : loadedCustomersTitle2) { - customerService.deleteCustomer(customer.getId()); + customerService.deleteCustomer(tenantId, customer.getId()); } pageLink = new TextPageLink(4, title2); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseDashboardServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseDashboardServiceTest.java index 02b5186f8d..e5acaf0e3d 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseDashboardServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseDashboardServiceTest.java @@ -75,10 +75,10 @@ public abstract class BaseDashboardServiceTest extends AbstractServiceTest { savedDashboard.setTitle("My new dashboard"); dashboardService.saveDashboard(savedDashboard); - Dashboard foundDashboard = dashboardService.findDashboardById(savedDashboard.getId()); + Dashboard foundDashboard = dashboardService.findDashboardById(tenantId, savedDashboard.getId()); Assert.assertEquals(foundDashboard.getTitle(), savedDashboard.getTitle()); - dashboardService.deleteDashboard(savedDashboard.getId()); + dashboardService.deleteDashboard(tenantId, savedDashboard.getId()); } @Test(expected = DataValidationException.class) @@ -110,9 +110,9 @@ public abstract class BaseDashboardServiceTest extends AbstractServiceTest { dashboard.setTenantId(tenantId); dashboard = dashboardService.saveDashboard(dashboard); try { - dashboardService.assignDashboardToCustomer(dashboard.getId(), new CustomerId(UUIDs.timeBased())); + dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), new CustomerId(UUIDs.timeBased())); } finally { - dashboardService.deleteDashboard(dashboard.getId()); + dashboardService.deleteDashboard(tenantId, dashboard.getId()); } } @@ -130,9 +130,9 @@ public abstract class BaseDashboardServiceTest extends AbstractServiceTest { customer.setTitle("Test different customer"); customer = customerService.saveCustomer(customer); try { - dashboardService.assignDashboardToCustomer(dashboard.getId(), customer.getId()); + dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customer.getId()); } finally { - dashboardService.deleteDashboard(dashboard.getId()); + dashboardService.deleteDashboard(tenantId, dashboard.getId()); tenantService.deleteTenant(tenant.getId()); } } @@ -143,10 +143,10 @@ public abstract class BaseDashboardServiceTest extends AbstractServiceTest { dashboard.setTenantId(tenantId); dashboard.setTitle("My dashboard"); Dashboard savedDashboard = dashboardService.saveDashboard(dashboard); - Dashboard foundDashboard = dashboardService.findDashboardById(savedDashboard.getId()); + Dashboard foundDashboard = dashboardService.findDashboardById(tenantId, savedDashboard.getId()); Assert.assertNotNull(foundDashboard); Assert.assertEquals(savedDashboard, foundDashboard); - dashboardService.deleteDashboard(savedDashboard.getId()); + dashboardService.deleteDashboard(tenantId, savedDashboard.getId()); } @Test @@ -155,10 +155,10 @@ public abstract class BaseDashboardServiceTest extends AbstractServiceTest { dashboard.setTenantId(tenantId); dashboard.setTitle("My dashboard"); Dashboard savedDashboard = dashboardService.saveDashboard(dashboard); - Dashboard foundDashboard = dashboardService.findDashboardById(savedDashboard.getId()); + Dashboard foundDashboard = dashboardService.findDashboardById(tenantId, savedDashboard.getId()); Assert.assertNotNull(foundDashboard); - dashboardService.deleteDashboard(savedDashboard.getId()); - foundDashboard = dashboardService.findDashboardById(savedDashboard.getId()); + dashboardService.deleteDashboard(tenantId, savedDashboard.getId()); + foundDashboard = dashboardService.findDashboardById(tenantId, savedDashboard.getId()); Assert.assertNull(foundDashboard); } @@ -261,7 +261,7 @@ public abstract class BaseDashboardServiceTest extends AbstractServiceTest { Assert.assertEquals(dashboardsTitle2, loadedDashboardsTitle2); for (DashboardInfo dashboard : loadedDashboardsTitle1) { - dashboardService.deleteDashboard(dashboard.getId()); + dashboardService.deleteDashboard(tenantId, dashboard.getId()); } pageLink = new TextPageLink(4, title1); @@ -270,7 +270,7 @@ public abstract class BaseDashboardServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (DashboardInfo dashboard : loadedDashboardsTitle2) { - dashboardService.deleteDashboard(dashboard.getId()); + dashboardService.deleteDashboard(tenantId, dashboard.getId()); } pageLink = new TextPageLink(4, title2); @@ -299,7 +299,7 @@ public abstract class BaseDashboardServiceTest extends AbstractServiceTest { dashboard.setTenantId(tenantId); dashboard.setTitle("Dashboard"+i); dashboard = dashboardService.saveDashboard(dashboard); - dashboards.add(new DashboardInfo(dashboardService.assignDashboardToCustomer(dashboard.getId(), customerId))); + dashboards.add(new DashboardInfo(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId))); } List loadedDashboards = new ArrayList<>(); @@ -318,7 +318,7 @@ public abstract class BaseDashboardServiceTest extends AbstractServiceTest { Assert.assertEquals(dashboards, loadedDashboards); - dashboardService.unassignCustomerDashboards(customerId); + dashboardService.unassignCustomerDashboards(tenantId, customerId); pageLink = new TimePageLink(42); pageData = dashboardService.findDashboardsByTenantIdAndCustomerId(tenantId, customerId, pageLink).get(); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceCredentialsCacheTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceCredentialsCacheTest.java index 9269fc34d9..5e7be3614d 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceCredentialsCacheTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceCredentialsCacheTest.java @@ -72,54 +72,54 @@ public abstract class BaseDeviceCredentialsCacheTest extends AbstractServiceTest @Test public void testFindDeviceCredentialsByCredentialsId_Cached() { - when(deviceCredentialsDao.findByCredentialsId(CREDENTIALS_ID_1)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); + when(deviceCredentialsDao.findByCredentialsId(SYSTEM_TENANT_ID, CREDENTIALS_ID_1)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); - verify(deviceCredentialsDao, times(1)).findByCredentialsId(CREDENTIALS_ID_1); + verify(deviceCredentialsDao, times(1)).findByCredentialsId(SYSTEM_TENANT_ID, CREDENTIALS_ID_1); } @Test public void testDeleteDeviceCredentials_EvictsCache() { - when(deviceCredentialsDao.findByCredentialsId(CREDENTIALS_ID_1)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); + when(deviceCredentialsDao.findByCredentialsId(SYSTEM_TENANT_ID, CREDENTIALS_ID_1)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); - verify(deviceCredentialsDao, times(1)).findByCredentialsId(CREDENTIALS_ID_1); + verify(deviceCredentialsDao, times(1)).findByCredentialsId(SYSTEM_TENANT_ID, CREDENTIALS_ID_1); - deviceCredentialsService.deleteDeviceCredentials(createDummyDeviceCredentials(CREDENTIALS_ID_1, deviceId)); + deviceCredentialsService.deleteDeviceCredentials(SYSTEM_TENANT_ID, createDummyDeviceCredentials(CREDENTIALS_ID_1, deviceId)); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); - verify(deviceCredentialsDao, times(2)).findByCredentialsId(CREDENTIALS_ID_1); + verify(deviceCredentialsDao, times(2)).findByCredentialsId(SYSTEM_TENANT_ID, CREDENTIALS_ID_1); } @Test public void testSaveDeviceCredentials_EvictsPreviousCache() throws Exception { - when(deviceCredentialsDao.findByCredentialsId(CREDENTIALS_ID_1)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); + when(deviceCredentialsDao.findByCredentialsId(SYSTEM_TENANT_ID, CREDENTIALS_ID_1)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); - verify(deviceCredentialsDao, times(1)).findByCredentialsId(CREDENTIALS_ID_1); + verify(deviceCredentialsDao, times(1)).findByCredentialsId(SYSTEM_TENANT_ID, CREDENTIALS_ID_1); - when(deviceCredentialsDao.findByDeviceId(deviceId)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); + when(deviceCredentialsDao.findByDeviceId(SYSTEM_TENANT_ID, deviceId)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); UUID deviceCredentialsId = UUID.randomUUID(); - when(deviceCredentialsDao.findById(deviceCredentialsId)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); - when(deviceService.findDeviceById(new DeviceId(deviceId))).thenReturn(new Device()); + when(deviceCredentialsDao.findById(SYSTEM_TENANT_ID, deviceCredentialsId)).thenReturn(createDummyDeviceCredentialsEntity(CREDENTIALS_ID_1)); + when(deviceService.findDeviceById(SYSTEM_TENANT_ID, new DeviceId(deviceId))).thenReturn(new Device()); - deviceCredentialsService.updateDeviceCredentials(createDummyDeviceCredentials(deviceCredentialsId, CREDENTIALS_ID_2, deviceId)); + deviceCredentialsService.updateDeviceCredentials(SYSTEM_TENANT_ID, createDummyDeviceCredentials(deviceCredentialsId, CREDENTIALS_ID_2, deviceId)); - when(deviceCredentialsDao.findByCredentialsId(CREDENTIALS_ID_1)).thenReturn(null); + when(deviceCredentialsDao.findByCredentialsId(SYSTEM_TENANT_ID, CREDENTIALS_ID_1)).thenReturn(null); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); deviceCredentialsService.findDeviceCredentialsByCredentialsId(CREDENTIALS_ID_1); - verify(deviceCredentialsDao, times(3)).findByCredentialsId(CREDENTIALS_ID_1); + verify(deviceCredentialsDao, times(3)).findByCredentialsId(SYSTEM_TENANT_ID, CREDENTIALS_ID_1); } private DeviceCredentialsService unwrapDeviceCredentialsService() throws Exception { diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceCredentialsServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceCredentialsServiceTest.java index 1d771b2840..b557be3019 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceCredentialsServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceCredentialsServiceTest.java @@ -50,7 +50,7 @@ public abstract class BaseDeviceCredentialsServiceTest extends AbstractServiceTe @Test(expected = DataValidationException.class) public void testCreateDeviceCredentials() { DeviceCredentials deviceCredentials = new DeviceCredentials(); - deviceCredentialsService.updateDeviceCredentials(deviceCredentials); + deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials); } @Test(expected = DataValidationException.class) @@ -60,12 +60,12 @@ public abstract class BaseDeviceCredentialsServiceTest extends AbstractServiceTe device.setType("default"); device.setTenantId(tenantId); device = deviceService.saveDevice(device); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(device.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); deviceCredentials.setDeviceId(null); try { - deviceCredentialsService.updateDeviceCredentials(deviceCredentials); + deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials); } finally { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } } @@ -76,12 +76,12 @@ public abstract class BaseDeviceCredentialsServiceTest extends AbstractServiceTe device.setType("default"); device.setTenantId(tenantId); device = deviceService.saveDevice(device); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(device.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); deviceCredentials.setCredentialsType(null); try { - deviceCredentialsService.updateDeviceCredentials(deviceCredentials); + deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials); } finally { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } } @@ -92,12 +92,12 @@ public abstract class BaseDeviceCredentialsServiceTest extends AbstractServiceTe device.setType("default"); device.setTenantId(tenantId); device = deviceService.saveDevice(device); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(device.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); deviceCredentials.setCredentialsId(null); try { - deviceCredentialsService.updateDeviceCredentials(deviceCredentials); + deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials); } finally { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } } @@ -108,16 +108,16 @@ public abstract class BaseDeviceCredentialsServiceTest extends AbstractServiceTe device.setType("default"); device.setTenantId(tenantId); device = deviceService.saveDevice(device); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(device.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); DeviceCredentials newDeviceCredentials = new DeviceCredentials(new DeviceCredentialsId(UUIDs.timeBased())); newDeviceCredentials.setCreatedTime(deviceCredentials.getCreatedTime()); newDeviceCredentials.setDeviceId(deviceCredentials.getDeviceId()); newDeviceCredentials.setCredentialsType(deviceCredentials.getCredentialsType()); newDeviceCredentials.setCredentialsId(deviceCredentials.getCredentialsId()); try { - deviceCredentialsService.updateDeviceCredentials(newDeviceCredentials); + deviceCredentialsService.updateDeviceCredentials(tenantId, newDeviceCredentials); } finally { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } } @@ -128,12 +128,12 @@ public abstract class BaseDeviceCredentialsServiceTest extends AbstractServiceTe device.setType("default"); device.setTenantId(tenantId); device = deviceService.saveDevice(device); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(device.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); deviceCredentials.setDeviceId(new DeviceId(UUIDs.timeBased())); try { - deviceCredentialsService.updateDeviceCredentials(deviceCredentials); + deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials); } finally { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } } @@ -144,10 +144,10 @@ public abstract class BaseDeviceCredentialsServiceTest extends AbstractServiceTe device.setName("My device"); device.setType("default"); Device savedDevice = deviceService.saveDevice(device); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); - deviceService.deleteDevice(savedDevice.getId()); - deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedDevice.getId()); + deviceService.deleteDevice(tenantId, savedDevice.getId()); + deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertNull(deviceCredentials); } @@ -158,11 +158,11 @@ public abstract class BaseDeviceCredentialsServiceTest extends AbstractServiceTe device.setName("My device"); device.setType("default"); Device savedDevice = deviceService.saveDevice(device); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); DeviceCredentials foundDeviceCredentials = deviceCredentialsService.findDeviceCredentialsByCredentialsId(deviceCredentials.getCredentialsId()); Assert.assertEquals(deviceCredentials, foundDeviceCredentials); - deviceService.deleteDevice(savedDevice.getId()); + deviceService.deleteDevice(tenantId, savedDevice.getId()); foundDeviceCredentials = deviceCredentialsService.findDeviceCredentialsByCredentialsId(deviceCredentials.getCredentialsId()); Assert.assertNull(foundDeviceCredentials); } @@ -174,14 +174,14 @@ public abstract class BaseDeviceCredentialsServiceTest extends AbstractServiceTe device.setName("My device"); device.setType("default"); Device savedDevice = deviceService.saveDevice(device); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); deviceCredentials.setCredentialsType(DeviceCredentialsType.ACCESS_TOKEN); deviceCredentials.setCredentialsId("access_token"); - deviceCredentialsService.updateDeviceCredentials(deviceCredentials); - DeviceCredentials foundDeviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedDevice.getId()); + deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials); + DeviceCredentials foundDeviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertEquals(deviceCredentials, foundDeviceCredentials); - deviceService.deleteDevice(savedDevice.getId()); + deviceService.deleteDevice(tenantId, savedDevice.getId()); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceServiceTest.java index cd8a4785bb..fe6e2266a7 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceServiceTest.java @@ -75,7 +75,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals(NULL_UUID, savedDevice.getCustomerId().getId()); Assert.assertEquals(device.getName(), savedDevice.getName()); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertNotNull(deviceCredentials); Assert.assertNotNull(deviceCredentials.getId()); Assert.assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); @@ -86,10 +86,10 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { savedDevice.setName("My new device"); deviceService.saveDevice(savedDevice); - Device foundDevice = deviceService.findDeviceById(savedDevice.getId()); + Device foundDevice = deviceService.findDeviceById(tenantId, savedDevice.getId()); Assert.assertEquals(foundDevice.getName(), savedDevice.getName()); - deviceService.deleteDevice(savedDevice.getId()); + deviceService.deleteDevice(tenantId, savedDevice.getId()); } @Test(expected = DataValidationException.class) @@ -125,9 +125,9 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { device.setTenantId(tenantId); device = deviceService.saveDevice(device); try { - deviceService.assignDeviceToCustomer(device.getId(), new CustomerId(UUIDs.timeBased())); + deviceService.assignDeviceToCustomer(tenantId, device.getId(), new CustomerId(UUIDs.timeBased())); } finally { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } } @@ -146,9 +146,9 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { customer.setTitle("Test different customer"); customer = customerService.saveCustomer(customer); try { - deviceService.assignDeviceToCustomer(device.getId(), customer.getId()); + deviceService.assignDeviceToCustomer(tenantId, device.getId(), customer.getId()); } finally { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); tenantService.deleteTenant(tenant.getId()); } } @@ -160,10 +160,10 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { device.setName("My device"); device.setType("default"); Device savedDevice = deviceService.saveDevice(device); - Device foundDevice = deviceService.findDeviceById(savedDevice.getId()); + Device foundDevice = deviceService.findDeviceById(tenantId, savedDevice.getId()); Assert.assertNotNull(foundDevice); Assert.assertEquals(savedDevice, foundDevice); - deviceService.deleteDevice(savedDevice.getId()); + deviceService.deleteDevice(tenantId, savedDevice.getId()); } @Test @@ -198,7 +198,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals("typeB", deviceTypes.get(1).getType()); Assert.assertEquals("typeC", deviceTypes.get(2).getType()); } finally { - devices.forEach((device) -> { deviceService.deleteDevice(device.getId()); }); + devices.forEach((device) -> { deviceService.deleteDevice(tenantId, device.getId()); }); } } @@ -209,12 +209,12 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { device.setName("My device"); device.setType("default"); Device savedDevice = deviceService.saveDevice(device); - Device foundDevice = deviceService.findDeviceById(savedDevice.getId()); + Device foundDevice = deviceService.findDeviceById(tenantId, savedDevice.getId()); Assert.assertNotNull(foundDevice); - deviceService.deleteDevice(savedDevice.getId()); - foundDevice = deviceService.findDeviceById(savedDevice.getId()); + deviceService.deleteDevice(tenantId, savedDevice.getId()); + foundDevice = deviceService.findDeviceById(tenantId, savedDevice.getId()); Assert.assertNull(foundDevice); - DeviceCredentials foundDeviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedDevice.getId()); + DeviceCredentials foundDeviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertNull(foundDeviceCredentials); } @@ -320,7 +320,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals(devicesTitle2, loadedDevicesTitle2); for (Device device : loadedDevicesTitle1) { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4, title1); @@ -329,7 +329,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (Device device : loadedDevicesTitle2) { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4, title2); @@ -399,7 +399,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals(devicesType2, loadedDevicesType2); for (Device device : loadedDevicesType1) { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4); @@ -408,7 +408,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (Device device : loadedDevicesType2) { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4); @@ -438,7 +438,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { device.setName("Device"+i); device.setType("default"); device = deviceService.saveDevice(device); - devices.add(deviceService.assignDeviceToCustomer(device.getId(), customerId)); + devices.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } List loadedDevices = new ArrayList<>(); @@ -487,7 +487,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { device.setName(name); device.setType("default"); device = deviceService.saveDevice(device); - devicesTitle1.add(deviceService.assignDeviceToCustomer(device.getId(), customerId)); + devicesTitle1.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } String title2 = "Device title 2"; List devicesTitle2 = new ArrayList<>(); @@ -500,7 +500,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { device.setName(name); device.setType("default"); device = deviceService.saveDevice(device); - devicesTitle2.add(deviceService.assignDeviceToCustomer(device.getId(), customerId)); + devicesTitle2.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } List loadedDevicesTitle1 = new ArrayList<>(); @@ -535,7 +535,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals(devicesTitle2, loadedDevicesTitle2); for (Device device : loadedDevicesTitle1) { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4, title1); @@ -544,14 +544,14 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (Device device : loadedDevicesTitle2) { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4, title2); pageData = deviceService.findDevicesByTenantIdAndCustomerId(tenantId, customerId, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - customerService.deleteCustomer(customerId); + customerService.deleteCustomer(tenantId, customerId); } @Test @@ -575,7 +575,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { device.setName(name); device.setType(type1); device = deviceService.saveDevice(device); - devicesType1.add(deviceService.assignDeviceToCustomer(device.getId(), customerId)); + devicesType1.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } String title2 = "Device title 2"; String type2 = "typeD"; @@ -589,7 +589,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { device.setName(name); device.setType(type2); device = deviceService.saveDevice(device); - devicesType2.add(deviceService.assignDeviceToCustomer(device.getId(), customerId)); + devicesType2.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } List loadedDevicesType1 = new ArrayList<>(); @@ -624,7 +624,7 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals(devicesType2, loadedDevicesType2); for (Device device : loadedDevicesType1) { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4); @@ -633,14 +633,14 @@ public abstract class BaseDeviceServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (Device device : loadedDevicesType2) { - deviceService.deleteDevice(device.getId()); + deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4); pageData = deviceService.findDevicesByTenantIdAndCustomerIdAndType(tenantId, customerId, type2, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - customerService.deleteCustomer(customerId); + customerService.deleteCustomer(tenantId, customerId); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseRelationCacheTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseRelationCacheTest.java index bc78fd7ec3..74af633014 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseRelationCacheTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseRelationCacheTest.java @@ -74,31 +74,31 @@ public abstract class BaseRelationCacheTest extends AbstractServiceTest { @Test public void testFindRelationByFrom_Cached() throws ExecutionException, InterruptedException { - when(relationDao.getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON)) + when(relationDao.getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON)) .thenReturn(Futures.immediateFuture(new EntityRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE))); - relationService.getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); - relationService.getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + relationService.getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + relationService.getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); - verify(relationDao, times(1)).getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + verify(relationDao, times(1)).getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); } @Test public void testDeleteRelations_EvictsCache() { - when(relationDao.getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON)) + when(relationDao.getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON)) .thenReturn(Futures.immediateFuture(new EntityRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE))); - relationService.getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); - relationService.getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + relationService.getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + relationService.getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); - verify(relationDao, times(1)).getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + verify(relationDao, times(1)).getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); - relationService.deleteRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + relationService.deleteRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); - relationService.getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); - relationService.getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + relationService.getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + relationService.getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); - verify(relationDao, times(2)).getRelation(ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); + verify(relationDao, times(2)).getRelation(SYSTEM_TENANT_ID, ENTITY_ID_FROM, ENTITY_ID_TO, RELATION_TYPE, RelationTypeGroup.COMMON); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseRelationServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseRelationServiceTest.java index d269126d90..e2d0bfb71f 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseRelationServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseRelationServiceTest.java @@ -54,13 +54,13 @@ public abstract class BaseRelationServiceTest extends AbstractServiceTest { Assert.assertTrue(saveRelation(relation)); - Assert.assertTrue(relationService.checkRelation(parentId, childId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); + Assert.assertTrue(relationService.checkRelation(SYSTEM_TENANT_ID, parentId, childId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); - Assert.assertFalse(relationService.checkRelation(parentId, childId, "NOT_EXISTING_TYPE", RelationTypeGroup.COMMON).get()); + Assert.assertFalse(relationService.checkRelation(SYSTEM_TENANT_ID, parentId, childId, "NOT_EXISTING_TYPE", RelationTypeGroup.COMMON).get()); - Assert.assertFalse(relationService.checkRelation(childId, parentId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); + Assert.assertFalse(relationService.checkRelation(SYSTEM_TENANT_ID, childId, parentId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); - Assert.assertFalse(relationService.checkRelation(childId, parentId, "NOT_EXISTING_TYPE", RelationTypeGroup.COMMON).get()); + Assert.assertFalse(relationService.checkRelation(SYSTEM_TENANT_ID, childId, parentId, "NOT_EXISTING_TYPE", RelationTypeGroup.COMMON).get()); } @Test @@ -75,13 +75,13 @@ public abstract class BaseRelationServiceTest extends AbstractServiceTest { saveRelation(relationA); saveRelation(relationB); - Assert.assertTrue(relationService.deleteRelationAsync(relationA).get()); + Assert.assertTrue(relationService.deleteRelationAsync(SYSTEM_TENANT_ID, relationA).get()); - Assert.assertFalse(relationService.checkRelation(parentId, childId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); + Assert.assertFalse(relationService.checkRelation(SYSTEM_TENANT_ID, parentId, childId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); - Assert.assertTrue(relationService.checkRelation(childId, subChildId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); + Assert.assertTrue(relationService.checkRelation(SYSTEM_TENANT_ID, childId, subChildId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); - Assert.assertTrue(relationService.deleteRelationAsync(childId, subChildId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); + Assert.assertTrue(relationService.deleteRelationAsync(SYSTEM_TENANT_ID, childId, subChildId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); } @Test @@ -96,11 +96,11 @@ public abstract class BaseRelationServiceTest extends AbstractServiceTest { saveRelation(relationA); saveRelation(relationB); - Assert.assertNull(relationService.deleteEntityRelationsAsync(childId).get()); + Assert.assertNull(relationService.deleteEntityRelationsAsync(SYSTEM_TENANT_ID, childId).get()); - Assert.assertFalse(relationService.checkRelation(parentId, childId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); + Assert.assertFalse(relationService.checkRelation(SYSTEM_TENANT_ID, parentId, childId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); - Assert.assertFalse(relationService.checkRelation(childId, subChildId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); + Assert.assertFalse(relationService.checkRelation(SYSTEM_TENANT_ID, childId, subChildId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); } @Test @@ -122,7 +122,7 @@ public abstract class BaseRelationServiceTest extends AbstractServiceTest { saveRelation(relationB1); saveRelation(relationB2); - List relations = relationService.findByFrom(parentA, RelationTypeGroup.COMMON); + List relations = relationService.findByFrom(SYSTEM_TENANT_ID, parentA, RelationTypeGroup.COMMON); Assert.assertEquals(2, relations.size()); for (EntityRelation relation : relations) { Assert.assertEquals(EntityRelation.CONTAINS_TYPE, relation.getType()); @@ -130,13 +130,13 @@ public abstract class BaseRelationServiceTest extends AbstractServiceTest { Assert.assertTrue(childA.equals(relation.getTo()) || childB.equals(relation.getTo())); } - relations = relationService.findByFromAndType(parentA, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON); + relations = relationService.findByFromAndType(SYSTEM_TENANT_ID, parentA, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON); Assert.assertEquals(2, relations.size()); - relations = relationService.findByFromAndType(parentA, EntityRelation.MANAGES_TYPE, RelationTypeGroup.COMMON); + relations = relationService.findByFromAndType(SYSTEM_TENANT_ID, parentA, EntityRelation.MANAGES_TYPE, RelationTypeGroup.COMMON); Assert.assertEquals(0, relations.size()); - relations = relationService.findByFrom(parentB, RelationTypeGroup.COMMON); + relations = relationService.findByFrom(SYSTEM_TENANT_ID, parentB, RelationTypeGroup.COMMON); Assert.assertEquals(2, relations.size()); for (EntityRelation relation : relations) { Assert.assertEquals(EntityRelation.MANAGES_TYPE, relation.getType()); @@ -144,15 +144,15 @@ public abstract class BaseRelationServiceTest extends AbstractServiceTest { Assert.assertTrue(childA.equals(relation.getTo()) || childB.equals(relation.getTo())); } - relations = relationService.findByFromAndType(parentB, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON); + relations = relationService.findByFromAndType(SYSTEM_TENANT_ID, parentB, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON); Assert.assertEquals(0, relations.size()); - relations = relationService.findByFromAndType(parentB, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON); + relations = relationService.findByFromAndType(SYSTEM_TENANT_ID, parentB, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON); Assert.assertEquals(0, relations.size()); } private Boolean saveRelation(EntityRelation relationA1) throws ExecutionException, InterruptedException { - return relationService.saveRelationAsync(relationA1).get(); + return relationService.saveRelationAsync(SYSTEM_TENANT_ID, relationA1).get(); } @Test @@ -177,26 +177,26 @@ public abstract class BaseRelationServiceTest extends AbstractServiceTest { // Data propagation to views is async Thread.sleep(3000); - List relations = relationService.findByTo(childA, RelationTypeGroup.COMMON); + List relations = relationService.findByTo(SYSTEM_TENANT_ID, childA, RelationTypeGroup.COMMON); Assert.assertEquals(2, relations.size()); for (EntityRelation relation : relations) { Assert.assertEquals(childA, relation.getTo()); Assert.assertTrue(parentA.equals(relation.getFrom()) || parentB.equals(relation.getFrom())); } - relations = relationService.findByToAndType(childA, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON); + relations = relationService.findByToAndType(SYSTEM_TENANT_ID, childA, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON); Assert.assertEquals(1, relations.size()); - relations = relationService.findByToAndType(childB, EntityRelation.MANAGES_TYPE, RelationTypeGroup.COMMON); + relations = relationService.findByToAndType(SYSTEM_TENANT_ID, childB, EntityRelation.MANAGES_TYPE, RelationTypeGroup.COMMON); Assert.assertEquals(1, relations.size()); - relations = relationService.findByToAndType(parentA, EntityRelation.MANAGES_TYPE, RelationTypeGroup.COMMON); + relations = relationService.findByToAndType(SYSTEM_TENANT_ID, parentA, EntityRelation.MANAGES_TYPE, RelationTypeGroup.COMMON); Assert.assertEquals(0, relations.size()); - relations = relationService.findByToAndType(parentB, EntityRelation.MANAGES_TYPE, RelationTypeGroup.COMMON); + relations = relationService.findByToAndType(SYSTEM_TENANT_ID, parentB, EntityRelation.MANAGES_TYPE, RelationTypeGroup.COMMON); Assert.assertEquals(0, relations.size()); - relations = relationService.findByTo(childB, RelationTypeGroup.COMMON); + relations = relationService.findByTo(SYSTEM_TENANT_ID, childB, RelationTypeGroup.COMMON); Assert.assertEquals(2, relations.size()); for (EntityRelation relation : relations) { Assert.assertEquals(childB, relation.getTo()); @@ -222,14 +222,14 @@ public abstract class BaseRelationServiceTest extends AbstractServiceTest { EntityRelationsQuery query = new EntityRelationsQuery(); query.setParameters(new RelationsSearchParameters(assetA, EntitySearchDirection.FROM, -1)); query.setFilters(Collections.singletonList(new EntityTypeFilter(EntityRelation.CONTAINS_TYPE, Collections.singletonList(EntityType.ASSET)))); - List relations = relationService.findByQuery(query).get(); + List relations = relationService.findByQuery(SYSTEM_TENANT_ID, query).get(); Assert.assertEquals(3, relations.size()); Assert.assertTrue(relations.contains(relationA)); Assert.assertTrue(relations.contains(relationB)); Assert.assertTrue(relations.contains(relationC)); //Test from cache - relations = relationService.findByQuery(query).get(); + relations = relationService.findByQuery(SYSTEM_TENANT_ID, query).get(); Assert.assertEquals(3, relations.size()); Assert.assertTrue(relations.contains(relationA)); Assert.assertTrue(relations.contains(relationB)); @@ -256,13 +256,13 @@ public abstract class BaseRelationServiceTest extends AbstractServiceTest { EntityRelationsQuery query = new EntityRelationsQuery(); query.setParameters(new RelationsSearchParameters(assetA, EntitySearchDirection.FROM, -1)); query.setFilters(Collections.singletonList(new EntityTypeFilter(EntityRelation.CONTAINS_TYPE, Collections.singletonList(EntityType.ASSET)))); - List relations = relationService.findByQuery(query).get(); + List relations = relationService.findByQuery(SYSTEM_TENANT_ID, query).get(); Assert.assertEquals(2, relations.size()); Assert.assertTrue(relations.contains(relationAB)); Assert.assertTrue(relations.contains(relationBC)); //Test from cache - relations = relationService.findByQuery(query).get(); + relations = relationService.findByQuery(SYSTEM_TENANT_ID, query).get(); Assert.assertEquals(2, relations.size()); Assert.assertTrue(relations.contains(relationAB)); Assert.assertTrue(relations.contains(relationBC)); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseRuleChainServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseRuleChainServiceTest.java index 28c61475ee..196fea1c8a 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseRuleChainServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseRuleChainServiceTest.java @@ -78,10 +78,10 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { savedRuleChain.setName("My new RuleChain"); ruleChainService.saveRuleChain(savedRuleChain); - RuleChain foundRuleChain = ruleChainService.findRuleChainById(savedRuleChain.getId()); + RuleChain foundRuleChain = ruleChainService.findRuleChainById(tenantId, savedRuleChain.getId()); Assert.assertEquals(foundRuleChain.getName(), savedRuleChain.getName()); - ruleChainService.deleteRuleChainById(savedRuleChain.getId()); + ruleChainService.deleteRuleChainById(tenantId, savedRuleChain.getId()); } @Test(expected = DataValidationException.class) @@ -105,10 +105,10 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { ruleChain.setTenantId(tenantId); ruleChain.setName("My RuleChain"); RuleChain savedRuleChain = ruleChainService.saveRuleChain(ruleChain); - RuleChain foundRuleChain = ruleChainService.findRuleChainById(savedRuleChain.getId()); + RuleChain foundRuleChain = ruleChainService.findRuleChainById(tenantId, savedRuleChain.getId()); Assert.assertNotNull(foundRuleChain); Assert.assertEquals(savedRuleChain, foundRuleChain); - ruleChainService.deleteRuleChainById(savedRuleChain.getId()); + ruleChainService.deleteRuleChainById(tenantId, savedRuleChain.getId()); } @Test @@ -117,10 +117,10 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { ruleChain.setTenantId(tenantId); ruleChain.setName("My RuleChain"); RuleChain savedRuleChain = ruleChainService.saveRuleChain(ruleChain); - RuleChain foundRuleChain = ruleChainService.findRuleChainById(savedRuleChain.getId()); + RuleChain foundRuleChain = ruleChainService.findRuleChainById(tenantId, savedRuleChain.getId()); Assert.assertNotNull(foundRuleChain); - ruleChainService.deleteRuleChainById(savedRuleChain.getId()); - foundRuleChain = ruleChainService.findRuleChainById(savedRuleChain.getId()); + ruleChainService.deleteRuleChainById(tenantId, savedRuleChain.getId()); + foundRuleChain = ruleChainService.findRuleChainById(tenantId, savedRuleChain.getId()); Assert.assertNull(foundRuleChain); } @@ -223,7 +223,7 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { Assert.assertEquals(ruleChainsName2, loadedRuleChainsName2); for (RuleChain ruleChain : loadedRuleChainsName1) { - ruleChainService.deleteRuleChainById(ruleChain.getId()); + ruleChainService.deleteRuleChainById(tenantId, ruleChain.getId()); } pageLink = new TextPageLink(4, name1); @@ -232,7 +232,7 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (RuleChain ruleChain : loadedRuleChainsName2) { - ruleChainService.deleteRuleChainById(ruleChain.getId()); + ruleChainService.deleteRuleChainById(tenantId, ruleChain.getId()); } pageLink = new TextPageLink(4, name2); @@ -251,7 +251,7 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { for (RuleNode ruleNode : savedRuleChainMetaData.getNodes()) { Assert.assertNotNull(ruleNode.getId()); - List relations = ruleChainService.getRuleNodeRelations(ruleNode.getId()); + List relations = ruleChainService.getRuleNodeRelations(tenantId, ruleNode.getId()); if ("name1".equals(ruleNode.getName())) { Assert.assertEquals(2, relations.size()); } else if ("name2".equals(ruleNode.getName())) { @@ -261,14 +261,14 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { } } - List loadedRuleNodes = ruleChainService.getRuleChainNodes(savedRuleChainMetaData.getRuleChainId()); + List loadedRuleNodes = ruleChainService.getRuleChainNodes(tenantId, savedRuleChainMetaData.getRuleChainId()); Collections.sort(savedRuleChainMetaData.getNodes(), ruleNodeIdComparator); Collections.sort(loadedRuleNodes, ruleNodeIdComparator); Assert.assertEquals(savedRuleChainMetaData.getNodes(), loadedRuleNodes); - ruleChainService.deleteRuleChainById(savedRuleChainMetaData.getRuleChainId()); + ruleChainService.deleteRuleChainById(tenantId, savedRuleChainMetaData.getRuleChainId()); } @Test @@ -291,14 +291,14 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { ruleNodes.set(name3Index, ruleNode4); - RuleChainMetaData updatedRuleChainMetaData = ruleChainService.saveRuleChainMetaData(savedRuleChainMetaData); + RuleChainMetaData updatedRuleChainMetaData = ruleChainService.saveRuleChainMetaData(tenantId, savedRuleChainMetaData); Assert.assertEquals(3, updatedRuleChainMetaData.getNodes().size()); Assert.assertEquals(3, updatedRuleChainMetaData.getConnections().size()); for (RuleNode ruleNode : updatedRuleChainMetaData.getNodes()) { Assert.assertNotNull(ruleNode.getId()); - List relations = ruleChainService.getRuleNodeRelations(ruleNode.getId()); + List relations = ruleChainService.getRuleNodeRelations(tenantId, ruleNode.getId()); if ("name1".equals(ruleNode.getName())) { Assert.assertEquals(2, relations.size()); } else if ("name2".equals(ruleNode.getName())) { @@ -308,14 +308,14 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { } } - List loadedRuleNodes = ruleChainService.getRuleChainNodes(savedRuleChainMetaData.getRuleChainId()); + List loadedRuleNodes = ruleChainService.getRuleChainNodes(tenantId, savedRuleChainMetaData.getRuleChainId()); Collections.sort(updatedRuleChainMetaData.getNodes(), ruleNodeIdComparator); Collections.sort(loadedRuleNodes, ruleNodeIdComparator); Assert.assertEquals(updatedRuleChainMetaData.getNodes(), loadedRuleNodes); - ruleChainService.deleteRuleChainById(savedRuleChainMetaData.getRuleChainId()); + ruleChainService.deleteRuleChainById(tenantId, savedRuleChainMetaData.getRuleChainId()); } private RuleChainMetaData createRuleChainMetadata() throws Exception { @@ -355,7 +355,7 @@ public abstract class BaseRuleChainServiceTest extends AbstractServiceTest { ruleChainMetaData.addConnectionInfo(0,2,"fail"); ruleChainMetaData.addConnectionInfo(1,2,"success"); - return ruleChainService.saveRuleChainMetaData(ruleChainMetaData); + return ruleChainService.saveRuleChainMetaData(tenantId, ruleChainMetaData); } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseUserServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseUserServiceTest.java index cd2dcc3c07..be73981770 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseUserServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseUserServiceTest.java @@ -75,39 +75,39 @@ public abstract class BaseUserServiceTest extends AbstractServiceTest { @Test public void testFindUserByEmail() { - User user = userService.findUserByEmail("sysadmin@thingsboard.org"); + User user = userService.findUserByEmail(SYSTEM_TENANT_ID, "sysadmin@thingsboard.org"); Assert.assertNotNull(user); Assert.assertEquals(Authority.SYS_ADMIN, user.getAuthority()); - user = userService.findUserByEmail("tenant@thingsboard.org"); + user = userService.findUserByEmail(tenantId, "tenant@thingsboard.org"); Assert.assertNotNull(user); Assert.assertEquals(Authority.TENANT_ADMIN, user.getAuthority()); - user = userService.findUserByEmail("customer@thingsboard.org"); + user = userService.findUserByEmail(tenantId, "customer@thingsboard.org"); Assert.assertNotNull(user); Assert.assertEquals(Authority.CUSTOMER_USER, user.getAuthority()); - user = userService.findUserByEmail("fake@thingsboard.org"); + user = userService.findUserByEmail(tenantId, "fake@thingsboard.org"); Assert.assertNull(user); } @Test public void testFindUserById() { - User user = userService.findUserByEmail("sysadmin@thingsboard.org"); + User user = userService.findUserByEmail(SYSTEM_TENANT_ID, "sysadmin@thingsboard.org"); Assert.assertNotNull(user); - User foundUser = userService.findUserById(user.getId()); + User foundUser = userService.findUserById(SYSTEM_TENANT_ID, user.getId()); Assert.assertNotNull(foundUser); Assert.assertEquals(user, foundUser); } @Test public void testFindUserCredentials() { - User user = userService.findUserByEmail("sysadmin@thingsboard.org"); + User user = userService.findUserByEmail(SYSTEM_TENANT_ID,"sysadmin@thingsboard.org"); Assert.assertNotNull(user); - UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId()); + UserCredentials userCredentials = userService.findUserCredentialsByUserId(SYSTEM_TENANT_ID, user.getId()); Assert.assertNotNull(userCredentials); } @Test public void testSaveUser() { - User tenantAdminUser = userService.findUserByEmail("tenant@thingsboard.org"); + User tenantAdminUser = userService.findUserByEmail(SYSTEM_TENANT_ID,"tenant@thingsboard.org"); User user = new User(); user.setAuthority(Authority.TENANT_ADMIN); user.setTenantId(tenantAdminUser.getTenantId()); @@ -119,7 +119,7 @@ public abstract class BaseUserServiceTest extends AbstractServiceTest { Assert.assertEquals(user.getEmail(), savedUser.getEmail()); Assert.assertEquals(user.getTenantId(), savedUser.getTenantId()); Assert.assertEquals(user.getAuthority(), savedUser.getAuthority()); - UserCredentials userCredentials = userService.findUserCredentialsByUserId(savedUser.getId()); + UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, savedUser.getId()); Assert.assertNotNull(userCredentials); Assert.assertNotNull(userCredentials.getId()); Assert.assertNotNull(userCredentials.getUserId()); @@ -129,44 +129,44 @@ public abstract class BaseUserServiceTest extends AbstractServiceTest { savedUser.setLastName("Downs"); userService.saveUser(savedUser); - savedUser = userService.findUserById(savedUser.getId()); + savedUser = userService.findUserById(tenantId, savedUser.getId()); Assert.assertEquals("Joe", savedUser.getFirstName()); Assert.assertEquals("Downs", savedUser.getLastName()); - userService.deleteUser(savedUser.getId()); + userService.deleteUser(tenantId, savedUser.getId()); } @Test(expected = DataValidationException.class) public void testSaveUserWithSameEmail() { - User tenantAdminUser = userService.findUserByEmail("tenant@thingsboard.org"); + User tenantAdminUser = userService.findUserByEmail(tenantId, "tenant@thingsboard.org"); tenantAdminUser.setEmail("sysadmin@thingsboard.org"); userService.saveUser(tenantAdminUser); } @Test(expected = DataValidationException.class) public void testSaveUserWithInvalidEmail() { - User tenantAdminUser = userService.findUserByEmail("tenant@thingsboard.org"); + User tenantAdminUser = userService.findUserByEmail(tenantId, "tenant@thingsboard.org"); tenantAdminUser.setEmail("tenant_thingsboard.org"); userService.saveUser(tenantAdminUser); } @Test(expected = DataValidationException.class) public void testSaveUserWithEmptyEmail() { - User tenantAdminUser = userService.findUserByEmail("tenant@thingsboard.org"); + User tenantAdminUser = userService.findUserByEmail(tenantId, "tenant@thingsboard.org"); tenantAdminUser.setEmail(null); userService.saveUser(tenantAdminUser); } @Test(expected = DataValidationException.class) public void testSaveUserWithoutTenant() { - User tenantAdminUser = userService.findUserByEmail("tenant@thingsboard.org"); + User tenantAdminUser = userService.findUserByEmail(tenantId, "tenant@thingsboard.org"); tenantAdminUser.setTenantId(null); userService.saveUser(tenantAdminUser); } @Test public void testDeleteUser() { - User tenantAdminUser = userService.findUserByEmail("tenant@thingsboard.org"); + User tenantAdminUser = userService.findUserByEmail(tenantId, "tenant@thingsboard.org"); User user = new User(); user.setAuthority(Authority.TENANT_ADMIN); user.setTenantId(tenantAdminUser.getTenantId()); @@ -174,20 +174,20 @@ public abstract class BaseUserServiceTest extends AbstractServiceTest { User savedUser = userService.saveUser(user); Assert.assertNotNull(savedUser); Assert.assertNotNull(savedUser.getId()); - User foundUser = userService.findUserById(savedUser.getId()); + User foundUser = userService.findUserById(tenantId, savedUser.getId()); Assert.assertNotNull(foundUser); - UserCredentials userCredentials = userService.findUserCredentialsByUserId(foundUser.getId()); + UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, foundUser.getId()); Assert.assertNotNull(userCredentials); - userService.deleteUser(foundUser.getId()); - userCredentials = userService.findUserCredentialsByUserId(foundUser.getId()); - foundUser = userService.findUserById(foundUser.getId()); + userService.deleteUser(tenantId, foundUser.getId()); + userCredentials = userService.findUserCredentialsByUserId(tenantId, foundUser.getId()); + foundUser = userService.findUserById(tenantId, foundUser.getId()); Assert.assertNull(foundUser); Assert.assertNull(userCredentials); } @Test public void testFindTenantAdmins() { - User tenantAdminUser = userService.findUserByEmail("tenant@thingsboard.org"); + User tenantAdminUser = userService.findUserByEmail(tenantId, "tenant@thingsboard.org"); TextPageData pageData = userService.findTenantAdmins(tenantAdminUser.getTenantId(), new TextPageLink(10)); Assert.assertFalse(pageData.hasNext()); List users = pageData.getData(); @@ -301,7 +301,7 @@ public abstract class BaseUserServiceTest extends AbstractServiceTest { Assert.assertEquals(tenantAdminsEmail2, loadedTenantAdminsEmail2); for (User user : loadedTenantAdminsEmail1) { - userService.deleteUser(user.getId()); + userService.deleteUser(tenantId, user.getId()); } pageLink = new TextPageLink(4, email1); @@ -310,7 +310,7 @@ public abstract class BaseUserServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (User user : loadedTenantAdminsEmail2) { - userService.deleteUser(user.getId()); + userService.deleteUser(tenantId, user.getId()); } pageLink = new TextPageLink(4, email2); @@ -323,7 +323,7 @@ public abstract class BaseUserServiceTest extends AbstractServiceTest { @Test public void testFindCustomerUsers() { - User customerUser = userService.findUserByEmail("customer@thingsboard.org"); + User customerUser = userService.findUserByEmail(tenantId, "customer@thingsboard.org"); TextPageData pageData = userService.findCustomerUsers(customerUser.getTenantId(), customerUser.getCustomerId(), new TextPageLink(10)); Assert.assertFalse(pageData.hasNext()); @@ -454,7 +454,7 @@ public abstract class BaseUserServiceTest extends AbstractServiceTest { Assert.assertEquals(customerUsersEmail2, loadedCustomerUsersEmail2); for (User user : loadedCustomerUsersEmail1) { - userService.deleteUser(user.getId()); + userService.deleteUser(tenantId, user.getId()); } pageLink = new TextPageLink(4, email1); @@ -463,7 +463,7 @@ public abstract class BaseUserServiceTest extends AbstractServiceTest { Assert.assertEquals(0, pageData.getData().size()); for (User user : loadedCustomerUsersEmail2) { - userService.deleteUser(user.getId()); + userService.deleteUser(tenantId, user.getId()); } pageLink = new TextPageLink(4, email2); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseWidgetTypeServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseWidgetTypeServiceTest.java index 28bdfbcfe8..6c1b00bb5f 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseWidgetTypeServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseWidgetTypeServiceTest.java @@ -81,10 +81,10 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { savedWidgetType.setName("New Widget Type"); widgetTypeService.saveWidgetType(savedWidgetType); - WidgetType foundWidgetType = widgetTypeService.findWidgetTypeById(savedWidgetType.getId()); + WidgetType foundWidgetType = widgetTypeService.findWidgetTypeById(tenantId, savedWidgetType.getId()); Assert.assertEquals(foundWidgetType.getName(), savedWidgetType.getName()); - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } @Test(expected = DataValidationException.class) @@ -101,7 +101,7 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { try { widgetTypeService.saveWidgetType(widgetType); } finally { - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } } @@ -129,7 +129,7 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { try { widgetTypeService.saveWidgetType(widgetType); } finally { - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } } @@ -148,7 +148,7 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { try { widgetTypeService.saveWidgetType(widgetType); } finally { - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } } @@ -179,7 +179,7 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { try { widgetTypeService.saveWidgetType(savedWidgetType); } finally { - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } } @@ -200,7 +200,7 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { try { widgetTypeService.saveWidgetType(savedWidgetType); } finally { - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } } @@ -221,7 +221,7 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { try { widgetTypeService.saveWidgetType(savedWidgetType); } finally { - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } } @@ -238,11 +238,11 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { widgetType.setName("Widget Type"); widgetType.setDescriptor(new ObjectMapper().readValue("{ \"someKey\": \"someValue\" }", JsonNode.class)); WidgetType savedWidgetType = widgetTypeService.saveWidgetType(widgetType); - WidgetType foundWidgetType = widgetTypeService.findWidgetTypeById(savedWidgetType.getId()); + WidgetType foundWidgetType = widgetTypeService.findWidgetTypeById(tenantId, savedWidgetType.getId()); Assert.assertNotNull(foundWidgetType); Assert.assertEquals(savedWidgetType, foundWidgetType); - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } @Test @@ -262,7 +262,7 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { Assert.assertNotNull(foundWidgetType); Assert.assertEquals(savedWidgetType, foundWidgetType); - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } @Test @@ -278,13 +278,13 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { widgetType.setName("Widget Type"); widgetType.setDescriptor(new ObjectMapper().readValue("{ \"someKey\": \"someValue\" }", JsonNode.class)); WidgetType savedWidgetType = widgetTypeService.saveWidgetType(widgetType); - WidgetType foundWidgetType = widgetTypeService.findWidgetTypeById(savedWidgetType.getId()); + WidgetType foundWidgetType = widgetTypeService.findWidgetTypeById(tenantId, savedWidgetType.getId()); Assert.assertNotNull(foundWidgetType); - widgetTypeService.deleteWidgetType(savedWidgetType.getId()); - foundWidgetType = widgetTypeService.findWidgetTypeById(savedWidgetType.getId()); + widgetTypeService.deleteWidgetType(tenantId, savedWidgetType.getId()); + foundWidgetType = widgetTypeService.findWidgetTypeById(tenantId, savedWidgetType.getId()); Assert.assertNull(foundWidgetType); - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } @Test @@ -317,7 +317,7 @@ public abstract class BaseWidgetTypeServiceTest extends AbstractServiceTest { Assert.assertTrue(loadedWidgetTypes.isEmpty()); - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/BaseWidgetsBundleServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/BaseWidgetsBundleServiceTest.java index 11589e2ca6..9dfb332869 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/BaseWidgetsBundleServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/BaseWidgetsBundleServiceTest.java @@ -71,10 +71,10 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { savedWidgetsBundle.setTitle("My new widgets bundle"); widgetsBundleService.saveWidgetsBundle(savedWidgetsBundle); - WidgetsBundle foundWidgetsBundle = widgetsBundleService.findWidgetsBundleById(savedWidgetsBundle.getId()); + WidgetsBundle foundWidgetsBundle = widgetsBundleService.findWidgetsBundleById(tenantId, savedWidgetsBundle.getId()); Assert.assertEquals(foundWidgetsBundle.getTitle(), savedWidgetsBundle.getTitle()); - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } @Test(expected = DataValidationException.class) @@ -102,7 +102,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { try { widgetsBundleService.saveWidgetsBundle(savedWidgetsBundle); } finally { - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } } @@ -116,7 +116,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { try { widgetsBundleService.saveWidgetsBundle(savedWidgetsBundle); } finally { - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } } @@ -126,10 +126,10 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { widgetsBundle.setTenantId(tenantId); widgetsBundle.setTitle("My widgets bundle"); WidgetsBundle savedWidgetsBundle = widgetsBundleService.saveWidgetsBundle(widgetsBundle); - WidgetsBundle foundWidgetsBundle = widgetsBundleService.findWidgetsBundleById(savedWidgetsBundle.getId()); + WidgetsBundle foundWidgetsBundle = widgetsBundleService.findWidgetsBundleById(tenantId, savedWidgetsBundle.getId()); Assert.assertNotNull(foundWidgetsBundle); Assert.assertEquals(savedWidgetsBundle, foundWidgetsBundle); - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } @Test @@ -141,7 +141,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { WidgetsBundle foundWidgetsBundle = widgetsBundleService.findWidgetsBundleByTenantIdAndAlias(tenantId, savedWidgetsBundle.getAlias()); Assert.assertNotNull(foundWidgetsBundle); Assert.assertEquals(savedWidgetsBundle, foundWidgetsBundle); - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); } @Test @@ -150,10 +150,10 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { widgetsBundle.setTenantId(tenantId); widgetsBundle.setTitle("My widgets bundle"); WidgetsBundle savedWidgetsBundle = widgetsBundleService.saveWidgetsBundle(widgetsBundle); - WidgetsBundle foundWidgetsBundle = widgetsBundleService.findWidgetsBundleById(savedWidgetsBundle.getId()); + WidgetsBundle foundWidgetsBundle = widgetsBundleService.findWidgetsBundleById(tenantId, savedWidgetsBundle.getId()); Assert.assertNotNull(foundWidgetsBundle); - widgetsBundleService.deleteWidgetsBundle(savedWidgetsBundle.getId()); - foundWidgetsBundle = widgetsBundleService.findWidgetsBundleById(savedWidgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, savedWidgetsBundle.getId()); + foundWidgetsBundle = widgetsBundleService.findWidgetsBundleById(tenantId, savedWidgetsBundle.getId()); Assert.assertNull(foundWidgetsBundle); } @@ -162,7 +162,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { TenantId tenantId = new TenantId(ModelConstants.NULL_UUID); - List systemWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(); + List systemWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(tenantId); List createdWidgetsBundles = new ArrayList<>(); for (int i=0;i<235;i++) { WidgetsBundle widgetsBundle = new WidgetsBundle(); @@ -178,7 +178,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { TextPageLink pageLink = new TextPageLink(19); TextPageData pageData = null; do { - pageData = widgetsBundleService.findSystemWidgetsBundlesByPageLink(pageLink); + pageData = widgetsBundleService.findSystemWidgetsBundlesByPageLink(tenantId, pageLink); loadedWidgetsBundles.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); @@ -191,10 +191,10 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { Assert.assertEquals(widgetsBundles, loadedWidgetsBundles); for (WidgetsBundle widgetsBundle : createdWidgetsBundles) { - widgetsBundleService.deleteWidgetsBundle(widgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, widgetsBundle.getId()); } - loadedWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(); + loadedWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(tenantId); Collections.sort(systemWidgetsBundles, idComparator); Collections.sort(loadedWidgetsBundles, idComparator); @@ -206,7 +206,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { public void testFindSystemWidgetsBundles() { TenantId tenantId = new TenantId(ModelConstants.NULL_UUID); - List systemWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(); + List systemWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(tenantId); List createdWidgetsBundles = new ArrayList<>(); for (int i=0;i<135;i++) { @@ -219,7 +219,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { List widgetsBundles = new ArrayList<>(createdWidgetsBundles); widgetsBundles.addAll(systemWidgetsBundles); - List loadedWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(); + List loadedWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(tenantId); Collections.sort(widgetsBundles, idComparator); Collections.sort(loadedWidgetsBundles, idComparator); @@ -227,10 +227,10 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { Assert.assertEquals(widgetsBundles, loadedWidgetsBundles); for (WidgetsBundle widgetsBundle : createdWidgetsBundles) { - widgetsBundleService.deleteWidgetsBundle(widgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, widgetsBundle.getId()); } - loadedWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(); + loadedWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(tenantId); Collections.sort(systemWidgetsBundles, idComparator); Collections.sort(loadedWidgetsBundles, idComparator); @@ -283,7 +283,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { @Test public void testFindAllWidgetsBundlesByTenantIdAndPageLink() { - List systemWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(); + List systemWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(tenantId); Tenant tenant = new Tenant(); tenant.setTitle("Test tenant"); @@ -345,7 +345,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { Assert.assertEquals(allSystemWidgetsBundles, loadedWidgetsBundles); for (WidgetsBundle widgetsBundle : createdSystemWidgetsBundles) { - widgetsBundleService.deleteWidgetsBundle(widgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, widgetsBundle.getId()); } loadedWidgetsBundles.clear(); @@ -369,7 +369,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { @Test public void testFindAllWidgetsBundlesByTenantId() { - List systemWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(); + List systemWidgetsBundles = widgetsBundleService.findSystemWidgetsBundles(tenantId); Tenant tenant = new Tenant(); tenant.setTitle("Test tenant"); @@ -414,7 +414,7 @@ public abstract class BaseWidgetsBundleServiceTest extends AbstractServiceTest { Assert.assertEquals(allSystemWidgetsBundles, loadedWidgetsBundles); for (WidgetsBundle widgetsBundle : createdSystemWidgetsBundles) { - widgetsBundleService.deleteWidgetsBundle(widgetsBundle.getId()); + widgetsBundleService.deleteWidgetsBundle(tenantId, widgetsBundle.getId()); } loadedWidgetsBundles = widgetsBundleService.findAllTenantWidgetsBundlesByTenantId(tenantId); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/attributes/BaseAttributesServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/attributes/BaseAttributesServiceTest.java index 113f0d0a2d..68e45a6bf2 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/attributes/BaseAttributesServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/attributes/BaseAttributesServiceTest.java @@ -50,8 +50,8 @@ public abstract class BaseAttributesServiceTest extends AbstractServiceTest { DeviceId deviceId = new DeviceId(UUIDs.timeBased()); KvEntry attrValue = new StringDataEntry("attribute1", "value1"); AttributeKvEntry attr = new BaseAttributeKvEntry(attrValue, 42L); - attributesService.save(deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attr)).get(); - Optional saved = attributesService.find(deviceId, DataConstants.CLIENT_SCOPE, attr.getKey()).get(); + attributesService.save(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attr)).get(); + Optional saved = attributesService.find(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE, attr.getKey()).get(); Assert.assertTrue(saved.isPresent()); Assert.assertEquals(attr, saved.get()); } @@ -62,17 +62,17 @@ public abstract class BaseAttributesServiceTest extends AbstractServiceTest { KvEntry attrOldValue = new StringDataEntry("attribute1", "value1"); AttributeKvEntry attrOld = new BaseAttributeKvEntry(attrOldValue, 42L); - attributesService.save(deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrOld)).get(); - Optional saved = attributesService.find(deviceId, DataConstants.CLIENT_SCOPE, attrOld.getKey()).get(); + attributesService.save(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrOld)).get(); + Optional saved = attributesService.find(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE, attrOld.getKey()).get(); Assert.assertTrue(saved.isPresent()); Assert.assertEquals(attrOld, saved.get()); KvEntry attrNewValue = new StringDataEntry("attribute1", "value2"); AttributeKvEntry attrNew = new BaseAttributeKvEntry(attrNewValue, 73L); - attributesService.save(deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrNew)).get(); + attributesService.save(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrNew)).get(); - saved = attributesService.find(deviceId, DataConstants.CLIENT_SCOPE, attrOld.getKey()).get(); + saved = attributesService.find(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE, attrOld.getKey()).get(); Assert.assertEquals(attrNew, saved.get()); } @@ -87,11 +87,11 @@ public abstract class BaseAttributesServiceTest extends AbstractServiceTest { KvEntry attrBNewValue = new StringDataEntry("B", "value3"); AttributeKvEntry attrBNew = new BaseAttributeKvEntry(attrBNewValue, 73L); - attributesService.save(deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrAOld)).get(); - attributesService.save(deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrANew)).get(); - attributesService.save(deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrBNew)).get(); + attributesService.save(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrAOld)).get(); + attributesService.save(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrANew)).get(); + attributesService.save(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE, Collections.singletonList(attrBNew)).get(); - List saved = attributesService.findAll(deviceId, DataConstants.CLIENT_SCOPE).get(); + List saved = attributesService.findAll(SYSTEM_TENANT_ID, deviceId, DataConstants.CLIENT_SCOPE).get(); Assert.assertNotNull(saved); Assert.assertEquals(2, saved.size()); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java index 81de40ac82..b409dea570 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java @@ -100,7 +100,7 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { } private void testLatestTsAndVerify(EntityId entityId) throws ExecutionException, InterruptedException { - List tsList = tsService.findAllLatest(entityId).get(); + List tsList = tsService.findAllLatest(tenantId, entityId).get(); assertNotNull(tsList); assertEquals(4, tsList.size()); @@ -140,13 +140,13 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { saveEntries(deviceId, TS - 1); saveEntries(deviceId, TS); - List entries = tsService.findLatest(deviceId, Collections.singleton(STRING_KEY)).get(); + List entries = tsService.findLatest(tenantId, deviceId, Collections.singleton(STRING_KEY)).get(); Assert.assertEquals(1, entries.size()); Assert.assertEquals(toTsEntry(TS, stringKvEntry), entries.get(0)); EntityView entityView = saveAndCreateEntityView(deviceId, Arrays.asList(STRING_KEY)); - entries = tsService.findLatest(entityView.getId(), Collections.singleton(STRING_KEY)).get(); + entries = tsService.findLatest(tenantId, entityView.getId(), Collections.singleton(STRING_KEY)).get(); Assert.assertEquals(1, entries.size()); Assert.assertEquals(toTsEntry(TS, stringKvEntry), entries.get(0)); } @@ -160,14 +160,14 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { saveEntries(deviceId, 30000); saveEntries(deviceId, 40000); - tsService.remove(deviceId, Collections.singletonList( + tsService.remove(tenantId, deviceId, Collections.singletonList( new BaseDeleteTsKvQuery(STRING_KEY, 15000, 45000))).get(); - List list = tsService.findAll(deviceId, Collections.singletonList( + List list = tsService.findAll(tenantId, deviceId, Collections.singletonList( new BaseReadTsKvQuery(STRING_KEY, 5000, 45000, 10000, 10, Aggregation.NONE))).get(); Assert.assertEquals(1, list.size()); - List latest = tsService.findLatest(deviceId, Collections.singletonList(STRING_KEY)).get(); + List latest = tsService.findLatest(tenantId, deviceId, Collections.singletonList(STRING_KEY)).get(); Assert.assertEquals(null, latest.get(0).getValueAsString()); } @@ -180,14 +180,14 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { saveEntries(deviceId, 30000); saveEntries(deviceId, 40000); - tsService.remove(deviceId, Collections.singletonList( + tsService.remove(tenantId, deviceId, Collections.singletonList( new BaseDeleteTsKvQuery(STRING_KEY, 25000, 45000, true))).get(); - List list = tsService.findAll(deviceId, Collections.singletonList( + List list = tsService.findAll(tenantId, deviceId, Collections.singletonList( new BaseReadTsKvQuery(STRING_KEY, 5000, 45000, 10000, 10, Aggregation.NONE))).get(); Assert.assertEquals(2, list.size()); - List latest = tsService.findLatest(deviceId, Collections.singletonList(STRING_KEY)).get(); + List latest = tsService.findLatest(tenantId, deviceId, Collections.singletonList(STRING_KEY)).get(); Assert.assertEquals(20000, latest.get(0).getTs()); } @@ -205,7 +205,7 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { entries.add(save(deviceId, 45000, 500)); entries.add(save(deviceId, 55000, 600)); - List list = tsService.findAll(deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, + List list = tsService.findAll(tenantId, deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, 60000, 20000, 3, Aggregation.NONE))).get(); assertEquals(3, list.size()); assertEquals(55000, list.get(0).getTs()); @@ -217,7 +217,7 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { assertEquals(35000, list.get(2).getTs()); assertEquals(java.util.Optional.of(400L), list.get(2).getLongValue()); - list = tsService.findAll(deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, + list = tsService.findAll(tenantId, deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, 60000, 20000, 3, Aggregation.AVG))).get(); assertEquals(3, list.size()); assertEquals(10000, list.get(0).getTs()); @@ -229,7 +229,7 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { assertEquals(50000, list.get(2).getTs()); assertEquals(java.util.Optional.of(550L), list.get(2).getLongValue()); - list = tsService.findAll(deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, + list = tsService.findAll(tenantId, deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, 60000, 20000, 3, Aggregation.SUM))).get(); assertEquals(3, list.size()); @@ -242,7 +242,7 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { assertEquals(50000, list.get(2).getTs()); assertEquals(java.util.Optional.of(1100L), list.get(2).getLongValue()); - list = tsService.findAll(deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, + list = tsService.findAll(tenantId, deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, 60000, 20000, 3, Aggregation.MIN))).get(); assertEquals(3, list.size()); @@ -255,7 +255,7 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { assertEquals(50000, list.get(2).getTs()); assertEquals(java.util.Optional.of(500L), list.get(2).getLongValue()); - list = tsService.findAll(deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, + list = tsService.findAll(tenantId, deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, 60000, 20000, 3, Aggregation.MAX))).get(); assertEquals(3, list.size()); @@ -268,7 +268,7 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { assertEquals(50000, list.get(2).getTs()); assertEquals(java.util.Optional.of(600L), list.get(2).getLongValue()); - list = tsService.findAll(deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, + list = tsService.findAll(tenantId, deviceId, Collections.singletonList(new BaseReadTsKvQuery(LONG_KEY, 0, 60000, 20000, 3, Aggregation.COUNT))).get(); assertEquals(3, list.size()); @@ -284,15 +284,15 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { private TsKvEntry save(DeviceId deviceId, long ts, long value) throws Exception { TsKvEntry entry = new BasicTsKvEntry(ts, new LongDataEntry(LONG_KEY, value)); - tsService.save(deviceId, entry).get(); + tsService.save(tenantId, deviceId, entry).get(); return entry; } private void saveEntries(DeviceId deviceId, long ts) throws ExecutionException, InterruptedException { - tsService.save(deviceId, toTsEntry(ts, stringKvEntry)).get(); - tsService.save(deviceId, toTsEntry(ts, longKvEntry)).get(); - tsService.save(deviceId, toTsEntry(ts, doubleKvEntry)).get(); - tsService.save(deviceId, toTsEntry(ts, booleanKvEntry)).get(); + tsService.save(tenantId, deviceId, toTsEntry(ts, stringKvEntry)).get(); + tsService.save(tenantId, deviceId, toTsEntry(ts, longKvEntry)).get(); + tsService.save(tenantId, deviceId, toTsEntry(ts, doubleKvEntry)).get(); + tsService.save(tenantId, deviceId, toTsEntry(ts, booleanKvEntry)).get(); } private static TsKvEntry toTsEntry(long ts, KvEntry entry) { diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDaoTest.java index b6a73537f7..42623b96eb 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDaoTest.java @@ -53,7 +53,7 @@ public class JpaAlarmDaoTest extends AbstractJpaDaoTest { saveAlarm(alarm1Id, tenantId, originator1Id, "TEST_ALARM"); saveAlarm(alarm2Id, tenantId, originator1Id, "TEST_ALARM"); saveAlarm(alarm3Id, tenantId, originator2Id, "TEST_ALARM"); - assertEquals(3, alarmDao.find().size()); + assertEquals(3, alarmDao.find(new TenantId(tenantId)).size()); ListenableFuture future = alarmDao .findLatestByOriginatorAndType(new TenantId(tenantId), new DeviceId(originator1Id), "TEST_ALARM"); Alarm alarm = future.get(); @@ -71,6 +71,6 @@ public class JpaAlarmDaoTest extends AbstractJpaDaoTest { alarm.setStartTs(System.currentTimeMillis()); alarm.setEndTs(System.currentTimeMillis()); alarm.setStatus(AlarmStatus.ACTIVE_UNACK); - alarmDao.save(alarm); + alarmDao.save(new TenantId(tenantId), alarm); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/asset/JpaAssetDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/asset/JpaAssetDaoTest.java index 8139c3b104..13a485305d 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/asset/JpaAssetDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/asset/JpaAssetDaoTest.java @@ -59,7 +59,7 @@ public class JpaAssetDaoTest extends AbstractJpaDaoTest { UUID customerId = i % 2 == 0 ? customerId1 : customerId2; saveAsset(assetId, tenantId, customerId, "ASSET_" + i, "TYPE_1"); } - assertEquals(60, assetDao.find().size()); + assertEquals(60, assetDao.find(new TenantId(tenantId1)).size()); TextPageLink pageLink1 = new TextPageLink(20, "ASSET_"); List assets1 = assetDao.findAssetsByTenantId(tenantId1, pageLink1); @@ -216,6 +216,6 @@ public class JpaAssetDaoTest extends AbstractJpaDaoTest { asset.setCustomerId(new CustomerId(customerId)); asset.setName(name); asset.setType(type); - assetDao.save(asset); + assetDao.save(new TenantId(tenantId), asset); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/component/JpaBaseComponentDescriptorDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/component/JpaBaseComponentDescriptorDaoTest.java index cdc5515164..eedc8d41ff 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/component/JpaBaseComponentDescriptorDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/component/JpaBaseComponentDescriptorDaoTest.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.plugin.ComponentScope; import org.thingsboard.server.common.data.plugin.ComponentType; import org.thingsboard.server.dao.AbstractJpaDaoTest; import org.thingsboard.server.dao.component.ComponentDescriptorDao; +import org.thingsboard.server.dao.service.AbstractServiceTest; import java.util.List; @@ -46,11 +47,11 @@ public class JpaBaseComponentDescriptorDaoTest extends AbstractJpaDaoTest { } TextPageLink pageLink1 = new TextPageLink(15, "COMPONENT_"); - List components1 = componentDescriptorDao.findByTypeAndPageLink(ComponentType.FILTER, pageLink1); + List components1 = componentDescriptorDao.findByTypeAndPageLink(AbstractServiceTest.SYSTEM_TENANT_ID, ComponentType.FILTER, pageLink1); assertEquals(15, components1.size()); TextPageLink pageLink2 = new TextPageLink(15, "COMPONENT_", components1.get(14).getId().getId(), null); - List components2 = componentDescriptorDao.findByTypeAndPageLink(ComponentType.FILTER, pageLink2); + List components2 = componentDescriptorDao.findByTypeAndPageLink(AbstractServiceTest.SYSTEM_TENANT_ID,ComponentType.FILTER, pageLink2); assertEquals(5, components2.size()); } @@ -63,12 +64,12 @@ public class JpaBaseComponentDescriptorDaoTest extends AbstractJpaDaoTest { } TextPageLink pageLink1 = new TextPageLink(15, "COMPONENT_"); - List components1 = componentDescriptorDao.findByScopeAndTypeAndPageLink( + List components1 = componentDescriptorDao.findByScopeAndTypeAndPageLink(AbstractServiceTest.SYSTEM_TENANT_ID, ComponentScope.SYSTEM, ComponentType.FILTER, pageLink1); assertEquals(15, components1.size()); TextPageLink pageLink2 = new TextPageLink(15, "COMPONENT_", components1.get(14).getId().getId(), null); - List components2 = componentDescriptorDao.findByScopeAndTypeAndPageLink( + List components2 = componentDescriptorDao.findByScopeAndTypeAndPageLink(AbstractServiceTest.SYSTEM_TENANT_ID, ComponentScope.SYSTEM, ComponentType.FILTER, pageLink2); assertEquals(5, components2.size()); } @@ -79,7 +80,7 @@ public class JpaBaseComponentDescriptorDaoTest extends AbstractJpaDaoTest { component.setType(type); component.setScope(scope); component.setName("COMPONENT_" + index); - componentDescriptorDao.save(component); + componentDescriptorDao.save(AbstractServiceTest.SYSTEM_TENANT_ID,component); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/customer/JpaCustomerDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/customer/JpaCustomerDaoTest.java index fd5b70c230..a6c99c6365 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/customer/JpaCustomerDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/customer/JpaCustomerDaoTest.java @@ -77,6 +77,6 @@ public class JpaCustomerDaoTest extends AbstractJpaDaoTest { customer.setId(new CustomerId(UUIDs.timeBased())); customer.setTenantId(new TenantId(tenantId)); customer.setTitle("CUSTOMER_" + index); - customerDao.save(customer); + customerDao.save(new TenantId(tenantId), customer); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/dashboard/JpaDashboardInfoDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/dashboard/JpaDashboardInfoDaoTest.java index 0d48d43c36..1491bdf33b 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/dashboard/JpaDashboardInfoDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/dashboard/JpaDashboardInfoDaoTest.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.AbstractJpaDaoTest; import org.thingsboard.server.dao.dashboard.DashboardInfoDao; +import org.thingsboard.server.dao.service.AbstractServiceTest; import java.util.List; import java.util.UUID; @@ -61,6 +62,6 @@ public class JpaDashboardInfoDaoTest extends AbstractJpaDaoTest { dashboardInfo.setId(new DashboardId(UUIDs.timeBased())); dashboardInfo.setTenantId(new TenantId(tenantId)); dashboardInfo.setTitle("DASHBOARD_" + index); - dashboardInfoDao.save(dashboardInfo); + dashboardInfoDao.save(AbstractServiceTest.SYSTEM_TENANT_ID, dashboardInfo); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceCredentialsDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceCredentialsDaoTest.java index 1ffe2c8ccd..1e19e2fcf5 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceCredentialsDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceCredentialsDaoTest.java @@ -21,11 +21,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.dao.AbstractJpaDaoTest; import org.thingsboard.server.dao.device.DeviceCredentialsDao; +import org.thingsboard.server.dao.service.AbstractServiceTest; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.thingsboard.server.dao.service.AbstractServiceTest.SYSTEM_TENANT_ID; /** * Created by Valerii Sosliuk on 5/6/2017. @@ -39,7 +41,7 @@ public class JpaDeviceCredentialsDaoTest extends AbstractJpaDaoTest { @DatabaseSetup("classpath:dbunit/device_credentials.xml") public void testFindByDeviceId() { UUID deviceId = UUID.fromString("958e3a30-3215-11e7-93ae-92361f002671"); - DeviceCredentials deviceCredentials = deviceCredentialsDao.findByDeviceId(deviceId); + DeviceCredentials deviceCredentials = deviceCredentialsDao.findByDeviceId(SYSTEM_TENANT_ID, deviceId); assertNotNull(deviceCredentials); assertEquals("958e3314-3215-11e7-93ae-92361f002671", deviceCredentials.getId().getId().toString()); assertEquals("ID_1", deviceCredentials.getCredentialsId()); @@ -49,7 +51,7 @@ public class JpaDeviceCredentialsDaoTest extends AbstractJpaDaoTest { @DatabaseSetup("classpath:dbunit/device_credentials.xml") public void findByCredentialsId() { String credentialsId = "ID_2"; - DeviceCredentials deviceCredentials = deviceCredentialsDao.findByCredentialsId(credentialsId); + DeviceCredentials deviceCredentials = deviceCredentialsDao.findByCredentialsId(SYSTEM_TENANT_ID, credentialsId); assertNotNull(deviceCredentials); assertEquals("958e3c74-3215-11e7-93ae-92361f002671", deviceCredentials.getId().getId().toString()); } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java index f0bf47c627..9d95e5170a 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java @@ -68,15 +68,15 @@ public class JpaDeviceDaoTest extends AbstractJpaDaoTest { UUID tenantId = UUIDs.timeBased(); UUID customerId = UUIDs.timeBased(); Device device = getDevice(tenantId, customerId); - deviceDao.save(device); + deviceDao.save(new TenantId(tenantId), device); UUID uuid = device.getId().getId(); - Device entity = deviceDao.findById(uuid); + Device entity = deviceDao.findById(new TenantId(tenantId), uuid); assertNotNull(entity); assertEquals(uuid, entity.getId().getId()); ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); - ListenableFuture future = service.submit(() -> deviceDao.findById(uuid)); + ListenableFuture future = service.submit(() -> deviceDao.findById(new TenantId(tenantId), uuid)); Device asyncDevice = future.get(); assertNotNull("Async device expected to be not null", asyncDevice); } @@ -93,8 +93,8 @@ public class JpaDeviceDaoTest extends AbstractJpaDaoTest { for(int i = 0; i < 5; i++) { UUID deviceId1 = UUIDs.timeBased(); UUID deviceId2 = UUIDs.timeBased(); - deviceDao.save(getDevice(tenantId1, customerId1, deviceId1)); - deviceDao.save(getDevice(tenantId2, customerId2, deviceId2)); + deviceDao.save(new TenantId(tenantId1), getDevice(tenantId1, customerId1, deviceId1)); + deviceDao.save(new TenantId(tenantId2), getDevice(tenantId2, customerId2, deviceId2)); deviceIds.add(deviceId1); deviceIds.add(deviceId2); } @@ -116,8 +116,8 @@ public class JpaDeviceDaoTest extends AbstractJpaDaoTest { for(int i = 0; i < 20; i++) { UUID deviceId1 = UUIDs.timeBased(); UUID deviceId2 = UUIDs.timeBased(); - deviceDao.save(getDevice(tenantId1, customerId1, deviceId1)); - deviceDao.save(getDevice(tenantId2, customerId2, deviceId2)); + deviceDao.save(new TenantId(tenantId1), getDevice(tenantId1, customerId1, deviceId1)); + deviceDao.save(new TenantId(tenantId2), getDevice(tenantId2, customerId2, deviceId2)); deviceIds.add(deviceId1); deviceIds.add(deviceId2); } @@ -129,8 +129,8 @@ public class JpaDeviceDaoTest extends AbstractJpaDaoTest { private void createDevices(UUID tenantId1, UUID tenantId2, UUID customerId1, UUID customerId2, int count) { for (int i = 0; i < count / 2; i++) { - deviceDao.save(getDevice(tenantId1, customerId1)); - deviceDao.save(getDevice(tenantId2, customerId2)); + deviceDao.save(new TenantId(tenantId1), getDevice(tenantId1, customerId1)); + deviceDao.save(new TenantId(tenantId2), getDevice(tenantId2, customerId2)); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/event/JpaBaseEventDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/event/JpaBaseEventDaoTest.java index 84ae307c05..4b94fd2113 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/event/JpaBaseEventDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/event/JpaBaseEventDaoTest.java @@ -30,6 +30,7 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.dao.AbstractJpaDaoTest; import org.thingsboard.server.dao.event.EventDao; +import org.thingsboard.server.dao.service.AbstractServiceTest; import java.io.IOException; import java.util.List; @@ -74,7 +75,7 @@ public class JpaBaseEventDaoTest extends AbstractJpaDaoTest { String eventType = STATS; String eventUid = "be41c7a3-31f5-11e7-9cfd-2786e6aa2046"; Event event = eventDao.findEvent(tenantId, new DeviceId(entityId), eventType, eventUid); - eventDao.find().stream().forEach(System.out::println); + eventDao.find(AbstractServiceTest.SYSTEM_TENANT_ID).stream().forEach(System.out::println); assertNotNull("Event expected to be not null", event); assertEquals("be41c7a2-31f5-11e7-9cfd-2786e6aa2046", event.getId().getId().toString()); } @@ -145,10 +146,10 @@ public class JpaBaseEventDaoTest extends AbstractJpaDaoTest { String type = i % 2 == 0 ? STATS : ALARM; UUID eventId1 = UUIDs.timeBased(); Event event1 = getEvent(eventId1, tenantId, entityId1, type); - eventDao.save(event1); + eventDao.save(new TenantId(tenantId), event1); UUID eventId2 = UUIDs.timeBased(); Event event2 = getEvent(eventId2, tenantId, entityId2, type); - eventDao.save(event2); + eventDao.save(new TenantId(tenantId), event2); } return System.currentTimeMillis(); } @@ -157,10 +158,10 @@ public class JpaBaseEventDaoTest extends AbstractJpaDaoTest { for (int i = 0; i < count / 2; i++) { UUID eventId1 = UUIDs.timeBased(); Event event1 = getEvent(eventId1, tenantId, entityId1); - eventDao.save(event1); + eventDao.save(new TenantId(tenantId), event1); UUID eventId2 = UUIDs.timeBased(); Event event2 = getEvent(eventId2, tenantId, entityId2); - eventDao.save(event2); + eventDao.save(new TenantId(tenantId), event2); } return System.currentTimeMillis(); } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/tenant/JpaTenantDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/tenant/JpaTenantDaoTest.java index bf36711100..36aff36092 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/tenant/JpaTenantDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/tenant/JpaTenantDaoTest.java @@ -23,6 +23,7 @@ import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.dao.AbstractJpaDaoTest; +import org.thingsboard.server.dao.service.AbstractServiceTest; import org.thingsboard.server.dao.tenant.TenantDao; import java.util.List; @@ -41,13 +42,13 @@ public class JpaTenantDaoTest extends AbstractJpaDaoTest { @DatabaseSetup("classpath:dbunit/empty_dataset.xml") public void testFindTenantsByRegion() { createTenants(); - assertEquals(60, tenantDao.find().size()); - List tenants1 = tenantDao.findTenantsByRegion("REGION_1", new TextPageLink(20,"title")); + assertEquals(60, tenantDao.find(AbstractServiceTest.SYSTEM_TENANT_ID).size()); + List tenants1 = tenantDao.findTenantsByRegion(AbstractServiceTest.SYSTEM_TENANT_ID, "REGION_1", new TextPageLink(20,"title")); assertEquals(20, tenants1.size()); - List tenants2 = tenantDao.findTenantsByRegion("REGION_1", + List tenants2 = tenantDao.findTenantsByRegion(AbstractServiceTest.SYSTEM_TENANT_ID,"REGION_1", new TextPageLink(20,"title", tenants1.get(19).getId().getId(), null)); assertEquals(10, tenants2.size()); - List tenants3 = tenantDao.findTenantsByRegion("REGION_1", + List tenants3 = tenantDao.findTenantsByRegion(AbstractServiceTest.SYSTEM_TENANT_ID,"REGION_1", new TextPageLink(20,"title", tenants2.get(9).getId().getId(), null)); assertEquals(0, tenants3.size()); } @@ -64,7 +65,7 @@ public class JpaTenantDaoTest extends AbstractJpaDaoTest { tenant.setId(new TenantId(UUIDs.timeBased())); tenant.setRegion(region); tenant.setTitle(title + "_" + index); - tenantDao.save(tenant); + tenantDao.save(AbstractServiceTest.SYSTEM_TENANT_ID, tenant); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserCredentialsDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserCredentialsDaoTest.java index 29e0471168..e89a6854ff 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserCredentialsDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserCredentialsDaoTest.java @@ -27,6 +27,7 @@ import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.thingsboard.server.dao.service.AbstractServiceTest.SYSTEM_TENANT_ID; /** * Created by Valerii Sosliuk on 4/22/2017. @@ -39,14 +40,14 @@ public class JpaUserCredentialsDaoTest extends AbstractJpaDaoTest { @Test @DatabaseSetup("classpath:dbunit/user_credentials.xml") public void testFindAll() { - List userCredentials = userCredentialsDao.find(); + List userCredentials = userCredentialsDao.find(SYSTEM_TENANT_ID); assertEquals(2, userCredentials.size()); } @Test @DatabaseSetup("classpath:dbunit/user_credentials.xml") public void testFindByUserId() { - UserCredentials userCredentials = userCredentialsDao.findByUserId(UUID.fromString("787827e6-27d7-11e7-93ae-92361f002671")); + UserCredentials userCredentials = userCredentialsDao.findByUserId(SYSTEM_TENANT_ID, UUID.fromString("787827e6-27d7-11e7-93ae-92361f002671")); assertNotNull(userCredentials); assertEquals("4b9e010c-27d5-11e7-93ae-92361f002671", userCredentials.getId().toString()); assertEquals(true, userCredentials.isEnabled()); @@ -58,7 +59,7 @@ public class JpaUserCredentialsDaoTest extends AbstractJpaDaoTest { @Test @DatabaseSetup("classpath:dbunit/user_credentials.xml") public void testFindByActivateToken() { - UserCredentials userCredentials = userCredentialsDao.findByActivateToken("ACTIVATE_TOKEN_1"); + UserCredentials userCredentials = userCredentialsDao.findByActivateToken(SYSTEM_TENANT_ID, "ACTIVATE_TOKEN_1"); assertNotNull(userCredentials); assertEquals("3ed10af0-27d5-11e7-93ae-92361f002671", userCredentials.getId().toString()); } @@ -66,7 +67,7 @@ public class JpaUserCredentialsDaoTest extends AbstractJpaDaoTest { @Test @DatabaseSetup("classpath:dbunit/user_credentials.xml") public void testFindByResetToken() { - UserCredentials userCredentials = userCredentialsDao.findByResetToken("RESET_TOKEN_2"); + UserCredentials userCredentials = userCredentialsDao.findByResetToken(SYSTEM_TENANT_ID, "RESET_TOKEN_2"); assertNotNull(userCredentials); assertEquals("4b9e010c-27d5-11e7-93ae-92361f002671", userCredentials.getId().toString()); } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserDaoTest.java index bacd73d13e..422cf18c10 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/user/JpaUserDaoTest.java @@ -28,6 +28,7 @@ import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.dao.AbstractJpaDaoTest; +import org.thingsboard.server.dao.service.AbstractServiceTest; import org.thingsboard.server.dao.user.UserDao; import java.io.IOException; @@ -49,14 +50,14 @@ public class JpaUserDaoTest extends AbstractJpaDaoTest { @Test @DatabaseSetup("classpath:dbunit/user.xml") public void testFindAll() { - List users = userDao.find(); + List users = userDao.find(AbstractServiceTest.SYSTEM_TENANT_ID); assertEquals(users.size(), 5); } @Test @DatabaseSetup("classpath:dbunit/user.xml") public void testFindByEmail() { - User user = userDao.findByEmail("sysadm@thingsboard.org"); + User user = userDao.findByEmail(AbstractServiceTest.SYSTEM_TENANT_ID,"sysadm@thingsboard.org"); assertNotNull("User is expected to be not null", user); assertEquals("9cb58ba0-27c1-11e7-93ae-92361f002671", user.getId().toString()); assertEquals("c97ea14e-27c1-11e7-93ae-92361f002671", user.getTenantId().toString()); @@ -112,9 +113,9 @@ public class JpaUserDaoTest extends AbstractJpaDaoTest { String additionalInfo = "{\"key\":\"value-100\"}"; JsonNode jsonNode = mapper.readTree(additionalInfo); user.setAdditionalInfo(jsonNode); - userDao.save(user); - assertEquals(6, userDao.find().size()); - User savedUser = userDao.findByEmail("user@thingsboard.org"); + userDao.save(AbstractServiceTest.SYSTEM_TENANT_ID,user); + assertEquals(6, userDao.find(AbstractServiceTest.SYSTEM_TENANT_ID).size()); + User savedUser = userDao.findByEmail(AbstractServiceTest.SYSTEM_TENANT_ID,"user@thingsboard.org"); assertNotNull(savedUser); assertEquals(additionalInfo, savedUser.getAdditionalInfo().toString()); } @@ -142,6 +143,6 @@ public class JpaUserDaoTest extends AbstractJpaDaoTest { String idString = id.toString(); String email = idString.substring(0, idString.indexOf('-')) + "@thingsboard.org"; user.setEmail(email); - userDao.save(user); + userDao.save(AbstractServiceTest.SYSTEM_TENANT_ID,user); } } diff --git a/dao/src/test/java/org/thingsboard/server/dao/sql/widget/JpaWidgetsBundleDaoTest.java b/dao/src/test/java/org/thingsboard/server/dao/sql/widget/JpaWidgetsBundleDaoTest.java index 12487a81a3..6e7052a690 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/sql/widget/JpaWidgetsBundleDaoTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/sql/widget/JpaWidgetsBundleDaoTest.java @@ -26,6 +26,7 @@ import org.thingsboard.server.common.data.id.WidgetsBundleId; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.widget.WidgetsBundle; import org.thingsboard.server.dao.AbstractJpaDaoTest; +import org.thingsboard.server.dao.service.AbstractServiceTest; import org.thingsboard.server.dao.widget.WidgetsBundleDao; import java.util.List; @@ -46,7 +47,7 @@ public class JpaWidgetsBundleDaoTest extends AbstractJpaDaoTest { @DatabaseSetup(value = "classpath:dbunit/widgets_bundle.xml",type= DatabaseOperation.CLEAN_INSERT) @DatabaseTearDown(value = "classpath:dbunit/widgets_bundle.xml", type= DatabaseOperation.DELETE_ALL) public void testFindAll() { - assertEquals(7, widgetsBundleDao.find().size()); + assertEquals(7, widgetsBundleDao.find(AbstractServiceTest.SYSTEM_TENANT_ID).size()); } @Test @@ -62,14 +63,14 @@ public class JpaWidgetsBundleDaoTest extends AbstractJpaDaoTest { @DatabaseSetup(value = "classpath:dbunit/widgets_bundle.xml", type= DatabaseOperation.DELETE_ALL) public void testFindSystemWidgetsBundles() { createSystemWidgetBundles(30, "WB_"); - assertEquals(30, widgetsBundleDao.find().size()); + assertEquals(30, widgetsBundleDao.find(AbstractServiceTest.SYSTEM_TENANT_ID).size()); // Get first page TextPageLink textPageLink1 = new TextPageLink(10, "WB"); - List widgetsBundles1 = widgetsBundleDao.findSystemWidgetsBundles(textPageLink1); + List widgetsBundles1 = widgetsBundleDao.findSystemWidgetsBundles(AbstractServiceTest.SYSTEM_TENANT_ID, textPageLink1); assertEquals(10, widgetsBundles1.size()); // Get next page TextPageLink textPageLink2 = new TextPageLink(10, "WB", widgetsBundles1.get(9).getId().getId(), null); - List widgetsBundles2 = widgetsBundleDao.findSystemWidgetsBundles(textPageLink2); + List widgetsBundles2 = widgetsBundleDao.findSystemWidgetsBundles(AbstractServiceTest.SYSTEM_TENANT_ID, textPageLink2); assertEquals(10, widgetsBundles2.size()); } @@ -84,7 +85,7 @@ public class JpaWidgetsBundleDaoTest extends AbstractJpaDaoTest { createWidgetBundles(5, tenantId2, "WB2_"); createSystemWidgetBundles(10, "WB_SYS_"); } - assertEquals(180, widgetsBundleDao.find().size()); + assertEquals(180, widgetsBundleDao.find(AbstractServiceTest.SYSTEM_TENANT_ID).size()); TextPageLink textPageLink1 = new TextPageLink(40, "WB"); List widgetsBundles1 = widgetsBundleDao.findTenantWidgetsBundlesByTenantId(tenantId1, textPageLink1); @@ -153,7 +154,7 @@ public class JpaWidgetsBundleDaoTest extends AbstractJpaDaoTest { widgetsBundle.setTitle(prefix + i); widgetsBundle.setId(new WidgetsBundleId(UUIDs.timeBased())); widgetsBundle.setTenantId(new TenantId(tenantId)); - widgetsBundleDao.save(widgetsBundle); + widgetsBundleDao.save(AbstractServiceTest.SYSTEM_TENANT_ID, widgetsBundle); } } private void createSystemWidgetBundles(int count, String prefix) { @@ -163,7 +164,7 @@ public class JpaWidgetsBundleDaoTest extends AbstractJpaDaoTest { widgetsBundle.setTitle(prefix + i); widgetsBundle.setTenantId(new TenantId(NULL_UUID)); widgetsBundle.setId(new WidgetsBundleId(UUIDs.timeBased())); - widgetsBundleDao.save(widgetsBundle); + widgetsBundleDao.save(AbstractServiceTest.SYSTEM_TENANT_ID, widgetsBundle); } } } diff --git a/dao/src/test/resources/cassandra-test.properties b/dao/src/test/resources/cassandra-test.properties index cf07b22e42..7b00b165b6 100644 --- a/dao/src/test/resources/cassandra-test.properties +++ b/dao/src/test/resources/cassandra-test.properties @@ -53,4 +53,6 @@ cassandra.query.buffer_size=100000 cassandra.query.concurrent_limit=1000 cassandra.query.permit_max_wait_time=20000 cassandra.query.rate_limit_print_interval_ms=30000 +cassandra.query.tenant_rate_limits.enabled=true +cassandra.query.tenant_rate_limits.configuration=5000:1,100000:60