Java Code Examples for com.datastax.oss.driver.api.core.CqlSession#execute()

The following examples show how to use com.datastax.oss.driver.api.core.CqlSession#execute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CassandraStatements.java    From dynamo-cassandra-proxy with Apache License 2.0 6 votes vote down vote up
public Prepared(CqlSession session, String keyspace, String replicationStrategy) {
    this.keyspace = keyspace;
    this.session = session;
    this.replicationStrategy = replicationStrategy;

    create_keyspace = prepare(STMT_create_keyspace);

    //Ensure the dynamo keyspaceName exists
    try {
        session.execute(create_keyspace.bind());
    } catch(DriverTimeoutException de){
        try {
            Thread.sleep(10000);
            session.execute(create_keyspace.bind());
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    get_columns = prepare(STMT_get_columns);
}
 
Example 2
Source File: AbstractBackupTest.java    From cassandra-backup with Apache License 2.0 6 votes vote down vote up
protected long insert(CqlSession session) {

        try {
            session.execute(insertInto(KEYSPACE, TABLE)
                                .value(ID, literal("1"))
                                .value(DATE, literal(timeBased()))
                                .value(NAME, literal("stefan1"))
                                .build());

            session.execute(insertInto(TestEntity2.KEYSPACE_2, TestEntity2.TABLE_2)
                                .value(ID, literal("1"))
                                .value(DATE, literal(timeBased()))
                                .value(NAME, literal("stefan1"))
                                .build());

            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            logger.error("Exception while sleeping!");
        }

        return System.currentTimeMillis();
    }
 
Example 3
Source File: CassandraAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private static void createTable(CqlSession session, String keyspace, String tableName) {
    ResultSet execute = session.execute("select table_name from system_schema.tables where keyspace_name = '"+keyspace+"';");
    List<Row> all = execute.all();
    boolean found = false;
    for(Row row : all) {
        String table = row.getString("table_name");
        if (table.equalsIgnoreCase(tableName)) {
            found = true;
            break;
        }
    }
    if (!found) {
        session.execute(String.format(createTableTemplate, tableName));
        LOGGER.debug("Table {} has been created", tableName);
    }
}
 
Example 4
Source File: CassandraAppenderTest.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {

    System.setProperty("cassandra.boot_without_jna", "true");
    System.setProperty("cassandra.storagedir", "target/data/cassandra/embedded");

    cassandraDaemon = new CassandraDaemon(false);
    logger.info("starting cassandra daemon");
    cassandraDaemon.activate();
    logger.info("cassandra up and running");
    CqlSession session = getSession();
    session.execute(
            "CREATE KEYSPACE IF NOT EXISTS " + KEYSPACE
                    + " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
    session.close();
    logger.info("default Keyspace 'decanter' created");
}
 
Example 5
Source File: CasquatchTestDaoBuilder.java    From casquatch with Apache License 2.0 5 votes vote down vote up
/**
 * Use and create keyspace if required
 * @param keyspace name of keyspace
 * @return builder with keyspace
 */
public CasquatchTestDaoBuilder withTestKeyspace(String keyspace) {
    CqlSession session = this.session("system");
    try {
        session.execute(SimpleStatement.builder(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1}  AND durable_writes = true;",keyspace)).setExecutionProfileName("ddl").build());
        session.close();
        log.info("Keyspace Created: {}",keyspace);
    }
    catch(Exception e) {
        log.error("Error running withTestKeyspace",e);
    }
    return (CasquatchTestDaoBuilder) this.withBasicSessionKeyspace(keyspace);
}
 
Example 6
Source File: InputFormatGrakn.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private Map<TokenRange, Long> describeSplits(String keyspace, String table, TokenRange tokenRange, int splitSize, int splitSizeMb, CqlSession session) {
    String query = String.format("SELECT mean_partition_size, partitions_count " +
                    "FROM %s.%s " +
                    "WHERE keyspace_name = ? AND table_name = ? AND range_start = ? AND range_end = ?",
            SchemaConstants.SYSTEM_KEYSPACE_NAME,
            SystemKeyspace.SIZE_ESTIMATES);

    ResultSet resultSet = session.execute(session.prepare(query).bind(keyspace, table, tokenRange.getStart().toString(), tokenRange.getEnd().toString()));

    Row row = resultSet.one();

    long meanPartitionSize = 0;
    long partitionCount = 0;
    int splitCount = 0;

    if (row != null) {
        meanPartitionSize = row.getLong("mean_partition_size");
        partitionCount = row.getLong("partitions_count");

        splitCount = splitSizeMb > 0
                ? (int) (meanPartitionSize * partitionCount / splitSizeMb / 1024 / 1024)
                : (int) (partitionCount / splitSize);
    }

    // If we have no data on this split or the size estimate is 0,
    // return the full split i.e., do not sub-split
    // Assume smallest granularity of partition count available from CASSANDRA-7688
    if (splitCount == 0) {
        Map<TokenRange, Long> wrappedTokenRange = new HashMap<>();
        wrappedTokenRange.put(tokenRange, (long) 128);
        return wrappedTokenRange;
    }

    List<TokenRange> splitRanges = tokenRange.splitEvenly(splitCount);
    Map<TokenRange, Long> rangesWithLength = new HashMap<>();
    for (TokenRange range : splitRanges) {
        rangesWithLength.put(range, partitionCount / splitCount);
    }
    return rangesWithLength;
}
 
Example 7
Source File: CassandraAppender.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
private static void useKeyspace(CqlSession session, String keyspace) {
    try {
        session.execute("USE " + keyspace + ";");
    } catch (InvalidQueryException e) {
        session.execute("CREATE KEYSPACE IF NOT EXISTS " + keyspace + " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 3 };");
        session.execute("USE " + keyspace + ";");
    }
}
 
Example 8
Source File: CassandraAppenderTest.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    Marshaller marshaller = new JsonMarshaller();
    CassandraAppender appender = new CassandraAppender();
    Dictionary<String, Object> config = new Hashtable<>();
    config.put(CassandraAppender.CASSANDRA_PORT_PROPERTY, CASSANDRA_HOST);
    config.put(CassandraAppender.CASSANDRA_PORT_PROPERTY, CASSANDRA_PORT);
    config.put(CassandraAppender.KEYSPACE_PROPERTY, KEYSPACE);
    config.put(CassandraAppender.TABLE_PROPERTY, TABLE_NAME);
    appender.marshaller = marshaller;
    appender.activate(config);
    
    Map<String, Object> properties = new HashMap<>();
    properties.put(EventConstants.TIMESTAMP, TIMESTAMP);
    Event event = new Event(TOPIC, properties);
    
    appender.handleEvent(event);
    appender.deactivate();

    CqlSession session = getSession();

    ResultSet execute = session.execute("SELECT * FROM "+ KEYSPACE+"."+TABLE_NAME+";");
    List<Row> all = execute.all();
    Assert.assertEquals(1, all.size());
    assertThat(all, not(nullValue()));
    
    assertThat(all.get(0).getInstant("timeStamp").toEpochMilli(), is(TIMESTAMP));
    
    session.close();
}
 
Example 9
Source File: CassandraLog4JManager.java    From jesterj with Apache License 2.0 5 votes vote down vote up
protected CassandraLog4JManager(String name) {
  super(LoggerContext.getContext(), name);
  System.out.println(">>>> Creating CassandraLog4JManager");
  CassandraSupport cassandra = new CassandraSupport();

  Callable<Object> makeTables = new Callable<Object>() {


    @Override
    public Object call() throws Exception {
      System.out.println("Table and key space creation thread started");
      boolean tryAgain = true;
      int tryCount = 0;
      // ugly but effective fix for https://github.com/nsoft/jesterj/issues/1
      while(tryAgain) {
        try {
          CqlSession session = cassandra.getSession();
          session.execute(CREATE_LOG_KEYSPACE);
          session.execute(CREATE_LOG_TABLE);
          session.execute(CREATE_FT_TABLE);
          session.execute(FTI_STATUS_INDEX);
          session.execute(FTI_SCANNER_INDEX);
          tryAgain = false;
        } catch (Exception e) {
          tryCount++;
          // complain and die if we can't set up the tables in cassandra.
          e.printStackTrace();
          Thread.sleep(1000);
          if (tryCount > 10) {
            die(e);
            tryAgain = false;
          }
        }
      }
      return null;
    }
  };
  this.cassandraReady = cassandra.whenBooted(makeTables);
}
 
Example 10
Source File: ScannerImpl.java    From jesterj with Apache License 2.0 5 votes vote down vote up
@Override
public void activate() {
  super.activate();
  if (isRemembering() || isHashing()) {
    CqlSession session = getCassandra().getSession();
    List<DocKey> strandedDocs = new ArrayList<>();
    PreparedStatement preparedQuery = getCassandra().getPreparedQuery(RESET_PROCESSING_Q);
    BoundStatement statement =  preparedQuery.bind(getName());
    ResultSet procRs = session.execute(statement);
    strandedDocs.addAll(procRs.all().stream()
        .map((row) -> new DocKey(row.getString(0), row.getString(1))).collect(Collectors.toList()));
    preparedQuery = getCassandra().getPreparedQuery(RESET_ERROR_Q);
    statement = preparedQuery.bind(getName());
    ResultSet errorRs = session.execute(statement);
    strandedDocs.addAll(errorRs.all().stream()
        .map((row) -> new DocKey(row.getString(0), row.getString(1))).collect(Collectors.toList()));
    preparedQuery = getCassandra().getPreparedQuery(RESET_BATCHED_Q);
    statement = preparedQuery.bind(getName());
    ResultSet batchedRs = session.execute(statement);
    strandedDocs.addAll(batchedRs.all().stream()
        .map((row) -> new DocKey(row.getString(0), row.getString(1))).collect(Collectors.toList()));

    preparedQuery = getCassandra().getPreparedQuery(RESET_DOCS_U);
    // todo: batch
    for (DocKey docId : strandedDocs) {
      statement = preparedQuery.bind(docId.docid, docId.scanner);
      session.execute(statement);
    }

  }
}
 
Example 11
Source File: ScannerImpl.java    From jesterj with Apache License 2.0 5 votes vote down vote up
@Override
public void sendToNext(Document doc) {
  if (isRemembering()) {
    CqlSession session = getCassandra().getSession();
    PreparedStatement preparedQuery = getCassandra().getPreparedQuery(UPDATE_HASH_U);
    BoundStatement bind = preparedQuery.bind(doc.getHash(), doc.getId(), doc.getSourceScannerName());
    session.execute(bind);
  }
  superSendToNext(doc);
}
 
Example 12
Source File: CassandraExtensionTests.java    From embedded-cassandra with Apache License 2.0 4 votes vote down vote up
@Test
void testCassandra() {
	CqlSessionCassandraConnection connection = (CqlSessionCassandraConnection) extension.getCassandraConnection();
	CqlSession session = connection.getConnection();
	session.execute("SELECT * FROM test.roles");
}
 
Example 13
Source File: Cassandra4Test.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
private static void createKeyspace(final CqlSession session) {
  final PreparedStatement prepared = session.prepare("CREATE keyspace test WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1};");
  final BoundStatement bound = prepared.bind();
  session.execute(bound);
}
 
Example 14
Source File: ScannerImpl.java    From jesterj with Apache License 2.0 4 votes vote down vote up
/**
 * What to do when a document has been recognized as required for indexing.
 *
 * @param doc The document to be processed
 */
public void docFound(Document doc) {
  log.trace("{} found doc: {}", getName(), doc.getId());
  String id = doc.getId();
  Function<String, String> idFunction = getIdFunction();
  String result = idFunction.apply(id);
  String idField = doc.getIdField();
  doc.removeAll(idField);
  doc.put(idField, result);

  id = doc.getId();
  String status = null;
  String md5 = null;
  if (isRemembering()) {
    PreparedStatement preparedQuery = getCassandra().getPreparedQuery(FTI_CHECK_Q);
    CqlSession session = getCassandra().getSession();
    ResultSet statusRs = session.execute(preparedQuery.bind(id, getName()));
    if (statusRs.getAvailableWithoutFetching() > 0) {
      if (statusRs.getAvailableWithoutFetching() > 1 || !statusRs.isFullyFetched()) {
        log.error("FATAL: duplicate primary keys in cassandra table??");
        throw new RuntimeException("VERY BAD: duplicate primary keys in FTI table?");
      } else {
        Row next = statusRs.all().iterator().next();
        status = next.getString(0);
        log.trace("Found '{}' with status {}", id, status);
        if (isHashing()) {
          md5 = next.getString(1);
        }
      }
    }
  }
  // written with negated and's so I can defer doc.getHash() until we are sure we
  // need to check the hash.
  if (isRemembering() &&                                         // easier to read, let jvm optimize this check out
      status != null &&                                          // A status was found so we have seen this before
      Status.valueOf(status) != Status.DIRTY &&                  // not marked dirty
      !heuristicDirty(doc)                                       // not dirty by subclass logic
      ) {
    if (!isHashing()) {
      log.trace("{} ignoring previously seen document {}", getName(), id);
      return;
    }
    if (md5 != null) {
      String hash = doc.getHash();
      if (md5.equals(hash)) {
        log.trace("{} ignoring document with previously seen content {}", getName(), id);
        return;
      }
    }
  }
  sendToNext(doc);
}
 
Example 15
Source File: CassandraVersion.java    From spring-data-examples with Apache License 2.0 3 votes vote down vote up
/**
 * Retrieve the Cassandra release version.
 *
 * @param session must not be {@literal null}.
 * @return the release {@link Version}.
 */
public static Version getReleaseVersion(CqlSession session) {

	Assert.notNull(session, "Session must not be null");

	ResultSet resultSet = session.execute("SELECT release_version FROM system.local;");
	Row row = resultSet.one();

	return Version.parse(row.getString(0));
}