public static void main(String[] args) { Session session = Connection.connect(); PreparedStatement preparedStatement = session.prepare("insert into user (id, name, age) values (?, ?, ?)"); try { BoundStatement boundStatement = preparedStatement.bind(UUIDs.timeBased(), "Hector", 34); ResultSet rs = session.execute(boundStatement); System.out.println(rs); } catch (Exception ex) { ex.printStackTrace(); } Connection.close(); }
public static void main(String[] args) { Session session = Connection.connect(); BatchStatement batchStatement = new BatchStatement(); PreparedStatement preparedStatement = session.prepare("insert into user (id, name) values (?, ?)"); int i = 0; while(i < 10) { batchStatement.add(preparedStatement.bind(UUIDs.timeBased(), "user-" + i)); ++i; } try { ResultSet rs = session.execute(batchStatement); System.out.println(rs); } catch (Exception ex) { ex.printStackTrace(); } Connection.close(); }
@Override public Alarm toData() { Alarm alarm = new Alarm(new AlarmId(id)); alarm.setCreatedTime(UUIDs.unixTimestamp(id)); if (tenantId != null) { alarm.setTenantId(new TenantId(tenantId)); } alarm.setOriginator(EntityIdFactory.getByTypeAndUuid(originatorType, originatorId)); alarm.setType(type); alarm.setSeverity(severity); alarm.setStatus(status); alarm.setPropagate(propagate); alarm.setStartTs(startTs); alarm.setEndTs(endTs); alarm.setAckTs(ackTs); alarm.setClearTs(clearTs); alarm.setDetails(details); return alarm; }
@Override public WidgetsBundle toData() { WidgetsBundle widgetsBundle = new WidgetsBundle(new WidgetsBundleId(id)); widgetsBundle.setCreatedTime(UUIDs.unixTimestamp(id)); if (tenantId != null) { widgetsBundle.setTenantId(new TenantId(tenantId)); } widgetsBundle.setAlias(alias); widgetsBundle.setTitle(title); if (image != null) { byte[] imageByteArray = new byte[image.remaining()]; image.get(imageByteArray); widgetsBundle.setImage(imageByteArray); } return widgetsBundle; }
@Override public Customer toData() { Customer customer = new Customer(new CustomerId(id)); customer.setCreatedTime(UUIDs.unixTimestamp(id)); customer.setTenantId(new TenantId(tenantId)); customer.setTitle(title); customer.setCountry(country); customer.setState(state); customer.setCity(city); customer.setAddress(address); customer.setAddress2(address2); customer.setZip(zip); customer.setPhone(phone); customer.setEmail(email); customer.setAdditionalInfo(additionalInfo); return customer; }
@Override public User toData() { User user = new User(new UserId(id)); user.setCreatedTime(UUIDs.unixTimestamp(id)); user.setAuthority(authority); if (tenantId != null) { user.setTenantId(new TenantId(tenantId)); } if (customerId != null) { user.setCustomerId(new CustomerId(customerId)); } user.setEmail(email); user.setFirstName(firstName); user.setLastName(lastName); user.setAdditionalInfo(additionalInfo); return user; }
@Override public Tenant toData() { Tenant tenant = new Tenant(new TenantId(id)); tenant.setCreatedTime(UUIDs.unixTimestamp(id)); tenant.setTitle(title); tenant.setRegion(region); tenant.setCountry(country); tenant.setState(state); tenant.setCity(city); tenant.setAddress(address); tenant.setAddress2(address2); tenant.setZip(zip); tenant.setPhone(phone); tenant.setEmail(email); tenant.setAdditionalInfo(additionalInfo); return tenant; }
@Override public Alarm toData() { Alarm alarm = new Alarm(new AlarmId(UUIDConverter.fromString(id))); alarm.setCreatedTime(UUIDs.unixTimestamp(UUIDConverter.fromString(id))); if (tenantId != null) { alarm.setTenantId(new TenantId(UUIDConverter.fromString(tenantId))); } alarm.setOriginator(EntityIdFactory.getByTypeAndUuid(originatorType, UUIDConverter.fromString(originatorId))); alarm.setType(type); alarm.setSeverity(severity); alarm.setStatus(status); alarm.setPropagate(propagate); alarm.setStartTs(startTs); alarm.setEndTs(endTs); alarm.setAckTs(ackTs); alarm.setClearTs(clearTs); alarm.setDetails(details); return alarm; }
@Override public Customer toData() { Customer customer = new Customer(new CustomerId(getId())); customer.setCreatedTime(UUIDs.unixTimestamp(getId())); customer.setTenantId(new TenantId(UUIDConverter.fromString(tenantId))); customer.setTitle(title); customer.setCountry(country); customer.setState(state); customer.setCity(city); customer.setAddress(address); customer.setAddress2(address2); customer.setZip(zip); customer.setPhone(phone); customer.setEmail(email); customer.setAdditionalInfo(additionalInfo); return customer; }
@Override public User toData() { User user = new User(new UserId(getId())); user.setCreatedTime(UUIDs.unixTimestamp(getId())); user.setAuthority(authority); if (tenantId != null) { user.setTenantId(new TenantId(UUIDConverter.fromString(tenantId))); } if (customerId != null) { user.setCustomerId(new CustomerId(UUIDConverter.fromString(customerId))); } user.setEmail(email); user.setFirstName(firstName); user.setLastName(lastName); user.setAdditionalInfo(additionalInfo); return user; }
@Override public Tenant toData() { Tenant tenant = new Tenant(new TenantId(getId())); tenant.setCreatedTime(UUIDs.unixTimestamp(getId())); tenant.setTitle(title); tenant.setRegion(region); tenant.setCountry(country); tenant.setState(state); tenant.setCity(city); tenant.setAddress(address); tenant.setAddress2(address2); tenant.setZip(zip); tenant.setPhone(phone); tenant.setEmail(email); tenant.setAdditionalInfo(additionalInfo); return tenant; }
private Optional<Event> save(EventEntity entity, boolean ifNotExists) { if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } Insert insert = QueryBuilder.insertInto(getColumnFamilyName()) .value(ModelConstants.ID_PROPERTY, entity.getId()) .value(ModelConstants.EVENT_TENANT_ID_PROPERTY, entity.getTenantId()) .value(ModelConstants.EVENT_ENTITY_TYPE_PROPERTY, entity.getEntityType()) .value(ModelConstants.EVENT_ENTITY_ID_PROPERTY, entity.getEntityId()) .value(ModelConstants.EVENT_TYPE_PROPERTY, entity.getEventType()) .value(ModelConstants.EVENT_UID_PROPERTY, entity.getEventUid()) .value(ModelConstants.EVENT_BODY_PROPERTY, entity.getBody()); if (ifNotExists) { insert = insert.ifNotExists(); } ResultSet rs = executeWrite(insert); if (rs.wasApplied()) { return Optional.of(DaoUtil.getData(entity)); } else { return Optional.empty(); } }
@Override @Transactional public D save(D domain) { E entity; try { entity = getEntityClass().getConstructor(domain.getClass()).newInstance(domain); } catch (Exception e) { log.error("Can't create entity for domain object {}", domain, e); throw new IllegalArgumentException("Can't create entity for domain object {" + domain + "}", e); } setSearchText(entity); log.debug("Saving entity {}", entity); if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } entity = getCrudRepository().save(entity); return DaoUtil.getData(entity); }
public Optional<Event> save(EventEntity entity, boolean ifNotExists) { log.debug("Save event [{}] ", entity); if (entity.getTenantId() == null) { log.trace("Save system event with predefined id {}", systemTenantId); entity.setTenantId(UUIDConverter.fromTimeUUID(systemTenantId)); } if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } if (StringUtils.isEmpty(entity.getEventUid())) { entity.setEventUid(entity.getId().toString()); } if (ifNotExists && eventRepository.findByTenantIdAndEntityTypeAndEntityId(entity.getTenantId(), entity.getEntityType(), entity.getEntityId()) != null) { return Optional.empty(); } return Optional.of(DaoUtil.getData(eventRepository.save(entity))); }
private Optional<ComponentDescriptor> saveIfNotExist(ComponentDescriptorEntity entity) { if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } ResultSet rs = executeRead(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()) .value(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, entity.getType()) .value(ModelConstants.COMPONENT_DESCRIPTOR_SCOPE_PROPERTY, entity.getScope()) .value(ModelConstants.COMPONENT_DESCRIPTOR_CONFIGURATION_DESCRIPTOR_PROPERTY, entity.getConfigurationDescriptor()) .value(ModelConstants.COMPONENT_DESCRIPTOR_ACTIONS_PROPERTY, entity.getActions()) .value(ModelConstants.SEARCH_TEXT_PROPERTY, entity.getSearchText()) .ifNotExists() ); if (rs.wasApplied()) { return Optional.of(DaoUtil.getData(entity)); } else { return Optional.empty(); } }
@Test public void testFindAssetsByTenantIdCustomerIdAndIdsAsync() throws ExecutionException, InterruptedException { UUID tenantId = UUIDs.timeBased(); UUID customerId1 = UUIDs.timeBased(); UUID customerId2 = UUIDs.timeBased(); List<UUID> searchIds = new ArrayList<>(); for (int i = 0; i < 30; i++) { UUID assetId = UUIDs.timeBased(); UUID customerId = i%2 == 0 ? customerId1 : customerId2; saveAsset(assetId, tenantId, customerId, "ASSET_" + i, "TYPE_1"); if (i % 3 == 0) { searchIds.add(assetId); } } ListenableFuture<List<Asset>> assetsFuture = assetDao .findAssetsByTenantIdAndCustomerIdAndIdsAsync(tenantId, customerId1, searchIds); List<Asset> assets = assetsFuture.get(); assertNotNull(assets); assertEquals(5, assets.size()); }
@Test public void testFindAssetsByTenantIdAndIdsAsync() throws ExecutionException, InterruptedException { UUID tenantId = UUIDs.timeBased(); UUID customerId = UUIDs.timeBased(); List<UUID> searchIds = new ArrayList<>(); for (int i = 0; i < 30; i++) { UUID assetId = UUIDs.timeBased(); saveAsset(assetId, tenantId, customerId, "ASSET_" + i, "TYPE_1"); if (i % 3 == 0) { searchIds.add(assetId); } } ListenableFuture<List<Asset>> assetsFuture = assetDao .findAssetsByTenantIdAndIdsAsync(tenantId, searchIds); List<Asset> assets = assetsFuture.get(); assertNotNull(assets); assertEquals(10, assets.size()); }
@Test public void testSaveNonExistentDeviceCredentials() throws Exception { Device device = new Device(); device.setName("My device"); device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); DeviceCredentials deviceCredentials = doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); DeviceCredentials newDeviceCredentials = new DeviceCredentials(new DeviceCredentialsId(UUIDs.timeBased())); newDeviceCredentials.setCreatedTime(deviceCredentials.getCreatedTime()); newDeviceCredentials.setDeviceId(deviceCredentials.getDeviceId()); newDeviceCredentials.setCredentialsType(deviceCredentials.getCredentialsType()); newDeviceCredentials.setCredentialsId(deviceCredentials.getCredentialsId()); doPost("/api/device/credentials", newDeviceCredentials) .andExpect(status().isBadRequest()) .andExpect(statusReason(containsString("Unable to update non-existent device credentials"))); }
@Test public void testFindDashboardsByTenantId() { UUID tenantId1 = UUIDs.timeBased(); UUID customerId1 = UUIDs.timeBased(); UUID tenantId2 = UUIDs.timeBased(); UUID customerId2 = UUIDs.timeBased(); for (int i = 0; i < 20; i++) { createDashboard(tenantId1, customerId1, i); createDashboard(tenantId2, customerId2, i * 2); } TextPageLink pageLink1 = new TextPageLink(15, "DASHBOARD"); List<DashboardInfo> dashboardInfos1 = dashboardInfoDao.findDashboardsByTenantId(tenantId1, pageLink1); assertEquals(15, dashboardInfos1.size()); TextPageLink pageLink2 = new TextPageLink(15, "DASHBOARD", dashboardInfos1.get(14).getId().getId(), null); List<DashboardInfo> dashboardInfos2 = dashboardInfoDao.findDashboardsByTenantId(tenantId1, pageLink2); assertEquals(5, dashboardInfos2.size()); }
private Map<String, Object> generate5TimeUUIDs() throws InterruptedException { Map<String, Object> params = new HashMap<>(); UUID commentId1 = UUIDs.timeBased(); Thread.sleep(1); UUID commentId2 = UUIDs.timeBased(); Thread.sleep(1); UUID commentId3 = UUIDs.timeBased(); Thread.sleep(1); UUID commentId4 = UUIDs.timeBased(); Thread.sleep(1); UUID commentId5 = UUIDs.timeBased(); params.put("commentId1", commentId1); params.put("commentId2", commentId2); params.put("commentId3", commentId3); params.put("commentId4", commentId4); params.put("commentId5", commentId5); return params; }
@Test public void testInsert() throws InterruptedException { Book book = new Book(); book.setIsbn(UUIDs.timeBased()); book.setTitle("Spring Integration Cassandra"); book.setAuthor("Cassandra Guru"); book.setPages(521); book.setSaleDate(new Date()); book.setInStock(true); this.sink.input().send(new GenericMessage<>(book)); final Select select = QueryBuilder.select().all().from("book"); assertEqualsEventually(1, new Supplier<Integer>() { @Override public Integer get() { return cassandraTemplate.select(select, Book.class).size(); } }); this.cassandraTemplate.delete(book); }
private void saveUser(UUID tenantId, UUID customerId) { User user = new User(); UUID id = UUIDs.timeBased(); user.setId(new UserId(id)); user.setTenantId(new TenantId(tenantId)); user.setCustomerId(new CustomerId(customerId)); if (customerId == NULL_UUID) { user.setAuthority(Authority.TENANT_ADMIN); } else { user.setAuthority(Authority.CUSTOMER_USER); } String idString = id.toString(); String email = idString.substring(0, idString.indexOf('-')) + "@thingsboard.org"; user.setEmail(email); userDao.save(user); }
@Test public void testFindDashboardsByTenantAndCustomerId() { UUID tenantId1 = UUIDs.timeBased(); UUID customerId1 = UUIDs.timeBased(); UUID tenantId2 = UUIDs.timeBased(); UUID customerId2 = UUIDs.timeBased(); for (int i = 0; i < 20; i++) { createDashboard(tenantId1, customerId1, i); createDashboard(tenantId2, customerId2, i * 2); } TextPageLink pageLink1 = new TextPageLink(15, "DASHBOARD"); List<DashboardInfo> dashboardInfos1 = dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(tenantId1, customerId1, pageLink1); assertEquals(15, dashboardInfos1.size()); TextPageLink pageLink2 = new TextPageLink(15, "DASHBOARD", dashboardInfos1.get(14).getId().getId(), null); List<DashboardInfo> dashboardInfos2 = dashboardInfoDao.findDashboardsByTenantIdAndCustomerId(tenantId1, customerId1, pageLink2); assertEquals(5, dashboardInfos2.size()); }
@Test @DatabaseSetup(value = "classpath:dbunit/widgets_bundle.xml", type= DatabaseOperation.DELETE_ALL) public void testFindWidgetsBundlesByTenantId() { UUID tenantId1 = UUIDs.timeBased(); UUID tenantId2 = UUIDs.timeBased(); // Create a bunch of widgetBundles for (int i= 0; i < 10; i++) { createWidgetBundles(3, tenantId1, "WB1_"); createWidgetBundles(5, tenantId2, "WB2_"); createSystemWidgetBundles(10, "WB_SYS_"); } assertEquals(180, widgetsBundleDao.find().size()); TextPageLink textPageLink1 = new TextPageLink(40, "WB"); List<WidgetsBundle> widgetsBundles1 = widgetsBundleDao.findTenantWidgetsBundlesByTenantId(tenantId1, textPageLink1); assertEquals(30, widgetsBundles1.size()); TextPageLink textPageLink2 = new TextPageLink(40, "WB"); List<WidgetsBundle> widgetsBundles2 = widgetsBundleDao.findTenantWidgetsBundlesByTenantId(tenantId2, textPageLink2); assertEquals(40, widgetsBundles2.size()); TextPageLink textPageLink3 = new TextPageLink(40, "WB", widgetsBundles2.get(39).getId().getId(), null); List<WidgetsBundle> widgetsBundles3 = widgetsBundleDao.findTenantWidgetsBundlesByTenantId(tenantId2, textPageLink3); assertEquals(10, widgetsBundles3.size()); }
@Test public void testFindDevicesByTenantIdAndIdsAsync() throws ExecutionException, InterruptedException { UUID tenantId1 = UUIDs.timeBased(); UUID customerId1 = UUIDs.timeBased(); UUID tenantId2 = UUIDs.timeBased(); UUID customerId2 = UUIDs.timeBased(); List<UUID> deviceIds = new ArrayList<>(); 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)); deviceIds.add(deviceId1); deviceIds.add(deviceId2); } ListenableFuture<List<Device>> devicesFuture = deviceDao.findDevicesByTenantIdAndIdsAsync(tenantId1, deviceIds); List<Device> devices = devicesFuture.get(); assertEquals(5, devices.size()); }
@Test public void testFindDevicesByTenantIdAndCustomerIdAndIdsAsync() throws ExecutionException, InterruptedException { UUID tenantId1 = UUIDs.timeBased(); UUID customerId1 = UUIDs.timeBased(); UUID tenantId2 = UUIDs.timeBased(); UUID customerId2 = UUIDs.timeBased(); List<UUID> deviceIds = new ArrayList<>(); 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)); deviceIds.add(deviceId1); deviceIds.add(deviceId2); } ListenableFuture<List<Device>> devicesFuture = deviceDao.findDevicesByTenantIdCustomerIdAndIdsAsync(tenantId1, customerId1, deviceIds); List<Device> devices = devicesFuture.get(); assertEquals(20, devices.size()); }
@Test public void testDeleteEntityRelations() throws ExecutionException, InterruptedException { AssetId parentId = new AssetId(UUIDs.timeBased()); AssetId childId = new AssetId(UUIDs.timeBased()); AssetId subChildId = new AssetId(UUIDs.timeBased()); EntityRelation relationA = new EntityRelation(parentId, childId, EntityRelation.CONTAINS_TYPE); EntityRelation relationB = new EntityRelation(childId, subChildId, EntityRelation.CONTAINS_TYPE); saveRelation(relationA); saveRelation(relationB); Assert.assertTrue(relationService.deleteEntityRelationsAsync(childId).get()); Assert.assertFalse(relationService.checkRelation(parentId, childId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); Assert.assertFalse(relationService.checkRelation(childId, subChildId, EntityRelation.CONTAINS_TYPE, RelationTypeGroup.COMMON).get()); }
@Test public void testRecursiveRelation() throws ExecutionException, InterruptedException { // A -> B -> [C,D] AssetId assetA = new AssetId(UUIDs.timeBased()); AssetId assetB = new AssetId(UUIDs.timeBased()); AssetId assetC = new AssetId(UUIDs.timeBased()); DeviceId deviceD = new DeviceId(UUIDs.timeBased()); EntityRelation relationAB = new EntityRelation(assetA, assetB, EntityRelation.CONTAINS_TYPE); EntityRelation relationBC = new EntityRelation(assetB, assetC, EntityRelation.CONTAINS_TYPE); EntityRelation relationBD = new EntityRelation(assetB, deviceD, EntityRelation.CONTAINS_TYPE); saveRelation(relationAB); saveRelation(relationBC); saveRelation(relationBD); 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<EntityRelation> relations = relationService.findByQuery(query).get(); Assert.assertEquals(2, relations.size()); Assert.assertTrue(relations.contains(relationAB)); Assert.assertTrue(relations.contains(relationBC)); }
@Test public void testFindAssetsByTenantIdAndName() { UUID assetId1 = UUIDs.timeBased(); UUID assetId2 = UUIDs.timeBased(); UUID tenantId1 = UUIDs.timeBased(); UUID tenantId2 = UUIDs.timeBased(); UUID customerId1 = UUIDs.timeBased(); UUID customerId2 = UUIDs.timeBased(); String name = "TEST_ASSET"; saveAsset(assetId1, tenantId1, customerId1, name, "TYPE_1"); saveAsset(assetId2, tenantId2, customerId2, name, "TYPE_1"); Optional<Asset> assetOpt1 = assetDao.findAssetsByTenantIdAndName(tenantId2, name); assertTrue("Optional expected to be non-empty", assetOpt1.isPresent()); assertEquals(assetId2, assetOpt1.get().getId().getId()); Optional<Asset> assetOpt2 = assetDao.findAssetsByTenantIdAndName(tenantId2, "NON_EXISTENT_NAME"); assertFalse("Optional expected to be empty", assetOpt2.isPresent()); }
protected PluginMetaData generatePlugin(TenantId tenantId, String token, String clazz, String actions, String configurationDescriptorResource, String dataResource) throws IOException { if (tenantId == null) { tenantId = new TenantId(UUIDs.timeBased()); } if (token == null) { token = UUID.randomUUID().toString(); } getOrCreateDescriptor(ComponentScope.TENANT, ComponentType.PLUGIN, clazz, configurationDescriptorResource, actions); PluginMetaData pluginMetaData = new PluginMetaData(); pluginMetaData.setName("Testing"); pluginMetaData.setClazz(clazz); pluginMetaData.setTenantId(tenantId); pluginMetaData.setApiToken(token); pluginMetaData.setAdditionalInfo(mapper.readTree("{\"test\":\"test\"}")); try { pluginMetaData.setConfiguration(readFromResource(dataResource)); } catch (IOException e) { throw new RuntimeException(e); } return pluginMetaData; }
@Test public void testFindAsync() throws ExecutionException, InterruptedException { UUID tenantId = UUIDs.timeBased(); UUID customerId = UUIDs.timeBased(); Device device = getDevice(tenantId, customerId); deviceDao.save(device); UUID uuid = device.getId().getId(); Device entity = deviceDao.findById(uuid); assertNotNull(entity); assertEquals(uuid, entity.getId().getId()); ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); ListenableFuture<Device> future = service.submit(() -> deviceDao.findById(uuid)); Device asyncDevice = future.get(); assertNotNull("Async device expected to be not null", asyncDevice); }