Java Code Examples for com.datastax.driver.core.querybuilder.Select

The following are top voted examples for showing how to use com.datastax.driver.core.querybuilder.Select. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: sunbird-utils   File: CassandraOperationImpl.java   Source Code and License 15 votes vote down vote up
@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;
}
 
Example 2
Project: sunbird-utils   File: CassandraOperationImpl.java   Source Code and License 8 votes vote down vote up
@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;
}
 
Example 3
Project: eventapis   File: CassandraViewQuery.java   Source Code and License 7 votes vote down vote up
@Override
public List<E> queryByOpId(String opId) throws EventStoreException {
    Select select = QueryBuilder.select(CassandraEventRecorder.ENTITY_ID).from(tableName);
    select.where(QueryBuilder.eq(CassandraEventRecorder.OP_ID, opId));
    List<Row> entityEventDatas = cassandraSession.execute(select, PagingIterable::all);

    Map<String, E> resultList = new HashMap<>();
    for (Row entityEvent : entityEventDatas) {
        String entityId = entityEvent.getString(CassandraEventRecorder.ENTITY_ID);
        if (!resultList.containsKey(entityId)) {
            E value = queryEntity(entityId);
            if (value != null)
                resultList.put(entityId, value);
        }
    }
    return new ArrayList<>(resultList.values());
}
 
Example 4
Project: sunbird-utils   File: CassandraOperationImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Response getAllRecords(String keyspaceName, String tableName) {
  long startTime = System.currentTimeMillis();
  ProjectLogger.log("Cassandra Service getAllRecords method started at ==" + startTime,
      LoggerEnum.PERF_LOG);
  Response response = new Response();
  try {
    Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName);
    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 getAllRecords method end at ==" + stopTime
      + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG);
  return response;
}
 
Example 5
Project: iotplatform   File: CassandraDeviceTypeDao.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<List<DeviceType>> findDeviceTypesByTenantIdCustomerIdAndIdsAsync(UUID tenantId, UUID customerId, List<UUID> deviceIds) {
    log.debug("Try to find devices by tenantId [{}], customerId [{}] and device Ids [{}]", tenantId, customerId, deviceIds);
    Select select = select().from(getColumnFamilyName());
    Select.Where query = select.where();
    query.and(eq(DEVICE_TYPE_TENANT_ID_PROPERTY, tenantId));
    query.and(eq(DEVICE_TYPE_CUSTOMER_ID_PROPERTY, customerId));
    query.and(in(ID_PROPERTY, deviceIds));
    return findListByStatementAsync(query);
}
 
Example 6
Project: iotplatform   File: BaseRelationDao.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<List<EntityRelation>> findRelations(EntityId from, String relationType, RelationTypeGroup typeGroup, ThingType 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()),
                    eq(ModelConstants.RELATION_TYPE_GROUP_PROPERTY, typeGroup.name()),
                    eq(ModelConstants.RELATION_TYPE_PROPERTY, relationType),
                    eq(ModelConstants.RELATION_TO_TYPE_PROPERTY, childType.name())),
            Arrays.asList(
                    pageLink.isAscOrder() ? QueryBuilder.desc(ModelConstants.RELATION_TYPE_GROUP_PROPERTY) :
                            QueryBuilder.asc(ModelConstants.RELATION_TYPE_GROUP_PROPERTY),
                    pageLink.isAscOrder() ? QueryBuilder.desc(ModelConstants.RELATION_TYPE_PROPERTY) :
                            QueryBuilder.asc(ModelConstants.RELATION_TYPE_PROPERTY),
                    pageLink.isAscOrder() ? QueryBuilder.desc(ModelConstants.RELATION_TO_TYPE_PROPERTY) :
                            QueryBuilder.asc(ModelConstants.RELATION_TO_TYPE_PROPERTY)
            ),
            pageLink, ModelConstants.RELATION_TO_ID_PROPERTY);
    return getFuture(executeAsyncRead(query), this::getEntityRelations);
}
 
Example 7
Project: iotplatform   File: CassandraBaseEventDao.java   Source Code and License 6 votes vote down vote up
@Override
public Event findEvent(UUID tenantId, EntityId entityId, String eventType, String eventUid) {
    log.debug("Search event entity by [{}][{}][{}][{}]", tenantId, entityId, eventType, eventUid);
    Select.Where query = select().from(getColumnFamilyName()).where(
            eq(ModelConstants.EVENT_TENANT_ID_PROPERTY, tenantId))
            .and(eq(ModelConstants.EVENT_ENTITY_TYPE_PROPERTY, entityId.getEntityType()))
            .and(eq(ModelConstants.EVENT_ENTITY_ID_PROPERTY, entityId.getId()))
            .and(eq(ModelConstants.EVENT_TYPE_PROPERTY, eventType))
            .and(eq(ModelConstants.EVENT_UID_PROPERTY, eventUid));
    log.trace("Execute query [{}]", query);
    EventEntity entity = findOneByStatement(query);
    if (log.isTraceEnabled()) {
        log.trace("Search result: [{}] for event entity [{}]", entity != null, entity);
    } else {
        log.debug("Search result: [{}]", entity != null);
    }
    return DaoUtil.getData(entity);
}
 
Example 8
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: CassandraHealthIndicator.java   Source Code and License 6 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	try {
		Select select = QueryBuilder.select("release_version").from("system",
				"local");
		ResultSet results = this.cassandraOperations.query(select);
		if (results.isExhausted()) {
			builder.up();
			return;
		}
		String version = results.one().getString(0);
		builder.up().withDetail("version", version);
	}
	catch (Exception ex) {
		builder.down(ex);
	}
}
 
Example 9
Project: cassandra   File: CassandraSinkIntegrationTests.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 10
Project: cassandra   File: CassandraSinkIntegrationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testIngestQuery() throws Exception {
	List<Book> books = getBookList(5);

	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
	Jackson2JsonObjectMapper mapper = new Jackson2JsonObjectMapper(objectMapper);

	this.sink.input().send(new GenericMessage<>(mapper.toJson(books)));

	final Select select = QueryBuilder.select().all().from("book");

	assertEqualsEventually(5, new Supplier<Integer>() {

		@Override
		public Integer get() {
			return cassandraTemplate.select(select, Book.class).size();
		}

	});

	this.cassandraTemplate.truncate("book");
}
 
Example 11
Project: cassandra   File: CassandraSinkIntegrationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testIngestQuery() throws Exception {
	List<Book> books = getBookList(5);

	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
	Jackson2JsonObjectMapper mapper = new Jackson2JsonObjectMapper(objectMapper);

	this.sink.input().send(new GenericMessage<>(mapper.toJson(books)));

	final Select select = QueryBuilder.select().all().from("book");

	assertEqualsEventually(5, new Supplier<Integer>() {

		@Override
		public Integer get() {
			return cassandraTemplate.select(select, Book.class).size();
		}

	});

	this.cassandraTemplate.truncate("book");
}
 
Example 12
Project: thingsboard   File: BaseRelationDao.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<List<EntityRelation>> findRelations(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()),
                    eq(ModelConstants.RELATION_TYPE_GROUP_PROPERTY, typeGroup.name()),
                    eq(ModelConstants.RELATION_TYPE_PROPERTY, relationType),
                    eq(ModelConstants.RELATION_TO_TYPE_PROPERTY, childType.name())),
            Arrays.asList(
                    pageLink.isAscOrder() ? QueryBuilder.desc(ModelConstants.RELATION_TYPE_GROUP_PROPERTY) :
                            QueryBuilder.asc(ModelConstants.RELATION_TYPE_GROUP_PROPERTY),
                    pageLink.isAscOrder() ? QueryBuilder.desc(ModelConstants.RELATION_TYPE_PROPERTY) :
                            QueryBuilder.asc(ModelConstants.RELATION_TYPE_PROPERTY),
                    pageLink.isAscOrder() ? QueryBuilder.desc(ModelConstants.RELATION_TO_TYPE_PROPERTY) :
                            QueryBuilder.asc(ModelConstants.RELATION_TO_TYPE_PROPERTY)
            ),
            pageLink, ModelConstants.RELATION_TO_ID_PROPERTY);
    return getFuture(executeAsyncRead(query), this::getEntityRelations);
}
 
Example 13
Project: thingsboard   File: CassandraDeviceDao.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<List<EntitySubtype>> findTenantDeviceTypesAsync(UUID tenantId) {
    Select select = select().from(ENTITY_SUBTYPE_COLUMN_FAMILY_NAME);
    Select.Where query = select.where();
    query.and(eq(ENTITY_SUBTYPE_TENANT_ID_PROPERTY, tenantId));
    query.and(eq(ENTITY_SUBTYPE_ENTITY_TYPE_PROPERTY, EntityType.DEVICE));
    query.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel());
    ResultSetFuture resultSetFuture = getSession().executeAsync(query);
    return Futures.transform(resultSetFuture, new Function<ResultSet, List<EntitySubtype>>() {
        @Nullable
        @Override
        public List<EntitySubtype> apply(@Nullable ResultSet resultSet) {
            Result<EntitySubtypeEntity> result = cluster.getMapper(EntitySubtypeEntity.class).map(resultSet);
            if (result != null) {
                List<EntitySubtype> entitySubtypes = new ArrayList<>();
                result.all().forEach((entitySubtypeEntity) ->
                    entitySubtypes.add(entitySubtypeEntity.toEntitySubtype())
                );
                return entitySubtypes;
            } else {
                return Collections.emptyList();
            }
        }
    });
}
 
Example 14
Project: thingsboard   File: CassandraBaseEventDao.java   Source Code and License 6 votes vote down vote up
@Override
public Event findEvent(UUID tenantId, EntityId entityId, String eventType, String eventUid) {
    log.debug("Search event entity by [{}][{}][{}][{}]", tenantId, entityId, eventType, eventUid);
    Select.Where query = select().from(getColumnFamilyName()).where(
            eq(ModelConstants.EVENT_TENANT_ID_PROPERTY, tenantId))
            .and(eq(ModelConstants.EVENT_ENTITY_TYPE_PROPERTY, entityId.getEntityType()))
            .and(eq(ModelConstants.EVENT_ENTITY_ID_PROPERTY, entityId.getId()))
            .and(eq(ModelConstants.EVENT_TYPE_PROPERTY, eventType))
            .and(eq(ModelConstants.EVENT_UID_PROPERTY, eventUid));
    log.trace("Execute query [{}]", query);
    EventEntity entity = findOneByStatement(query);
    if (log.isTraceEnabled()) {
        log.trace("Search result: [{}] for event entity [{}]", entity != null, entity);
    } else {
        log.debug("Search result: [{}]", entity != null);
    }
    return DaoUtil.getData(entity);
}
 
Example 15
Project: thingsboard   File: CassandraAssetDao.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<List<EntitySubtype>> findTenantAssetTypesAsync(UUID tenantId) {
    Select select = select().from(ENTITY_SUBTYPE_COLUMN_FAMILY_NAME);
    Select.Where query = select.where();
    query.and(eq(ENTITY_SUBTYPE_TENANT_ID_PROPERTY, tenantId));
    query.and(eq(ENTITY_SUBTYPE_ENTITY_TYPE_PROPERTY, EntityType.ASSET));
    query.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel());
    ResultSetFuture resultSetFuture = getSession().executeAsync(query);
    return Futures.transform(resultSetFuture, new Function<ResultSet, List<EntitySubtype>>() {
        @Nullable
        @Override
        public List<EntitySubtype> apply(@Nullable ResultSet resultSet) {
            Result<EntitySubtypeEntity> result = cluster.getMapper(EntitySubtypeEntity.class).map(resultSet);
            if (result != null) {
                List<EntitySubtype> entitySubtypes = new ArrayList<>();
                result.all().forEach((entitySubtypeEntity) ->
                        entitySubtypes.add(entitySubtypeEntity.toEntitySubtype())
                );
                return entitySubtypes;
            } else {
                return Collections.emptyList();
            }
        }
    });
}
 
Example 16
Project: spring-boot-concourse   File: CassandraHealthIndicator.java   Source Code and License 6 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	try {
		Select select = QueryBuilder.select("release_version").from("system",
				"local");
		ResultSet results = this.cassandraOperations.query(select);
		if (results.isExhausted()) {
			builder.up();
			return;
		}
		String version = results.one().getString(0);
		builder.up().withDetail("version", version);
	}
	catch (Exception ex) {
		builder.down(ex);
	}
}
 
Example 17
Project: spring-cloud-stream-app-starters   File: CassandraSinkIntegrationTests.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 18
Project: spring-cloud-stream-app-starters   File: CassandraSinkIntegrationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testIngestQuery() throws Exception {
	List<Book> books = getBookList(5);

	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
	Jackson2JsonObjectMapper mapper = new Jackson2JsonObjectMapper(objectMapper);

	this.sink.input().send(new GenericMessage<>(mapper.toJson(books)));

	final Select select = QueryBuilder.select().all().from("book");

	assertEqualsEventually(5, new Supplier<Integer>() {

		@Override
		public Integer get() {
			return cassandraTemplate.select(select, Book.class).size();
		}

	});

	this.cassandraTemplate.truncate("book");
}
 
Example 19
Project: gcplot   File: CassandraGCEventRepository.java   Source Code and License 6 votes vote down vote up
protected Optional<Row> singleEvent(String analyseId, String jvmId, String bucketId,
                                    DateTime start, String[] fields) {
    List<String> dates = dates(Range.of(start.toDateTime(DateTimeZone.UTC),
            DateTime.now(DateTimeZone.UTC)));
    for (String date : dates) {
        Select from = QueryBuilder.select(fields).from(Strings.isNullOrEmpty(bucketId) ? TABLE_NAME : BUCKET_TABLE_NAME);
        Select.Where statement = from.limit(1)
                .where(eq("analyse_id", UUID.fromString(analyseId)))
                .and(eq("jvm_id", jvmId))
                .and(eq("date", date));
        if (!Strings.isNullOrEmpty(bucketId)) {
            statement = statement.and(eq("bucket_id", bucketId));
        }
        List<Row> rows = connector.session().execute(statement).all();
        if (rows.size() > 0) {
            return Optional.of(rows.get(0));
        }
    }
    return Optional.empty();
}
 
Example 20
Project: silverflash   File: CassandraMessageStore.java   Source Code and License 6 votes vote down vote up
public boolean schemaExists() throws StoreException {
  if (session != null) {
    boolean exists = false;
    Select select = QueryBuilder.select().column("keyspace_name").from("system.schema_keyspaces");
    ResultSet results = session.execute(select);

    for (Row row : results) {
      String name = row.getString("keyspace_name");
      if (KEYSPACE_NAME.equals(name)) {
        exists = true;
        break;
      }
    }
    return exists;
  } else {
    throw new StoreException("Keyspaces not available; store not open");
  }
}
 
Example 21
Project: contestparser   File: CassandraHealthIndicator.java   Source Code and License 6 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	try {
		Select select = QueryBuilder.select("release_version").from("system",
				"local");
		ResultSet results = this.cassandraAdminOperations.query(select);
		if (results.isExhausted()) {
			builder.up();
			return;
		}
		String version = results.one().getString(0);
		builder.up().withDetail("version", version);
	}
	catch (Exception ex) {
		builder.down(ex);
	}
}
 
Example 22
Project: playorm   File: CqlSession.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 23
Project: stratio-cassandra-test   File: CassandraUtilsSelect.java   Source Code and License 6 votes vote down vote up
public List<Row> get() {
    Select.Where where = QueryBuilder.select().from(parent.getKeyspace(), parent.getTable()).where();
    for (Clause clause : clauses) {
        where.and(clause);
    }
    if (searchBuilder != null) {
        where.and(QueryBuilder.eq(parent.getIndexColumn(), searchBuilder.refresh(refresh).toJson()));
    }
    BuiltStatement statement = limit == null ? where : where.limit(limit);

    String query = statement.toString();
    query = query.substring(0, query.length() - 1);
    StringBuilder sb = new StringBuilder(query);
    for (String extra : extras) {
        sb.append(" ");
        sb.append(extra);
        sb.append(" ");
    }
    return parent.execute(sb, fetchSize);
}
 
Example 24
Project: newts   File: CassandraSearcher.java   Source Code and License 6 votes vote down vote up
@Inject
public CassandraSearcher(CassandraSession session, MetricRegistry registry, ContextConfigurations contextConfigurations) {
    m_session = checkNotNull(session, "session argument");
    m_searchTimer = registry.timer(name("search", "search"));
    m_contextConfigurations = checkNotNull(contextConfigurations, "contextConfigurations argument");

    Select select = QueryBuilder.select(Schema.C_TERMS_RESOURCE).from(Schema.T_TERMS);
    select.where(eq(Schema.C_TERMS_CONTEXT, bindMarker(Schema.C_TERMS_CONTEXT)))
          .and(  eq(Schema.C_TERMS_FIELD, bindMarker(Schema.C_TERMS_FIELD)))
          .and(  eq(Schema.C_TERMS_VALUE, bindMarker(Schema.C_TERMS_VALUE)));
    m_searchStatement = m_session.prepare(select.toString());

    select = QueryBuilder.select(Schema.C_ATTRS_ATTR, Schema.C_ATTRS_VALUE).from(Schema.T_ATTRS);
    select.where(eq(Schema.C_ATTRS_CONTEXT, bindMarker(Schema.C_ATTRS_CONTEXT)))
          .and(  eq(Schema.C_ATTRS_RESOURCE, bindMarker(Schema.C_ATTRS_RESOURCE)));
    m_selectAttributesStatement = m_session.prepare(select.toString());

    select = QueryBuilder.select(Schema.C_METRICS_NAME).from(Schema.T_METRICS);
    select.where(eq(Schema.C_METRICS_CONTEXT, bindMarker(Schema.C_METRICS_CONTEXT)))
          .and(  eq(Schema.C_METRICS_RESOURCE, bindMarker(Schema.C_METRICS_RESOURCE)));
    m_selectMetricNamesStatement = m_session.prepare(select.toString());
}
 
Example 25
Project: agon   File: CassandraBadgeRepository.java   Source Code and License 6 votes vote down vote up
@Override
public Collection<Badge> findByEvent(String event) {
    Map<UUID, Badge> badges = new HashMap<>();

    Select.Where select = QueryBuilder.select().distinct().column("badge_id")
            .from("badge_events")
            .where(QueryBuilder.eq("event", event));

    ResultSet set = session.execute(select);

    for(Row row:set.all()) {
        UUID badgeId = row.getUUID("badge_id");

        if(badges.get(badgeId) == null) {
            badges.put(badgeId, get(badgeId).get());
        }
    }
    return badges.values();
}
 
Example 26
Project: agon   File: CassandraBadgeRepository.java   Source Code and License 6 votes vote down vote up
@Override
public List<Goal> findGoalsByBadgeId(UUID badgeId) {
    Select.Where goalQuery = QueryBuilder.select("event", "count")
            .from("badge_events")
            .where(QueryBuilder.eq("badge_id", badgeId));
    ResultSet rows = session.execute(goalQuery);
    List<Goal> goals = new ArrayList<>();

    for (Row row : rows) {
        goals.add(new Goal.Builder()
                .event(row.getString("event"))
                .value(row.getInt("count"))
                .build());
    }

    return goals;
}
 
Example 27
Project: agon   File: CassandraBadgeRepository.java   Source Code and License 6 votes vote down vote up
@Override
public Optional<Badge> get(UUID id) {
    Select.Where badgeQuery = QueryBuilder
            .select()
            .all()
            .from("badges")
            .where(QueryBuilder.eq("id", id));
    ResultSet set = session.execute(badgeQuery);
    Row row = set.one();

    return Optional.of(new Badge.Builder().id(row.getUUID("id"))
            .retired(row.getBool("retired"))
            .description(row.getString("description"))
            .name(row.getString("name"))
            .goals(findGoalsByBadgeId(id))
            .url(row.getString("url"))
            .build());
}
 
Example 28
Project: agon   File: CassandraPlayerRepository.java   Source Code and License 6 votes vote down vote up
@Override
public boolean evaluate(long playerId, Badge badge) {
    if(hasEarned(playerId, badge.getId())) return false;

    int goalsAchieved = 0;

    for (Goal goal : badge.getGoals()) {
        Select.Where eval = QueryBuilder.select().all()
                .from("player_event_counts")
                .where(QueryBuilder.eq("player_id", playerId))
                .and(QueryBuilder.eq("event", goal.getEvent()));

        ResultSet resultSet = session.execute(eval);
        Row row = resultSet.one();
        if(row != null) {
            long count = row.getLong("counter_value");
            if(count >= goal.getValue() ) {
                goalsAchieved++;
            }
        }
    }
    return goalsAchieved == badge.getGoals().size();
}
 
Example 29
Project: kaa   File: EndpointUserConfigurationCassandraDao.java   Source Code and License 6 votes vote down vote up
@Override
public CassandraEndpointUserConfiguration findByUserIdAndAppTokenAndSchemaVersion(
        String userId,
        String appToken,
        Integer schemaVersion
) {
  LOG.debug("Searching for user specific configuration by user id {}, "
          + "application token {} and schema version {}",
      userId, appToken, schemaVersion);
  Select.Where select = select().from(getColumnFamilyName())
      .where(eq(EP_USER_CONF_USER_ID_PROPERTY, userId))
      .and(eq(EP_USER_CONF_APP_TOKEN_PROPERTY, appToken))
      .and(eq(EP_USER_CONF_VERSION_PROPERTY, schemaVersion));

  CassandraEndpointUserConfiguration userConfiguration = findOneByStatement(select);
  if (LOG.isTraceEnabled()) {
    LOG.debug("[{},{},{}] Search result: {}.",
        userId, appToken, schemaVersion, userConfiguration);
  } else {
    LOG.debug("[{},{},{}] Search result: {}.",
        userId, appToken, schemaVersion, userConfiguration != null);
  }
  return userConfiguration;
}
 
Example 30
Project: gora   File: CassandraQueryFactory.java   Source Code and License 6 votes vote down vote up
private static String processKeys(String[] columnNames, BuiltStatement delete) {
  BuiltStatement query = null;
  boolean isWhereNeeded = true;
  for (String columnName : columnNames) {
    if (isWhereNeeded) {
      if (delete instanceof Delete) {
        query = ((Delete) delete).where(QueryBuilder.eq(columnName, "?"));
      } else {
        query = ((Select) delete).where(QueryBuilder.eq(columnName, "?"));
      }
      isWhereNeeded = false;
    } else {
      if (delete instanceof Delete) {
        query = ((Delete.Where) query).and(QueryBuilder.eq(columnName, "?"));
      } else {
        query = ((Select.Where) query).and(QueryBuilder.eq(columnName, "?"));
      }
    }
  }
  return query != null ? query.getQueryString() : null;
}
 
Example 31
Project: blueflood   File: DMetadataIO.java   Source Code and License 6 votes vote down vote up
private void createPreparedStatements() {

        Select.Where select = select()
                .all()
                .from( CassandraModel.CF_METRICS_METADATA_NAME )
                .where( eq( KEY, bindMarker() ));

        getValue = DatastaxIO.getSession().prepare( select );

        Insert insert = insertInto( CassandraModel.CF_METRICS_METADATA_NAME )
                .value( KEY, bindMarker() )
                .value( COLUMN1, bindMarker() )
                .value( VALUE, bindMarker() );

        putValue = DatastaxIO.getSession().prepare( insert );
        putValue.setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
    }
 
Example 32
Project: blueflood   File: DLocatorIO.java   Source Code and License 6 votes vote down vote up
/**
 * Create all prepared statements use in this class for metrics_locator
 */
private void createPreparedStatements()  {

    // create a generic select statement for retrieving from metrics_locator
    Select.Where select = QueryBuilder
            .select()
            .all()
            .from( CassandraModel.CF_METRICS_LOCATOR_NAME )
            .where( eq ( KEY, bindMarker() ));
    getValue = DatastaxIO.getSession().prepare( select );

    // create a generic insert statement for inserting into metrics_locator
    Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_LOCATOR_NAME)
            .using(ttl(TenantTtlProvider.LOCATOR_TTL))
            .value(KEY, bindMarker())
            .value(COLUMN1, bindMarker())
            .value(VALUE, bindMarker());
    putValue = DatastaxIO.getSession()
            .prepare(insert)
            .setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
}
 
Example 33
Project: blueflood   File: DDelayedLocatorIO.java   Source Code and License 6 votes vote down vote up
public DDelayedLocatorIO() {

        // create a generic select statement for retrieving from metrics_delayed_locator
        Select.Where select = QueryBuilder
                .select()
                .all()
                .from( CassandraModel.CF_METRICS_DELAYED_LOCATOR_NAME )
                .where( eq ( KEY, bindMarker() ));
        getValue = DatastaxIO.getSession().prepare( select );

        // create a generic insert statement for inserting into metrics_delayed_locator
        Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_DELAYED_LOCATOR_NAME)
                .using(ttl(TenantTtlProvider.DELAYED_LOCATOR_TTL))
                .value(KEY, bindMarker())
                .value(COLUMN1, bindMarker())
                .value(VALUE, bindMarker());
        putValue = DatastaxIO.getSession()
                .prepare(insert)
                .setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
    }
 
Example 34
Project: eventapis   File: CassandraViewQuery.java   Source Code and License 5 votes vote down vote up
private E queryEntityInternal(String entityId, Select select) throws EventStoreException {
    List<Row> entityEventDatas = cassandraSession.execute(select, PagingIterable::all);


    E initialInstance, result = null;
    try {
        initialInstance = entityType.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        log.error(e.getMessage(), e);
        throw new EventStoreException(e);
    }
    for (Row entityEventData : entityEventDatas) {
        EntityEvent entityEvent = convertToEntityEvent(entityEventData);
        if (entityEvent.getStatus() == EventState.CREATED || entityEvent.getStatus() == EventState.SUCCEDEED) {
            EntityFunctionSpec<E, ?> functionSpec = functionMap.get(entityEvent.getEventType());
            if (functionSpec != null) {
                EntityEventWrapper eventWrapper = new EntityEventWrapper<>(functionSpec.getQueryType(), objectMapper, entityEvent);
                EntityFunction<E, ?> entityFunction = functionSpec.getEntityFunction();
                result = (E) entityFunction.apply(result == null ? initialInstance : result, eventWrapper);
            } else
                log.trace("Function Spec is not available for " + entityEvent.getEventType() + " EntityId:" + entityId + " Table:" + tableName);
        }
        if (result != null) {
            result.setId(entityId);
            result.setVersion(entityEvent.getEventKey().getVersion());
        }
    }
    return (result == null || result.getId() == null) ? null : result;
}
 
Example 35
Project: eventapis   File: CassandraViewQuery.java   Source Code and License 5 votes vote down vote up
@Override
public List<EntityEvent> queryHistory(String entityId) throws EventStoreException {
    Select select = QueryBuilder.select().from(tableName);
    select.where(QueryBuilder.eq(CassandraEventRecorder.ENTITY_ID, entityId));
    return cassandraSession.execute(select, PagingIterable::all)
            .stream().map(CassandraViewQuery::convertToEntityEvent).collect(Collectors.toList());
}
 
Example 36
Project: eventapis   File: CassandraViewQuery.java   Source Code and License 5 votes vote down vote up
@Override
public E queryEntity(String entityId, int version) throws EventStoreException {
    Select select = QueryBuilder.select().from(tableName);
    select.where(QueryBuilder.eq(CassandraEventRecorder.ENTITY_ID, entityId));
    select.where(QueryBuilder.lte(CassandraEventRecorder.VERSION, version));
    return queryEntityInternal(entityId, select);
}
 
Example 37
Project: xm-ms-timeline   File: EntityMappingRepository.java   Source Code and License 5 votes vote down vote up
/**
 * Get entity id by entity key.
 *
 * @param key    the entity key
 * @param tenant tenant name
 * @return entity id
 */
public Long getIdByKey(String key, String tenant) {
    Select select = QueryBuilder.select(ENTITY_ID_COL).from(tenant, TABLE_KEY_ID);
    select.where(eq(ENTITY_KEY_COL, key));
    ResultSet resultSet = session.execute(select);
    Row row = resultSet.one();
    return  row == null ? null : row.getLong(ENTITY_ID_COL);
}
 
Example 38
Project: xm-ms-timeline   File: EntityMappingRepository.java   Source Code and License 5 votes vote down vote up
/**
 * Get entity key by entity id.
 *
 * @param entityId entity id
 * @param tenant   tenant name
 * @return entity key
 */
public String getKeyById(Long entityId, String tenant) {
    Select select = QueryBuilder.select(ENTITY_KEY_COL).from(tenant, VIEW_ID_KEY);
    select.where(eq(ENTITY_ID_COL, entityId));
    ResultSet resultSet = session.execute(select);
    Row row = resultSet.one();
    return row == null ? null : row.getString(ENTITY_KEY_COL);
}
 
Example 39
Project: xm-ms-timeline   File: TimelineRepository.java   Source Code and License 5 votes vote down vote up
/**
 * Get timelines by user key and date.
 *
 * @param userKey  the user key
 * @param dateFrom the date from
 * @param dateTo   the date to
 * @param page     the next page code
 * @param limit    the limit per page
 * @return timeline page with list of timelines and next page code
 */
public TimelinePageVM getTimelinesByUserKeyAndDate(String userKey,
                                                   Instant dateFrom,
                                                   Instant dateTo,
                                                   String page,
                                                   int limit) {
    Select select = QueryBuilder.select(getFields()).from(TenantContext.getCurrent().getTenant(),
        TABLE_TIMELINE_BY_USER_AND_DATE);
    select.where(eq(USER_KEY_COL, userKey));
    prepareWhereClause(select, null, dateFrom, dateTo, limit);
    return getPage(select, page, limit);
}
 
Example 40
Project: xm-ms-timeline   File: TimelineRepository.java   Source Code and License 5 votes vote down vote up
/**
 * Get timelines by user key, operation and date.
 *
 * @param userKey   the user key
 * @param operation the operation
 * @param dateFrom  the date from
 * @param dateTo    the date to
 * @param page      the next page code
 * @param limit     the limit per page
 * @return timeline page with list of timelines and next page code
 */
public TimelinePageVM getTimelinesByUserKeyAndOpAndDate(String userKey,
                                                        String operation,
                                                        Instant dateFrom,
                                                        Instant dateTo,
                                                        String page,
                                                        int limit) {
    Select select = QueryBuilder.select(getFields()).from(TenantContext.getCurrent().getTenant(),
        TABLE_TIMELINE_BY_USER_AND_OP_AND_DATE);
    select.where(eq(USER_KEY_COL, userKey));
    prepareWhereClause(select, operation, dateFrom, dateTo, limit);
    return getPage(select, page, limit);
}
 
Example 41
Project: xm-ms-timeline   File: TimelineRepository.java   Source Code and License 5 votes vote down vote up
/**
 * Get timelines by entity id and date.
 *
 * @param id       the entity id
 * @param dateFrom the date from
 * @param dateTo   the date to
 * @param page     the next page code
 * @param limit    the limit per page
 * @return timeline page with list of timelines and next page code
 */
public TimelinePageVM getTimelinesByEntityAndDate(Long id,
                                                  Instant dateFrom,
                                                  Instant dateTo,
                                                  String page,
                                                  int limit) {
    Select select = QueryBuilder.select(getFields()).from(TenantContext.getCurrent().getTenant(),
        TABLE_TIMELINE_BY_ENTITY_AND_DATE);
    select.where(eq(ENTITY_ID_COL, id));
    prepareWhereClause(select, null, dateFrom, dateTo, limit);
    return getPage(select, page, limit);
}
 
Example 42
Project: xm-ms-timeline   File: TimelineRepository.java   Source Code and License 5 votes vote down vote up
/**
 * Get timelines by entity id, operation and date.
 *
 * @param id        the entity id
 * @param operation the operation
 * @param dateFrom  the date from
 * @param dateTo    the date to
 * @param page      the next page code
 * @param limit     the limit per page
 * @return timeline page with list of timelines and next page code
 */
public TimelinePageVM getTimelinesByEntityAndOpAndDate(Long id,
                                                       String operation,
                                                       Instant dateFrom,
                                                       Instant dateTo,
                                                       String page,
                                                       int limit) {
    Select select = QueryBuilder.select(getFields()).from(TenantContext.getCurrent().getTenant(),
        TABLE_TIMELINE_BY_ENTITY_AND_OP_AND_DATE);
    select.where(eq(ENTITY_ID_COL, id));
    prepareWhereClause(select, operation, dateFrom, dateTo, limit);
    return getPage(select, page, limit);
}
 
Example 43
Project: xm-ms-timeline   File: TimelineRepository.java   Source Code and License 5 votes vote down vote up
private void prepareWhereClause(Select select, String operation, Instant dateFrom, Instant dateTo, int limit) {
    if (StringUtils.isNotBlank(operation)) {
        select.where(eq(OPERATION_COL, operation));
    }
    if (dateFrom != null) {
        select.where(gte(START_DATE_COL, Date.from(dateFrom)));
    }
    if (dateTo != null) {
        select.where(lte(START_DATE_COL, Date.from(dateTo)));
    }

    select.setFetchSize(limit);
}
 
Example 44
Project: xm-ms-timeline   File: TimelineRepository.java   Source Code and License 5 votes vote down vote up
private TimelinePageVM getPage(Select select, String page, int limit) {
    //If we have a 'next' page set we deserialise it and add it to the select
    //statement
    if (page != null) {
        select.setPagingState(PagingState.fromString(page));
    }

    //Execute the query
    ResultSet resultSet = session.execute(select);

    //Get the next paging state
    PagingState newPagingState = resultSet.getExecutionInfo().getPagingState();
    //The number of rows that can be read without fetching
    int remaining = resultSet.getAvailableWithoutFetching();

    List<XmTimeline> timelines = new ArrayList<>(limit);

    for (Row row : resultSet) {
        XmTimeline timeline = TimelineMapper.createTimeline(row);

        timelines.add(timeline);

        //If we can't move to the next row without fetching we break
        if (--remaining == 0) {
            break;
        }
    }

    //Serialise the next paging state
    String serializedNewPagingState = newPagingState != null
        ? newPagingState.toString() :
        null;

    //Return an object with a list of timelines and the next paging state
    return new TimelinePageVM(timelines, serializedNewPagingState);
}
 
Example 45
Project: sunbird-utils   File: CassandraOperationImpl.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 46
Project: iotplatform   File: CassandraCustomerDao.java   Source Code and License 5 votes vote down vote up
@Override
public Optional<Customer> findCustomersByTenantIdAndTitle(UUID tenantId, String title) {
    Select select = select().from(CUSTOMER_BY_TENANT_AND_TITLE_VIEW_NAME);
    Select.Where query = select.where();
    query.and(eq(CUSTOMER_TENANT_ID_PROPERTY, tenantId));
    query.and(eq(CUSTOMER_TITLE_PROPERTY, title));
    CustomerEntity customerEntity = findOneByStatement(query);
    Customer customer = DaoUtil.getData(customerEntity);
    return Optional.ofNullable(customer);
}
 
Example 47
Project: iotplatform   File: CassandraAbstractModelDao.java   Source Code and License 5 votes vote down vote up
@Override
public D findById(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);
    return DaoUtil.getData(entity);
}
 
Example 48
Project: iotplatform   File: CassandraAbstractModelDao.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<D> findByIdAsync(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);
}
 
Example 49
Project: iotplatform   File: CassandraBasePluginDao.java   Source Code and License 5 votes vote down vote up
@Override
public PluginMetaData findByApiToken(String apiToken) {
    log.debug("Search plugin meta-data entity by api token [{}]", apiToken);
    Select.Where query = select().from(ModelConstants.PLUGIN_BY_API_TOKEN_COLUMN_FAMILY_NAME).where(eq(ModelConstants.PLUGIN_API_TOKEN_PROPERTY, apiToken));
    log.trace("Execute query [{}]", query);
    PluginMetaDataEntity entity = findOneByStatement(query);
    if (log.isTraceEnabled()) {
        log.trace("Search result: [{}] for plugin entity [{}]", entity != null, entity);
    } else {
        log.debug("Search result: [{}]", entity != null);
    }
    return DaoUtil.getData(entity);
}
 
Example 50
Project: iotplatform   File: CassandraDeviceTypeDao.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<List<DeviceType>> findDeviceTypesByTenantIdAndIdsAsync(UUID tenantId, List<UUID> deviceIds) {
    log.debug("Try to find devices by tenantId [{}] and device Ids [{}]", tenantId, deviceIds);
    Select select = select().from(getColumnFamilyName());
    Select.Where query = select.where();
    query.and(eq(DEVICE_TYPE_TENANT_ID_PROPERTY, tenantId));
    query.and(in(ID_PROPERTY, deviceIds));
    return findListByStatementAsync(query);
}
 
Example 51
Project: iotplatform   File: CassandraDeviceTypeDao.java   Source Code and License 5 votes vote down vote up
@Override
public Optional<DeviceType> findDeviceTypeByTenantIdAndName(UUID tenantId, String deviceName) {
    Select select = select().from(DEVICE_TYPE_BY_TENANT_AND_NAME_VIEW_NAME);
    Select.Where query = select.where();
    query.and(eq(DEVICE_TYPE_TENANT_ID_PROPERTY, tenantId));
    query.and(eq(DEVICE_TYPE_NAME_PROPERTY, deviceName));
    return Optional.ofNullable(DaoUtil.getData(findOneByStatement(query)));
}
 
Example 52
Project: iotplatform   File: CassandraDeviceDao.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<List<Device>> findDevicesByTenantIdAndIdsAsync(UUID tenantId, List<UUID> deviceIds) {
    log.debug("Try to find devices by tenantId [{}] and device Ids [{}]", tenantId, deviceIds);
    Select select = select().from(getColumnFamilyName());
    Select.Where query = select.where();
    query.and(eq(DEVICE_TENANT_ID_PROPERTY, tenantId));
    query.and(in(ID_PROPERTY, deviceIds));
    return findListByStatementAsync(query);
}
 
Example 53
Project: iotplatform   File: CassandraDeviceDao.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<List<Device>> findDevicesByTenantIdCustomerIdAndIdsAsync(UUID tenantId, UUID customerId, List<UUID> deviceIds) {
    log.debug("Try to find devices by tenantId [{}], customerId [{}] and device Ids [{}]", tenantId, customerId, deviceIds);
    Select select = select().from(getColumnFamilyName());
    Select.Where query = select.where();
    query.and(eq(DEVICE_TENANT_ID_PROPERTY, tenantId));
    query.and(eq(DEVICE_CUSTOMER_ID_PROPERTY, customerId));
    query.and(in(ID_PROPERTY, deviceIds));
    return findListByStatementAsync(query);
}
 
Example 54
Project: iotplatform   File: CassandraDeviceDao.java   Source Code and License 5 votes vote down vote up
@Override
public Optional<Device> findDeviceByTenantIdAndName(UUID tenantId, String deviceName) {
    Select select = select().from(DEVICE_BY_TENANT_AND_NAME_VIEW_NAME);
    Select.Where query = select.where();
    query.and(eq(DEVICE_TENANT_ID_PROPERTY, tenantId));
    query.and(eq(DEVICE_NAME_PROPERTY, deviceName));
    return Optional.ofNullable(DaoUtil.getData(findOneByStatement(query)));
}
 
Example 55
Project: iotplatform   File: CassandraBaseAttributesDao.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<Optional<AttributeKvEntry>> find(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<? super ResultSet, ? extends Optional<AttributeKvEntry>>) input ->
                    Optional.ofNullable(convertResultToAttributesKvEntry(attributeKey, input.one()))
            , readResultsProcessingExecutor);
}
 
Example 56
Project: iotplatform   File: CassandraBaseAttributesDao.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<List<AttributeKvEntry>> findAll(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<? super ResultSet, ? extends List<AttributeKvEntry>>) input ->
                    convertResultToAttributesKvEntryList(input)
            , readResultsProcessingExecutor);
}
 
Example 57
Project: iotplatform   File: CassandraAlarmDao.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<Alarm> findLatestByOriginatorAndType(TenantId tenantId, EntityId originator, String type) {
    Select select = select().from(ALARM_COLUMN_FAMILY_NAME);
    Select.Where query = select.where();
    query.and(eq(ALARM_TENANT_ID_PROPERTY, tenantId.getId()));
    query.and(eq(ALARM_ORIGINATOR_ID_PROPERTY, originator.getId()));
    query.and(eq(ALARM_ORIGINATOR_TYPE_PROPERTY, originator.getEntityType()));
    query.and(eq(ALARM_TYPE_PROPERTY, type));
    query.limit(1);
    query.orderBy(QueryBuilder.asc(ModelConstants.ALARM_TYPE_PROPERTY), QueryBuilder.desc(ModelConstants.ID_PROPERTY));
    return findOneByStatementAsync(query);
}
 
Example 58
Project: iotplatform   File: CassandraAlarmDao.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<Alarm> findAlarmByIdAsync(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);
}
 
Example 59
Project: iotplatform   File: CassandraBaseRuleDao.java   Source Code and License 5 votes vote down vote up
@Override
public List<RuleMetaData> findRulesByPlugin(String pluginToken) {
    log.debug("Search rules by api token [{}]", pluginToken);
    Select select = select().from(ModelConstants.RULE_BY_PLUGIN_TOKEN);
    Select.Where query = select.where();
    query.and(eq(ModelConstants.RULE_PLUGIN_TOKEN_PROPERTY, pluginToken));
    return DaoUtil.convertDataList(findListByStatement(query));
}
 
Example 60
Project: iotplatform   File: CassandraBaseTimeseriesDao.java   Source Code and License 5 votes vote down vote up
/**
 * Select existing partitions from the table
 * <code>{@link ModelConstants#TS_KV_PARTITIONS_CF}</code> for the given entity
 */
private ResultSetFuture fetchPartitions(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);
}