@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; }
public void deleteRows(String tablename, Map<String, String> cols) { String ns = ""; String tbl = tablename; int ix = tbl.indexOf('.'); if (ix >= 0) { ns = tablename.substring(0, ix); tbl = tablename.substring(ix+1); } Delete stmt = QueryBuilder.delete().from(ns, tbl); if (cols.size() == 1) { // only handles 1 WHERE value right now String k = cols.keySet().iterator().next(); Clause eqclause = QueryBuilder.eq(k, cols.get(k)); session.execute(stmt.where(eqclause)); } else { session.execute(stmt); } }
private void checkIfRowExsits(String table, byte[] rowKey, String colName) { Clause rkClause = QueryBuilder.eq("id", ByteBuffer.wrap(rowKey)); Clause cnClause = QueryBuilder.eq("colname", colName); try { Query query = QueryBuilder.select().all().from(keys, table).where(rkClause).and(cnClause); ResultSet resultSet = session.execute(query); if (resultSet.isExhausted()) return; else { Query delQuery = QueryBuilder.delete().from(keys, table).where(rkClause).and(cnClause); session.execute(delQuery); } } catch (Exception e) { System.out.println(" Exception:" + e.getMessage()); } }
private void remove(Remove action, MetaLookup ormSession) { String colFamily = action.getColFamily().getColumnFamily(); String table = lookupOrCreate(colFamily, ormSession); if (action.getAction() == null) throw new IllegalArgumentException("action param is missing ActionEnum so we know to remove entire row or just columns in the row"); switch (action.getAction()) { case REMOVE_ENTIRE_ROW: Clause eqClause = QueryBuilder.eq("id", ByteBuffer.wrap(action.getRowKey())); Query query = QueryBuilder.delete().from(keys, table).where(eqClause); session.execute(query); break; case REMOVE_COLUMNS_FROM_ROW: removeColumns(action, table); break; default: throw new RuntimeException("bug, unknown remove action=" + action.getAction()); } }
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; }
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); }
private ReadQueryDataImpl(Tablename tablename, ImmutableMap<String, ImmutableList<Object>> keys, ImmutableSet<Clause> whereClauses, ImmutableMap<String, Boolean> columnsToFetch, Integer limit, Boolean allowFiltering, Integer fetchSize, Boolean distinct, PagingState pagingState) { this.tablename = tablename; this.keys = keys; this.whereClauses = whereClauses; this.columnsToFetch = columnsToFetch; this.limit = limit; this.allowFiltering = allowFiltering; this.fetchSize = fetchSize; this.distinct = distinct; this.pagingState = pagingState; }
private WriteQueryDataImpl(Tablename tablemname, ImmutableMap<String, Object> keys, ImmutableList<Clause> whereConditions, ImmutableMap<String, Optional<Object>> valuesToMutate, ImmutableMap<String, ImmutableSet<Object>> setValuesToAdd, ImmutableMap<String, ImmutableSet<Object>> setValuesToRemove, ImmutableMap<String, ImmutableList<Object>> listValuesToAppend, ImmutableMap<String, ImmutableList<Object>> listValuesToPrepend, ImmutableMap<String, ImmutableList<Object>> listValuesToRemove, ImmutableMap<String, ImmutableMap<Object, Optional<Object>>> mapValuesToMutate, ImmutableList<Clause> onlyIfConditions, Boolean ifNotExists) { this.tablename = tablemname; this.keys = keys; this.whereConditions = whereConditions; this.valuesToMutate = valuesToMutate; this.setValuesToAdd = setValuesToAdd; this.setValuesToRemove = setValuesToRemove; this.listValuesToAppend = listValuesToAppend; this.listValuesToPrepend = listValuesToPrepend; this.listValuesToRemove = listValuesToRemove; this.mapValuesToMutate = mapValuesToMutate; this.onlyIfConditions = onlyIfConditions; this.ifNotExists = ifNotExists; }
@Override public Optional<CassandraEndpointRegistration> findByEndpointId(String endpointId) { LOG.debug("Searching for endpoint registration by endpoint ID [{}]", endpointId); Optional<String> credentialsId = this.byEndpointId.getCredentialsIdByEndpointId( endpointId); if (credentialsId.isPresent()) { LOG.debug("[{}] Endpoint credentials ID by endpoint ID: {}", endpointId, credentialsId.get()); Clause clause = QueryBuilder.eq( CassandraModelConstants.EP_REGISTRATION_CREDENTIALS_ID_PROPERTY, credentialsId.get()); Statement statement = QueryBuilder.select().from(this.getColumnFamilyName()) .where(clause); return Optional.ofNullable(this.findOneByStatement(statement)); } else { LOG.debug("[{}] No credentials ID found by endpoint ID: {}", endpointId); return Optional.empty(); } }
@Override public void removeByEndpointId(String endpointId) { LOG.debug("Removing endpoint registration by endpoint ID", endpointId); Optional<String> credentialsId = this.byEndpointId.getCredentialsIdByEndpointId( endpointId); if (credentialsId.isPresent()) { Clause clause = QueryBuilder.eq( CassandraModelConstants.EP_REGISTRATION_BY_ENDPOINT_ID_ENDPOINT_ID_PROPERTY, endpointId); Statement statement = QueryBuilder.delete() .from(this.byEndpointId.getColumnFamilyName()) .where(clause); this.execute(statement); clause = QueryBuilder.eq( CassandraModelConstants.EP_REGISTRATION_CREDENTIALS_ID_PROPERTY, credentialsId.get()); statement = QueryBuilder.delete().from(this.getColumnFamilyName()).where(clause); this.execute(statement); } else { LOG.debug("[{}] No credentials ID found by endpoint ID: {}", endpointId); } }
@SuppressWarnings("rawtypes") public void delete(String keyspace, String table, JSONArray columns, JSONObject where, ConsistencyLevel consistency_level) throws MemnonException, IOException { Delete.Selection selection = QueryBuilder.delete(); if (columns == null) { selection.all(); } else { Iterator columnIterator = columns.iterator(); while (columnIterator.hasNext()) { selection.column((String) columnIterator.next()); } } Delete statement = selection.from(table); Iterator whereIterator = where.entrySet().iterator(); while (whereIterator.hasNext()) { Map.Entry pair = (Map.Entry) whereIterator.next(); Clause clause = QueryBuilder.eq((String) pair.getKey(), pair.getValue()); statement.where(clause); } executeStatement(keyspace, statement); }
private Collection<RegularStatement> diffSet(String table, String column, Clause whereClause, Set<?> past, Set<?> present) { List<RegularStatement> queries = Lists.newArrayList(); Set<?> removes = Sets.newHashSet(past); removes.removeAll(present); if (!removes.isEmpty()) { queries.add(QueryBuilder.update(table).with(removeAll(column, removes)).where(whereClause)); } Set<?> adds = Sets.newHashSet(present); adds.removeAll(past); if (!adds.isEmpty()) { queries.add(QueryBuilder.update(table).with(addAll(column, adds)).where(whereClause)); } return queries; }
public void updateShardPointer(final Shard shard){ Assignment assignment = QueryBuilder.set(COLUMN_POINTER, shard.getPointer()); Clause queueNameClause = QueryBuilder.eq(COLUMN_QUEUE_NAME, shard.getQueueName()); Clause regionClause = QueryBuilder.eq(COLUMN_REGION, shard.getRegion()); Clause activeClause = QueryBuilder.eq(COLUMN_ACTIVE, 1); Clause shardIdClause = QueryBuilder.eq(COLUMN_SHARD_ID, shard.getShardId()); Statement update = QueryBuilder.update(getTableName(shard.getType())) .with(assignment) .where(queueNameClause) .and(regionClause) .and(activeClause) .and(shardIdClause); cassandraClient.getQueueMessageSession().execute(update); }
@Override public DatabaseQueueMessageBody loadMessageData(final UUID messageId ){ logger.trace("loadMessageData {}", messageId); Clause messageIdClause = QueryBuilder.eq( COLUMN_MESSAGE_ID, messageId ); Statement select = QueryBuilder.select().from( TABLE_MESSAGE_DATA).where(messageIdClause); Row row = cassandraClient.getApplicationSession().execute(select).one(); if ( row == null ) { return null; } return new DatabaseQueueMessageBody( row.getBytes( COLUMN_MESSAGE_DATA), row.getString( COLUMN_CONTENT_TYPE)); }
private Statement createDeleteAllMessagesStatement( Shard shard ) { Clause queueNameClause = QueryBuilder.eq( COLUMN_QUEUE_NAME, shard.getQueueName() ); Clause regionClause = QueryBuilder.eq( COLUMN_REGION, shard.getRegion() ); Clause shardIdClause = QueryBuilder.eq( COLUMN_SHARD_ID, shard.getShardId() ); DatabaseQueueMessage.Type dbqmType = Shard.Type.DEFAULT.equals( shard.getType() ) ? DatabaseQueueMessage.Type.DEFAULT : DatabaseQueueMessage.Type.INFLIGHT; Statement deleteAll = QueryBuilder.delete().from( getTableName( dbqmType )) .where(queueNameClause) .and(regionClause) .and(shardIdClause); return deleteAll; }
@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; }
public List<Map<String, Object>> selectRows(final String tablename, Map<String, String> cols) { String ns = ""; String tbl = tablename; int ix = tbl.indexOf('.'); if (ix >= 0) { ns = tablename.substring(0, ix); tbl = tablename.substring(ix+1); } Select sel = QueryBuilder.select().all().from(ns, tbl); Statement stmt = sel; if (cols.size() == 1) { // only handles 1 WHERE value right now String k = cols.keySet().iterator().next(); Clause eqclause = QueryBuilder.eq(k, cols.get(k)); stmt = sel.where(eqclause); } ResultSet resultset = session.execute(stmt); List<Map<String, Object>> results = new ArrayList<Map<String,Object>>(); for (Row row : resultset) { Map<String, Object> map = new HashMap<String, Object>(); for (Definition definition : row.getColumnDefinitions()) { map.put(definition.getName(), readRow(row, definition.getName(), definition.getType())); } results.add(map); } return results; }
private static void addWhereClause(Where where, List<CassandraColumnHandle> partitionKeyColumns, List<Object> filterPrefix) { for (int i = 0; i < filterPrefix.size(); i++) { CassandraColumnHandle column = partitionKeyColumns.get(i); Object value = column.getCassandraType().getJavaValue(filterPrefix.get(i)); Clause clause = QueryBuilder.eq(CassandraCqlUtils.validColumnName(column.getName()), value); where.and(clause); } }
@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; }
private void removeIndex(RemoveIndex action, MetaLookup ormSession) { String colFamily = action.getIndexCfName(); if (colFamily.equalsIgnoreCase("BytesIndice")) return; String table = lookupOrCreate(colFamily, ormSession); String rowKey = StandardConverters.convertFromBytes(String.class, action.getRowKey()); IndexColumn column = action.getColumn(); byte[] fk = column.getPrimaryKey(); byte[] indexedValue = action.getColumn().getIndexedValue(); Object indValue = null; if (table.equalsIgnoreCase("StringIndice")) indValue = StandardConverters.convertFromBytes(String.class, indexedValue); else if (table.equalsIgnoreCase("IntegerIndice")) indValue = StandardConverters.convertFromBytes(Long.class, indexedValue); else if (table.equalsIgnoreCase("DecimalIndice")) indValue = StandardConverters.convertFromBytes(Float.class, indexedValue); boolean exists = findIndexRow(table, rowKey, fk, indValue); if (!exists) { if (log.isInfoEnabled()) log.info("Index: " + column.toString() + " already removed."); } else { Clause eqClause = QueryBuilder.eq("id", rowKey); 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", ""); } } Clause fkClause = QueryBuilder.eq("colvalue", ByteBuffer.wrap(fk)); Query query = QueryBuilder.delete().from(keys, table).where(eqClause).and(indClause).and(fkClause); session.execute(query); } }
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; }
public Iterable<Metric> loadMetrics( RetentionTable table, String name, Interval interval ) { if ( session == null ) { open(); } Clause cName = QueryBuilder.eq( COL_NAME, name ); Ordering order = QueryBuilder.desc( COL_TIME ); // start inclusive, end exclusive Clause cBtm = QueryBuilder.gte( COL_TIME, interval.start() ); Clause cTop = QueryBuilder.lt( COL_TIME, interval.end() ); Statement stm = QueryBuilder.select().all().from( table.tableName() ).where( cName ).and( cBtm ).and( cTop ).orderBy( order ); final Iterator<Row> iter = session.execute( stm ).iterator(); return new Iterable<Metric>() { @Override public Iterator<Metric> iterator() { return new Iterator<Metric>() { @Override public boolean hasNext() { return iter.hasNext(); } @Override public Metric next() { Row row = iter.next(); return new Metric( row.getString( COL_NAME ), row.getLong( COL_TIME ), row.getDouble( COL_VALUE ) ); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }
public Iterable<Metric> loadUnorderedMetrics( RetentionTable table, String name ) { if ( session == null ) { open(); } Clause cName = QueryBuilder.eq( COL_NAME, name ); Statement stm = QueryBuilder.select().all().from( table.tableName() ).where( cName ); final Iterator<Row> iter = session.execute( stm ).iterator(); return new Iterable<Metric>() { @Override public Iterator<Metric> iterator() { return new Iterator<Metric>() { @Override public boolean hasNext() { return iter.hasNext(); } @Override public Metric next() { Row row = iter.next(); return new Metric( row.getString( COL_NAME ), row.getLong( COL_TIME ), row.getDouble( COL_VALUE ) ); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }
/** * Constructor */ ReadQueryDataImpl(Tablename tablename) { this(tablename, ImmutableMap.<String, ImmutableList<Object>>of(), ImmutableSet.<Clause>of(), ImmutableMap.<String, Boolean>of(), null, null, null, null, null); }
@Override public ReadQueryDataImpl whereConditions(ImmutableSet<Clause> whereClauses) { return new ReadQueryDataImpl(this.tablename, this.keys, whereClauses, this.columnsToFetch, this.limit, this.allowFiltering, this.fetchSize, this.distinct, this.pagingState); }
public CounterMutationQueryData(Tablename tablename) { this(tablename, ImmutableMap.<String, Object>of(), ImmutableList.<Clause>of(), null, 0); }
private CounterMutationQueryData(Tablename tablename, ImmutableMap<String, Object> keys, ImmutableList<Clause> whereConditions, String name, long diff) { this.tablename = tablename; this.keys = keys; this.whereConditions = whereConditions; this.name = name; this.diff = diff; }
public CountReadQueryData(Tablename tablename) { this(tablename, ImmutableSet.<Clause>of(), null, null, null, null); }
private CountReadQueryData(Tablename tablename, ImmutableSet<Clause> whereClauses, Integer limit, Boolean allowFiltering, Integer fetchSize, Boolean distinct) { this.tablename = tablename; this.whereClauses = whereClauses; this.limit = limit; this.allowFiltering = allowFiltering; this.fetchSize = fetchSize; this.distinct = distinct; }
public CountReadQueryData whereConditions(ImmutableSet<Clause> whereClauses) { return new CountReadQueryData(this.tablename, whereClauses, this.limit, this.allowFiltering, this.fetchSize, this.distinct); }
/** * constructor */ WriteQueryDataImpl(Tablename tablename) { this(tablename, ImmutableMap.<String, Object>of(), ImmutableList.<Clause>of(), ImmutableMap.<String, Optional<Object>>of(), ImmutableMap.<String, ImmutableSet<Object>>of(), ImmutableMap.<String, ImmutableSet<Object>>of(), ImmutableMap.<String, ImmutableList<Object>>of(), ImmutableMap.<String, ImmutableList<Object>>of(), ImmutableMap.<String, ImmutableList<Object>>of(), ImmutableMap.<String, ImmutableMap<Object, Optional<Object>>>of(), ImmutableList.<Clause>of(), null); }
/** * constructor */ DeleteQueryDataImpl(Tablename tablename) { this(tablename, ImmutableMap.<String, Object>of(), ImmutableList.<Clause>of(), ImmutableList.<Clause>of(), null, null); }
private DeleteQueryDataImpl(Tablename tablename, ImmutableMap<String, Object> keyNameValuePairs, ImmutableList<Clause> whereConditions, ImmutableList<Clause> onlyIfConditions, Boolean ifExists, ImmutableMap<String, List<Object>> mapValuesToRemove) { this.tablename = tablename; this.keyNameValuePairs = keyNameValuePairs; this.whereConditions = whereConditions; this.onlyIfConditions = onlyIfConditions; this.ifExists = ifExists; this.mapValuesToRemove = mapValuesToRemove; }
private Clause[] buildKeyClauses(CassandraEntityMapper<T> entityMapper, T entity) { List<String> keyColumns = entityMapper.getKeyColumnNames(); Clause[] clauses = new Clause[keyColumns.size()]; for (int i = 0; i < keyColumns.size(); i++) { String columnName = keyColumns.get(i); clauses[i] = eq( columnName, entityMapper.getColumnValueForName(columnName, entity, cassandraClient)); } return clauses; }
@Override public Optional<CassandraEndpointRegistration> findByCredentialsId(String credentialsId) { LOG.debug("Searching for endpoint registration by credentials ID [{}]", credentialsId); Clause clause = QueryBuilder.eq( CassandraModelConstants.EP_REGISTRATION_CREDENTIALS_ID_PROPERTY, credentialsId); Statement statement = QueryBuilder.select().from(this.getColumnFamilyName()) .where(clause); return Optional.ofNullable(this.findOneByStatement(statement)); }
/** * Found credential's id by endpoint id. * @param endpointId is endpoint id * @return string id or empty <code>Optional</code> if not found */ public Optional<String> getCredentialsIdByEndpointId(String endpointId) { Clause clause = QueryBuilder.eq( CassandraModelConstants.EP_REGISTRATION_BY_ENDPOINT_ID_ENDPOINT_ID_PROPERTY, endpointId); Statement statement = QueryBuilder.select().from(this.getColumnFamilyName()).where(clause); CassandraEpRegistrationByEndpointId result = this.findOneByStatement(statement); if (result != null) { return Optional.of(result.getCredentialsId()); } else { return Optional.empty(); } }
@SuppressWarnings("rawtypes") public JSONArray select(String keyspace, String table, JSONArray columns, JSONObject where, ConsistencyLevel consistencyLevel) throws MemnonException, CharacterCodingException { Selection selection = QueryBuilder.select(); if (columns == null) { selection.all(); } else { Iterator columnIterator = columns.iterator(); while (columnIterator.hasNext()) { selection.column((String) columnIterator.next()); } } Select statement = selection.from(table); Iterator whereIterator = where.entrySet().iterator(); while (whereIterator.hasNext()) { Map.Entry pair = (Map.Entry) whereIterator.next(); Clause clause = QueryBuilder.eq((String) pair.getKey(), pair.getValue()); statement.where(clause); } ResultSet results = executeStatement(keyspace, statement); return JsonMarshaller.marshallResultSet(results); }
private Collection<RegularStatement> diffCollection(String table, String column, Clause whereClause, Object past, Object present) { if (past instanceof Set<?>) { return diffSet(table, column, whereClause, (Set<?>) past, (Set<?>) present); } else if (past instanceof Map<?, ?>) { return diffMap(table, column, whereClause, (Map<?, ?>) past, (Map<?, ?>) present); } else { throw new RuntimeException("unknown collection type!"); } }