@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 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()); }
@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; }
/** * Creates and stores a new {@link Addressbook} inside of Cassandra. {@link Contact} classes are converted using the * custom {@link example.springdata.cassandra.convert.ConverterConfiguration.PersonWriteConverter}. */ @Test public void shouldCreateAddressbook() { Addressbook addressbook = new Addressbook(); addressbook.setId("private"); addressbook.setMe(new Contact("Walter", "White")); addressbook.setFriends(Arrays.asList(new Contact("Jesse", "Pinkman"), new Contact("Saul", "Goodman"))); operations.insert(addressbook); Row row = operations.selectOne(QueryBuilder.select().from("addressbook"), Row.class); assertThat(row, is(notNullValue())); assertThat(row.getString("id"), is(equalTo("private"))); assertThat(row.getString("me"), containsString("\"firstname\":\"Walter\"")); assertThat(row.getList("friends", String.class), hasSize(2)); }
/** * Creates and loads a new {@link Addressbook} inside of Cassandra. {@link Contact} classes are converted using the * custom {@link example.springdata.cassandra.convert.ConverterConfiguration.PersonReadConverter}. */ @Test public void shouldReadAddressbook() { Addressbook addressbook = new Addressbook(); addressbook.setId("private"); addressbook.setMe(new Contact("Walter", "White")); addressbook.setFriends(Arrays.asList(new Contact("Jesse", "Pinkman"), new Contact("Saul", "Goodman"))); operations.insert(addressbook); Addressbook loaded = operations.selectOne(QueryBuilder.select().from("addressbook"), Addressbook.class); assertThat(loaded.getMe(), is(equalTo(addressbook.getMe()))); assertThat(loaded.getFriends(), is(equalTo(addressbook.getFriends()))); }
/** * Cassandra {@link com.datastax.driver.core.Statement}s can be used together with {@link CassandraTemplate} and the * mapping layer. */ @Test public void insertAndSelect() { Insert insert = QueryBuilder.insertInto("users").value("user_id", 42L) // .value("uname", "heisenberg") // .value("fname", "Walter") // .value("lname", "White") // .ifNotExists(); // template.execute(insert); User user = template.selectOneById(User.class, 42L); assertThat(user.getUsername(), is(equalTo("heisenberg"))); List<User> users = template.select(QueryBuilder.select().from("users"), User.class); assertThat(users, hasSize(1)); assertThat(users.get(0), is(equalTo(user))); }
/** * {@link CassandraTemplate} allows selection of projections on template-level. All basic data types including * {@link Row} can be selected. */ @Test @SuppressWarnings("unchecked") public void selectProjections() { User user = new User(); user.setId(42L); user.setUsername("heisenberg"); user.setFirstname("Walter"); user.setLastname("White"); template.insert(user); Long id = template.selectOne(QueryBuilder.select("user_id").from("users"), Long.class); assertThat(id, is(user.getId())); Row row = template.selectOne(QueryBuilder.select("user_id").from("users"), Row.class); assertThat(row.getLong(0), is(user.getId())); Map<String, Object> map = template.selectOne(QueryBuilder.select().from("users"), Map.class); assertThat(map, hasEntry("user_id", user.getId())); assertThat(map, hasEntry("fname", "Walter")); }
@Override public long uploadPackage(DataPackage dataPack) { long time = System.currentTimeMillis(); try { Session session; Cluster cluster; cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); session = cluster.connect(); ByteBuffer buffer = ByteBuffer.wrap(dataPack.getData()); Statement statement = QueryBuilder.insertInto(DATABASE, MAIN_TABLE) .value(COL_ID, time) .value(COL_DATA, buffer) .value(COL_DESC, dataPack.getDescription()); session.execute(statement); } catch (Exception ex) { System.out.println(ex.getMessage()); } return time; }
@Override public DataPackage downloadPackage(long packageID) { DataPackage dataPack = new DataPackage(); try { Session session; Cluster cluster; cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); session = cluster.connect(); Statement statement = QueryBuilder.select() .all() .from(DATABASE, MAIN_TABLE) .where(eq(COL_ID, packageID)); ResultSet results = session.execute(statement); for(Row row : results) { dataPack.setId(row.getLong(COL_ID)); dataPack.setDescription(row.getString(COL_DESC)); dataPack.setData(row.getBytes(COL_DATA).array()); } } catch (Exception ex) { System.out.println(ex.getMessage()); } return dataPack; }
@Override public List<DataPackage> listPackages() { List<DataPackage> dataPacks = new ArrayList<>(); try { Session session; Cluster cluster; cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); session = cluster.connect(); Statement statement = QueryBuilder.select() .all() .from(DATABASE, MAIN_TABLE); ResultSet results = session.execute(statement); for(Row row : results) { DataPackage dataPack = new DataPackage(); dataPack.setId(row.getLong(COL_ID)); dataPack.setDescription(row.getString(COL_DESC)); dataPacks.add(dataPack); } } catch (Exception ex) { System.out.println(ex.getMessage()); } return dataPacks; }
@Override public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { String tokenValue = refreshToken.getValue(); // Lookup RefreshTokenToAccessToken table for locating access token RefreshTokenToAccessToken refreshTokenToAccessToken = refreshTokenToAccessTokenRepository.findOne(tokenValue); if (refreshTokenToAccessToken != null) { String accessTokenKey = refreshTokenToAccessToken.getAccessTokenKey(); AccessToken accessToken = accessTokenRepository.findOne(accessTokenKey); String jsonOAuth2AccessToken = accessToken.getoAuth2AccessToken(); OAuth2AccessToken oAuth2AccessToken = OAuthUtil.deserializeOAuth2AccessToken(jsonOAuth2AccessToken); // Delete access token from all related tables List<RegularStatement> statementList = prepareRemoveAccessTokenStatements(oAuth2AccessToken); // Delete from RefreshTokenToAccessToken table Delete refreshTokenToAccessTokenDelete = CassandraTemplate.createDeleteQuery(RefreshTokenToAccessToken.TABLE, refreshTokenToAccessToken, null, cassandraTemplate.getConverter()); statementList.add(refreshTokenToAccessTokenDelete); Batch batch = QueryBuilder.batch(statementList.toArray(new RegularStatement[statementList.size()])); cassandraTemplate.execute(batch); } }
@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; }
@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); }
private Optional<Event> save(EventEntity entity, boolean ifNotExists) { if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } Insert insert = QueryBuilder.insertInto(getColumnFamilyName()) .value(ModelConstants.ID_PROPERTY, entity.getId()) .value(ModelConstants.EVENT_TENANT_ID_PROPERTY, entity.getTenantId()) .value(ModelConstants.EVENT_ENTITY_TYPE_PROPERTY, entity.getEntityType()) .value(ModelConstants.EVENT_ENTITY_ID_PROPERTY, entity.getEntityId()) .value(ModelConstants.EVENT_TYPE_PROPERTY, entity.getEventType()) .value(ModelConstants.EVENT_UID_PROPERTY, entity.getEventUid()) .value(ModelConstants.EVENT_BODY_PROPERTY, entity.getBody()); if (ifNotExists) { insert = insert.ifNotExists(); } ResultSet rs = executeWrite(insert); if (rs.wasApplied()) { return Optional.of(DaoUtil.getData(entity)); } else { return Optional.empty(); } }
private Optional<ComponentDescriptor> saveIfNotExist(ComponentDescriptorEntity entity) { if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } ResultSet rs = executeRead(QueryBuilder.insertInto(getColumnFamilyName()) .value(ModelConstants.ID_PROPERTY, entity.getId()) .value(ModelConstants.COMPONENT_DESCRIPTOR_NAME_PROPERTY, entity.getName()) .value(ModelConstants.COMPONENT_DESCRIPTOR_CLASS_PROPERTY, entity.getClazz()) .value(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, entity.getType()) .value(ModelConstants.COMPONENT_DESCRIPTOR_SCOPE_PROPERTY, entity.getScope()) .value(ModelConstants.COMPONENT_DESCRIPTOR_CONFIGURATION_DESCRIPTOR_PROPERTY, entity.getConfigurationDescriptor()) .value(ModelConstants.COMPONENT_DESCRIPTOR_ACTIONS_PROPERTY, entity.getActions()) .value(ModelConstants.SEARCH_TEXT_PROPERTY, entity.getSearchText()) .ifNotExists() ); if (rs.wasApplied()) { return Optional.of(DaoUtil.getData(entity)); } else { return Optional.empty(); } }
Indexer(Session session, @Nullable Integer indexTtl, @Nullable ConcurrentMap<PartitionKeyToTraceId, Pair<Long>> sharedState, IndexSupport index) { this.index = index; this.boundName = UPPER_CAMEL.to(LOWER_HYPHEN, index.getClass().getSimpleName()); Insert insert = index.declarePartitionKey(QueryBuilder.insertInto(index.table()) .value("ts", QueryBuilder.bindMarker("ts")) .value("trace_id", QueryBuilder.bindMarker("trace_id"))); if (indexTtl != null) { insert.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_"))); } this.prepared = session.prepare(insert); this.indexTtl = indexTtl; this.session = session; this.timestampCodec = new TimestampCodec(session); this.sharedState = sharedState; }
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); } }
@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); } }
private void insertBlockedDeltas(BatchStatement batchStatement, BlockedDeltaTableDDL tableDDL, ConsistencyLevel consistencyLevel, ByteBuffer rowKey, UUID changeId, ByteBuffer encodedDelta) { List<ByteBuffer> blocks = _daoUtils.getDeltaBlocks(encodedDelta); if (blocks.size() > 1) { _blockedRowsMigratedMeter.mark(); } for (int i = 0; i < blocks.size(); i++) { batchStatement.add(QueryBuilder.insertInto(tableDDL.getTableMetadata()) .value(tableDDL.getRowKeyColumnName(), rowKey) .value(tableDDL.getChangeIdColumnName(), changeId) .value(tableDDL.getBlockColumnName(), i) .value(tableDDL.getValueColumnName(), blocks.get(i)) .setConsistencyLevel(consistencyLevel)); } }
@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); }
@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"); }
@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); }
@Override public List<BoundedSource<T>> split(CassandraIO.Read<T> spec, long desiredBundleSizeBytes) { try (Cluster cluster = getCluster(spec.hosts(), spec.port(), spec.username(), spec.password(), spec.localDc(), spec.consistencyLevel())) { if (isMurmur3Partitioner(cluster)) { LOG.info("Murmur3Partitioner detected, splitting"); return split(spec, desiredBundleSizeBytes, getEstimatedSizeBytes(spec)); } else { LOG.warn("Only Murmur3Partitioner is supported for splitting, using an unique source for " + "the read"); String splitQuery = QueryBuilder.select().from(spec.keyspace(), spec.table()).toString(); List<BoundedSource<T>> sources = new ArrayList<>(); sources.add(new CassandraIO.CassandraSource<T>(spec, splitQuery)); return sources; } } }
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(); }
/** * Returns the Ref to which the specified name is mapped * * @param name the name whose associated value is to be returned * @return the Ref to which the specified name is mapped, or null if * the store contains no mapping for the name * @throws IOException if an exception occurs when communicating to the * database */ public Ref get(String name) throws IOException { try { Statement stmt = QueryBuilder .select() .all() .from(keyspace, TABLE_NAME) .where(QueryBuilder.eq("name", name)); ResultSet results = session.execute(stmt); Ref r = rowToRef(results.one()); if (!results.isExhausted()) { throw new IllegalStateException("Multiple rows for a single ref: " + name); } return r; } catch (RuntimeException e) { e.printStackTrace(); throw new IOException(e); } }
/** * @return a Collection view of all refs in the store * @throws IOException if an exception occurs when communicating to the * database */ public Collection<Ref> values() throws IOException { try { List<Ref> refs = new ArrayList<Ref>(); Statement stmt = QueryBuilder .select() .all() .from(keyspace, TABLE_NAME); stmt.setFetchSize(FETCH_SIZE); ResultSet results = session.execute(stmt); for (Row row : results) { refs.add(rowToRef(row)); } return refs; } catch (RuntimeException e) { e.printStackTrace(); throw new IOException(e); } }
/** * Inserts a row into the refs table. This works for both insertion of a * new row, and updating an existing row. * * @param name the primary key * @param type a type where the value is mapped to an integer through * the RefType enum * @param value the value, either a commit id or in the case of a * symbolic reference, the target name * @param auxValue an additional value, either the peeled object id in the * case of a peeled tag ref, or an empty string for all * other types of commits * @throws IOException if an exception occurs when communicating to the * database */ private void putRow(String name, RefType type, String value, String auxValue) throws IOException { try { Statement stmt = QueryBuilder.insertInto(keyspace, TABLE_NAME) .value("name", name) .value("type", type.getValue()) .value("value", value) .value("aux_value", auxValue); session.execute(stmt); } catch (RuntimeException e) { e.printStackTrace(); throw new IOException(e); } }
/** * Inserts a Pack description into the store. * If a description for this "name" already exists it will be overwritten. * * @param desc the pack description to insert * @throws IOException if an exception occurs when communicating to the * database */ public void insertDesc(Collection<DfsPackDescription> desc) throws IOException { try { for (DfsPackDescription pd : desc) { Statement stmt = QueryBuilder.insertInto(keyspace, DESC_TABLE_NAME) .value("name", pd.toString()) .value("source", pd.getPackSource().ordinal()) .value("last_modified", pd.getLastModified()) .value("size_map", DescMapper.getFileSizeMap(pd)) .value("object_count", pd.getObjectCount()) .value("delta_count", pd.getDeltaCount()) .value("extensions", DescMapper.getExtBits(pd)) .value("index_version", pd.getIndexVersion()); session.execute(stmt); } } catch (RuntimeException e) { e.printStackTrace(); throw new IOException(e); } }
/** * Returns a ByteBuffer with the contents of the file given by the pair * "desc" and "ext". * * @throws IOException if an exception occurs when communicating to the * database */ public ByteBuffer readFile(DfsPackDescription desc, PackExt ext) throws IOException { try { Statement stmt = QueryBuilder .select() .all() .from(keyspace, DATA_TABLE_NAME) .where(QueryBuilder.eq("name", desc.getFileName(ext))); ResultSet results = session.execute(stmt); Row r = results.one(); if (!results.isExhausted()) { throw new IllegalStateException("Multiple rows for a single file: " + desc.getFileName(ext)); } return r.getBytes("data"); } catch (RuntimeException e) { e.printStackTrace(); throw new IOException(e); } }
public static void prepare(CassandraProcessEngineConfiguration config) { selectStatement = config.getSession().prepare(select("val") .from(IndexTableHandler.INDEX_TABLE_NAME) .where(eq("idx_name", QueryBuilder.bindMarker())) .and(eq("idx_value", QueryBuilder.bindMarker()))); insertStatement = config.getSession().prepare(insertInto(IndexTableHandler.INDEX_TABLE_NAME) .value("idx_name", QueryBuilder.bindMarker()) .value("idx_value",QueryBuilder.bindMarker()) .value("val",QueryBuilder.bindMarker())); deleteStatement = config.getSession().prepare(delete().all() .from(IndexTableHandler.INDEX_TABLE_NAME) .where(eq("idx_name", QueryBuilder.bindMarker())) .and(eq("idx_value",QueryBuilder.bindMarker())) .and(eq("val",QueryBuilder.bindMarker()))); deleteUniqueStatement = config.getSession().prepare(delete().all() .from(IndexTableHandler.INDEX_TABLE_NAME) .where(eq("idx_name", QueryBuilder.bindMarker())) .and(eq("idx_value",QueryBuilder.bindMarker()))); }
public void delete(CassandraPersistenceSession session, ExecutionEntity entity) { if(entity.isProcessInstanceExecution()) { session.addStatement(QueryBuilder.delete().all() .from(ProcessInstanceTableHandler.TABLE_NAME).where(eq("id", entity.getProcessInstanceId())) .onlyIf(eq("version", entity.getRevision())), entity.getProcessInstanceId()); session.batchShouldNotLock(entity.getProcessInstanceId()); } else { session.addStatement(QueryBuilder.delete().mapElt("executions", entity.getId()) .from(ProcessInstanceTableHandler.TABLE_NAME).where(eq("id", entity.getProcessInstanceId())), entity.getProcessInstanceId()); } for(IndexHandler<ExecutionEntity> index:indexHandlers.values()){ session.addIndexStatement(index.getDeleteStatement(session,entity), entity.getProcessInstanceId()); } }
public void perform(CassandraPersistenceSession session, Object parameter, BatchStatement flush) { String deploymentId = (String) parameter; Session s = session.getSession(); List<Row> processDefinitionsToDelete = s.execute(QueryBuilder.select("id", "key", "version").from(ProcessDefinitionTableHandler.TABLE_NAME).where(eq("deployment_id", deploymentId))).all(); List<String> ids = new ArrayList<String>(); for (Row processDefinitionToDelete : processDefinitionsToDelete) { ids.add(processDefinitionToDelete.getString("id")); flush.add(QueryBuilder.delete().all().from(ProcessDefinitionTableHandler.TABLE_NAME_IDX_VERSION) .where(eq("key", processDefinitionToDelete.getString("key"))) .and(eq("version", processDefinitionToDelete.getInt("version")))); } flush.add(QueryBuilder.delete().all().from(ProcessDefinitionTableHandler.TABLE_NAME).where(in("id", ids))); }
public Object selectOne(String statement, Object parameter) { LOG.log(Level.FINE, "selectOne for statement '"+statement+"' parameter: "+parameter.toString()); SingleResultQueryHandler<?> queryHandler = singleResultQueryHandlers.get(statement); if(queryHandler != null) { DbEntity result = queryHandler.executeQuery(this, parameter); fireEntityLoaded(result); return result; } else if ("selectTableCount".equals(statement)) { @SuppressWarnings("unchecked") String tableName = ((Map<String, String>) parameter).get("tableName"); return cassandraSession.execute(QueryBuilder.select().countAll().from(tableName)).one().getLong(0); } else { LOG.warning("unknown query "+statement); return null; } }