@Override public Response getRecordById(String keyspaceName, String tableName, String identifier) { long startTime = System.currentTimeMillis(); ProjectLogger.log("Cassandra Service getRecordById method started at ==" + startTime, LoggerEnum.PERF_LOG); Response response = new Response(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); Where selectWhere = selectQuery.where(); Clause clause = QueryBuilder.eq(Constants.IDENTIFIER, identifier); selectWhere.and(clause); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException(ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log("Cassandra Service getRecordById method end at ==" + stopTime + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return response; }
@Override public Response getRecordsByProperty(String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList) { long startTime = System.currentTimeMillis(); ProjectLogger.log("Cassandra Service getRecordsByProperty method started at ==" + startTime, LoggerEnum.PERF_LOG); Response response = new Response(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); Where selectWhere = selectQuery.where(); Clause clause = QueryBuilder.in(propertyName, propertyValueList); selectWhere.and(clause); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException(ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log("Cassandra Service getRecordsByProperty method end at ==" + stopTime + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return response; }
@Override public Response deleteRecord(String keyspaceName, String tableName, String identifier) { long startTime = System.currentTimeMillis(); ProjectLogger.log("Cassandra Service deleteRecord method started at ==" + startTime, LoggerEnum.PERF_LOG); Response response = new Response(); try { Delete.Where delete = QueryBuilder.delete().from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException(ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log("Cassandra Service deleteRecord method end at ==" + stopTime + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return response; }
public boolean findIndexRow(String table, String rowKey, byte[] key, Object indValue) { Select selectQuery = QueryBuilder.select().all().from(keys, table).allowFiltering(); Where selectWhere = selectQuery.where(); Clause rkClause = QueryBuilder.eq("id", rowKey); selectWhere.and(rkClause); Clause indClause = null; if (indValue != null) { indClause = QueryBuilder.eq("colname", indValue); } else { if (table.equalsIgnoreCase("IntegerIndice")) { indClause = QueryBuilder.eq("colname", ByteBuffer.wrap(new byte[0])); } else { indClause = QueryBuilder.eq("colname", ""); } } selectWhere.and(indClause); Clause keyClause = QueryBuilder.eq("colvalue", ByteBuffer.wrap(key)); selectWhere.and(keyClause); Query query = selectWhere.limit(1); ResultSet resultSet = session.execute(query); return !resultSet.isExhausted(); }
public static Where createRowQueryFromValues(List<byte[]> values, DboColumnMeta colMeta, Select selectQuery, String rowKey) { Where selectWhere = selectQuery.where(); Clause rkClause = QueryBuilder.eq("id", rowKey); selectWhere.and(rkClause); Object[] valStrings = new Object[values.size()]; int count = 0; for (byte[] value : values) { valStrings[count] = StandardConverters.convertFromBytes(String.class, value); count++; } Clause inClause = QueryBuilder.in("colname", valStrings); selectWhere.and(inClause); return selectWhere; }
@Override public Response getRecordsByProperty(String keyspaceName, String tableName, String propertyName, Object propertyValue) { long startTime = System.currentTimeMillis(); ProjectLogger.log("Cassandra Service getRecordsByProperty method started at ==" + startTime, LoggerEnum.PERF_LOG); Response response = new Response(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); Where selectWhere = selectQuery.where(); Clause clause = QueryBuilder.eq(propertyName, propertyValue); selectWhere.and(clause); ResultSet results = null; Session session = connectionManager.getSession(keyspaceName); results = session.execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException(ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log("Cassandra Service getRecordsByProperty method end at ==" + stopTime + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return response; }
@Override public DeviceCredentials findByDeviceId(UUID deviceId) { log.debug("Try to find device credentials by deviceId [{}] ", deviceId); Where query = select().from(ModelConstants.DEVICE_CREDENTIALS_BY_DEVICE_COLUMN_FAMILY_NAME) .where(eq(ModelConstants.DEVICE_CREDENTIALS_DEVICE_ID_PROPERTY, deviceId)); log.trace("Execute query {}", query); DeviceCredentialsEntity deviceCredentialsEntity = findOneByStatement(query); log.trace("Found device credentials [{}] by deviceId [{}]", deviceCredentialsEntity, deviceId); return DaoUtil.getData(deviceCredentialsEntity); }
@Override public DeviceCredentials findByCredentialsId(String credentialsId) { log.debug("Try to find device credentials by credentialsId [{}] ", credentialsId); Where query = select().from(ModelConstants.DEVICE_CREDENTIALS_BY_CREDENTIALS_ID_COLUMN_FAMILY_NAME) .where(eq(ModelConstants.DEVICE_CREDENTIALS_CREDENTIALS_ID_PROPERTY, credentialsId)); log.trace("Execute query {}", query); DeviceCredentialsEntity deviceCredentialsEntity = findOneByStatement(query); log.trace("Found device credentials [{}] by credentialsId [{}]", deviceCredentialsEntity, credentialsId); return DaoUtil.getData(deviceCredentialsEntity); }
@Override public User findByEmail(String email) { log.debug("Try to find user by email [{}] ", email); Where query = select().from(ModelConstants.USER_BY_EMAIL_COLUMN_FAMILY_NAME).where(eq(ModelConstants.USER_EMAIL_PROPERTY, email)); log.trace("Execute query {}", query); UserEntity userEntity = findOneByStatement(query); log.trace("Found user [{}] by email [{}]", userEntity, email); return DaoUtil.getData(userEntity); }
@Override public UserCredentials findByUserId(UUID userId) { log.debug("Try to find user credentials by userId [{}] ", userId); Where query = select().from(ModelConstants.USER_CREDENTIALS_BY_USER_COLUMN_FAMILY_NAME).where(eq(ModelConstants.USER_CREDENTIALS_USER_ID_PROPERTY, userId)); log.trace("Execute query {}", query); UserCredentialsEntity userCredentialsEntity = findOneByStatement(query); log.trace("Found user credentials [{}] by userId [{}]", userCredentialsEntity, userId); return DaoUtil.getData(userCredentialsEntity); }
@Override public UserCredentials findByActivateToken(String activateToken) { log.debug("Try to find user credentials by activateToken [{}] ", activateToken); Where query = select().from(ModelConstants.USER_CREDENTIALS_BY_ACTIVATE_TOKEN_COLUMN_FAMILY_NAME) .where(eq(ModelConstants.USER_CREDENTIALS_ACTIVATE_TOKEN_PROPERTY, activateToken)); log.trace("Execute query {}", query); UserCredentialsEntity userCredentialsEntity = findOneByStatement(query); log.trace("Found user credentials [{}] by activateToken [{}]", userCredentialsEntity, activateToken); return DaoUtil.getData(userCredentialsEntity); }
@Override public UserCredentials findByResetToken(String resetToken) { log.debug("Try to find user credentials by resetToken [{}] ", resetToken); Where query = select().from(ModelConstants.USER_CREDENTIALS_BY_RESET_TOKEN_COLUMN_FAMILY_NAME) .where(eq(ModelConstants.USER_CREDENTIALS_RESET_TOKEN_PROPERTY, resetToken)); log.trace("Execute query {}", query); UserCredentialsEntity userCredentialsEntity = findOneByStatement(query); log.trace("Found user credentials [{}] by resetToken [{}]", userCredentialsEntity, resetToken); return DaoUtil.getData(userCredentialsEntity); }
@Override public AdminSettings findByKey(String key) { log.debug("Try to find admin settings by key [{}] ", key); Where query = select().from(ADMIN_SETTINGS_BY_KEY_COLUMN_FAMILY_NAME).where(eq(ADMIN_SETTINGS_KEY_PROPERTY, key)); log.trace("Execute query {}", query); AdminSettingsEntity adminSettingsEntity = findOneByStatement(query); log.trace("Found admin settings [{}] by key [{}]", adminSettingsEntity, key); return DaoUtil.getData(adminSettingsEntity); }
@Override public List<WidgetType> findWidgetTypesByTenantIdAndBundleAlias(UUID tenantId, String bundleAlias) { log.debug("Try to find widget types by tenantId [{}] and bundleAlias [{}]", tenantId, bundleAlias); Where query = select().from(WIDGET_TYPE_BY_TENANT_AND_ALIASES_COLUMN_FAMILY_NAME) .where() .and(eq(WIDGET_TYPE_TENANT_ID_PROPERTY, tenantId)) .and(eq(WIDGET_TYPE_BUNDLE_ALIAS_PROPERTY, bundleAlias)); List<WidgetTypeEntity> widgetTypesEntities = findListByStatement(query); log.trace("Found widget types [{}] by tenantId [{}] and bundleAlias [{}]", widgetTypesEntities, tenantId, bundleAlias); return DaoUtil.convertDataList(widgetTypesEntities); }
@Override public WidgetType findByTenantIdBundleAliasAndAlias(UUID tenantId, String bundleAlias, String alias) { log.debug("Try to find widget type by tenantId [{}], bundleAlias [{}] and alias [{}]", tenantId, bundleAlias, alias); Where query = select().from(WIDGET_TYPE_BY_TENANT_AND_ALIASES_COLUMN_FAMILY_NAME) .where() .and(eq(WIDGET_TYPE_TENANT_ID_PROPERTY, tenantId)) .and(eq(WIDGET_TYPE_BUNDLE_ALIAS_PROPERTY, bundleAlias)) .and(eq(WIDGET_TYPE_ALIAS_PROPERTY, alias)); log.trace("Execute query {}", query); WidgetTypeEntity widgetTypeEntity = findOneByStatement(query); log.trace("Found widget type [{}] by tenantId [{}], bundleAlias [{}] and alias [{}]", widgetTypeEntity, tenantId, bundleAlias, alias); return DaoUtil.getData(widgetTypeEntity); }
@Override public AssetCredentials findByAssetId(UUID assetId) { log.debug("Try to find asset credentials by assetId [{}] ", assetId); Where query = select().from(ModelConstants.ASSET_CREDENTIALS_BY_ASSET_COLUMN_FAMILY_NAME) .where(eq(ModelConstants.ASSET_CREDENTIALS_ASSET_ID_PROPERTY, assetId)); log.trace("Execute query {}", query); AssetCredentialsEntity assetCredentialsEntity = findOneByStatement(query); log.trace("Found asset credentials [{}] by assetId [{}]", assetCredentialsEntity, assetId); return DaoUtil.getData(assetCredentialsEntity); }
@Override public AssetCredentials findByCredentialsId(String credentialsId) { log.debug("Try to find asset credentials by credentialsId [{}] ", credentialsId); Where query = select().from(ModelConstants.ASSET_CREDENTIALS_BY_CREDENTIALS_ID_COLUMN_FAMILY_NAME) .where(eq(ModelConstants.ASSET_CREDENTIALS_CREDENTIALS_ID_PROPERTY, credentialsId)); log.trace("Execute query {}", query); AssetCredentialsEntity assetCredentialsEntity = findOneByStatement(query); log.trace("Found asset credentials [{}] by credentialsId [{}]", assetCredentialsEntity, credentialsId); return DaoUtil.getData(assetCredentialsEntity); }
@Override public UserCredentials findByUserId(UUID userId) { log.debug("Try to find user credentials by userId [{}] ", userId); Where query = select().from(ModelConstants.USER_CREDENTIALS_BY_USER_COLUMN_FAMILY_NAME).where(eq(ModelConstants.USER_CREDENTIALS_USER_ID_PROPERTY, userId)); log.trace(EXECUTE_QUERY, query); UserCredentialsEntity userCredentialsEntity = findOneByStatement(query); log.trace("Found user credentials [{}] by userId [{}]", userCredentialsEntity, userId); return DaoUtil.getData(userCredentialsEntity); }
@Override public UserCredentials findByActivateToken(String activateToken) { log.debug("Try to find user credentials by activateToken [{}] ", activateToken); Where query = select().from(ModelConstants.USER_CREDENTIALS_BY_ACTIVATE_TOKEN_COLUMN_FAMILY_NAME) .where(eq(ModelConstants.USER_CREDENTIALS_ACTIVATE_TOKEN_PROPERTY, activateToken)); log.trace(EXECUTE_QUERY, query); UserCredentialsEntity userCredentialsEntity = findOneByStatement(query); log.trace("Found user credentials [{}] by activateToken [{}]", userCredentialsEntity, activateToken); return DaoUtil.getData(userCredentialsEntity); }
@Override public UserCredentials findByResetToken(String resetToken) { log.debug("Try to find user credentials by resetToken [{}] ", resetToken); Where query = select().from(ModelConstants.USER_CREDENTIALS_BY_RESET_TOKEN_COLUMN_FAMILY_NAME) .where(eq(ModelConstants.USER_CREDENTIALS_RESET_TOKEN_PROPERTY, resetToken)); log.trace(EXECUTE_QUERY, query); UserCredentialsEntity userCredentialsEntity = findOneByStatement(query); log.trace("Found user credentials [{}] by resetToken [{}]", userCredentialsEntity, resetToken); return DaoUtil.getData(userCredentialsEntity); }
private void loadCache(boolean reverse) { if (cachedRows != null && cachedRows.hasNext()) return; // There are more rows so return and the code will return // the next result from cache ResultSet resultSet = null; if (needToGetBatch) { if (batchListener != null) batchListener.beforeFetchingNextBatch(); String rowKeyString = StandardConverters.convertFromBytes(String.class, rowKey); Select selectQuery = QueryBuilder.select().all().from(keySpace, indTable).allowFiltering(); Where whereClause = Cql3Util.createRowQuery(from, to, columnMeta, selectQuery, rowKeyString, indTable); Query query = null; if (batchSize != null) query = whereClause.limit(batchSize); else query = whereClause.disableTracing(); resultSet = session.execute(query); // Need to see where we use this batchListener if (batchListener != null && batchSize != null) batchListener.afterFetchingNextBatch(batchSize); List<com.datastax.driver.core.Row> finalRes = new ArrayList<com.datastax.driver.core.Row>(); fillinCache(finalRes, resultSet); needToGetBatch = false; if (reverse) { while (cachedRows.hasNext()) cachedRows.next(); } } }
@Override public List<Future<ResultSet>> start() { List<Future<ResultSet>> futures = new ArrayList<Future<ResultSet>>(); String rowKeyString = StandardConverters.convertFromBytes(String.class, rowKey); for (byte[] val : values) { Select selectQuery = QueryBuilder.select().all().from(keySpace, indTable).allowFiltering(); Where selectWhere = selectQuery.where(); Clause rkClause = QueryBuilder.eq("id", rowKeyString); selectWhere.and(rkClause); Object value = null; value = columnMeta.getStorageType().convertFromNoSql(val); value = Cql3Util.checkForBooleanAndNull(value, indTable, columnMeta); Clause valClause = QueryBuilder.eq("colname", value); selectWhere.and(valClause); Query query = selectWhere.disableTracing(); Future future = session.executeAsync(query); futures.add(future); } return futures; }
public static Where createRowQuery(Key from, Key to, DboColumnMeta colMeta, Select selectQuery, String rowKey, String indTable) { Where selectWhere = selectQuery.where(); Clause rkClause = QueryBuilder.eq("id", rowKey); selectWhere.and(rkClause); Object valFrom = null, valTo = null; if (colMeta != null) { if (from != null) { valFrom = colMeta.getStorageType().convertFromNoSql(from.getKey()); valFrom = checkForBooleanAndNull(valFrom, indTable, colMeta); } if (to != null) { valTo = colMeta.getStorageType().convertFromNoSql(to.getKey()); valTo = checkForBooleanAndNull(valTo, indTable, colMeta); } } else return selectWhere; if (from != null) { if (from.isInclusive()) { Clause gteClause = QueryBuilder.gte("colname", valFrom); selectWhere.and(gteClause); } else { Clause gtClause = QueryBuilder.gt("colname", valFrom); selectWhere.and(gtClause); } } if (to != null) { if (to.isInclusive()) { Clause lteClause = QueryBuilder.lte("colname", valTo); selectWhere.and(lteClause); } else { Clause ltClause = QueryBuilder.lt("colname", valTo); selectWhere.and(ltClause); } } return selectWhere; }
@Override public CassandraEndpointUser findByExternalIdAndTenantId(String externalId, String tenantId) { LOG.debug("Try to find endpoint user by external id {} and tenant id {}", externalId, tenantId); Where where = select().from(getColumnFamilyName()) .where(eq(EP_USER_EXTERNAL_ID_PROPERTY, externalId)) .and(eq(EP_USER_TENANT_ID_PROPERTY, tenantId)); LOG.trace("Try to find endpoint user by cql select {}", where); CassandraEndpointUser endpointUser = findOneByStatement(where); LOG.trace("Found {} endpoint user", endpointUser); return endpointUser; }
@Override public String generateAccessToken(String externalId, String tenantId) { LOG.debug("Generating access token for endpoint user with external id {} and tenant id {}", externalId, tenantId); String accessToken = UUID.randomUUID().toString(); Update.Where query = update(getColumnFamilyName()) .with(set(CassandraModelConstants.EP_USER_ACCESS_TOKEN_PROPERTY, accessToken)) .where(eq(EP_USER_EXTERNAL_ID_PROPERTY, externalId)) .and(eq(EP_USER_TENANT_ID_PROPERTY, tenantId)); execute(query); LOG.trace("Generated access token {} for endpoint user by query {}", accessToken, query); return accessToken; }
@Override public CassandraNotification findById(String id) { LOG.debug("Try to find notification by id {}", id); CassandraNotification nf = new CassandraNotification(id); Where query = select().from(getColumnFamilyName()) .where(eq(NF_TOPIC_ID_PROPERTY, nf.getTopicId())) .and(eq(NF_NOTIFICATION_TYPE_PROPERTY, nf.getType().name())) .and(eq(NF_VERSION_PROPERTY, nf.getNfVersion())) .and(eq(NF_SEQ_NUM_PROPERTY, nf.getSeqNum())); LOG.trace("Execute query {}", query); nf = findOneByStatement(query); LOG.trace("Found notification {} by id {}", nf, id); return nf; }
@Override public void removeById(String id) { LOG.debug("Remove notification by id {}", id); CassandraNotification nf = new CassandraNotification(id); Delete.Where deleteQuery = delete().from(getColumnFamilyName()) .where(eq(NF_TOPIC_ID_PROPERTY, nf.getTopicId())) .and(eq(NF_NOTIFICATION_TYPE_PROPERTY, nf.getType().name())) .and(eq(NF_VERSION_PROPERTY, nf.getNfVersion())) .and(eq(NF_SEQ_NUM_PROPERTY, nf.getSeqNum())); LOG.trace("Remove notification by id {}", deleteQuery); execute(deleteQuery); }
@Override public List<CassandraNotification> findNotificationsByTopicId(String topicId) { LOG.debug("Try to find notifications by topic id {}", topicId); Where query = select().from(getColumnFamilyName()).where(eq(NF_TOPIC_ID_PROPERTY, topicId)) .and(QueryBuilder.in( NF_NOTIFICATION_TYPE_PROPERTY, getStringTypes(NotificationTypeDto.values()))); LOG.trace("Execute query {}", query); List<CassandraNotification> notifications = findListByStatement(query); if (LOG.isTraceEnabled()) { LOG.trace("Found notifications {}", Arrays.toString(notifications.toArray())); } return notifications; }
@Override public void removeNotificationsByTopicId(String topicId) { LOG.debug("Remove notifications by topic id {}", topicId); Delete.Where query = delete().from(getColumnFamilyName()) .where(eq(NF_TOPIC_ID_PROPERTY, topicId)) .and(QueryBuilder.in( NF_NOTIFICATION_TYPE_PROPERTY, getStringTypes(NotificationTypeDto.values()))); execute(query); LOG.trace("Execute query {}", query); }
@Override public List<CassandraNotification> findNotificationsByTopicIdAndVersionAndStartSecNum( String topicId, int seqNum, int sysNfVersion, int userNfVersion) { LOG.debug("Try to find notifications by topic id {} start sequence number {} " + "system schema version {} user schema version {}", topicId, seqNum, sysNfVersion, userNfVersion); List<CassandraNotification> resultList = new ArrayList<>(); Where systemQuery = select().from(getColumnFamilyName()) .where(eq(NF_TOPIC_ID_PROPERTY, topicId)) .and(eq(NF_NOTIFICATION_TYPE_PROPERTY, NotificationTypeDto.SYSTEM.name())) .and(eq(NF_VERSION_PROPERTY, sysNfVersion)) .and(QueryBuilder.gt(NF_SEQ_NUM_PROPERTY, seqNum)); Where userQuery = select().from(getColumnFamilyName()) .where(eq(NF_TOPIC_ID_PROPERTY, topicId)) .and(eq(NF_NOTIFICATION_TYPE_PROPERTY, NotificationTypeDto.USER.name())) .and(eq(NF_VERSION_PROPERTY, userNfVersion)) .and(QueryBuilder.gt(NF_SEQ_NUM_PROPERTY, seqNum)); List<CassandraNotification> systemList = findListByStatement(systemQuery); List<CassandraNotification> userList = findListByStatement(userQuery); resultList.addAll(systemList); resultList.addAll(userList); if (LOG.isTraceEnabled()) { LOG.trace("Found notifications {} by topic id {}, seqNum {}, sysVer {}, userVer {} ", Arrays.toString( resultList.toArray()), topicId, seqNum, sysNfVersion, userNfVersion); } return resultList; }
public static Where buildQuery(String searchView, List<Clause> clauses, TimePageLink pageLink, String idColumn) { return buildQuery(searchView, clauses, Collections.emptyList(), pageLink, idColumn); }
public static Where buildQuery(String searchView, List<Clause> clauses, Ordering order, TimePageLink pageLink, String idColumn) { return buildQuery(searchView, clauses, Collections.singletonList(order), pageLink, idColumn); }