com.datastax.driver.core.exceptions.InvalidQueryException Java Examples

The following examples show how to use com.datastax.driver.core.exceptions.InvalidQueryException. 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: CassandraSessionDAO.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected void createTable() {
   try {
      cassandraSession.execute("select count(*) from " + tableName);
   } catch(InvalidQueryException ive) {
      String query =
            "CREATE TABLE " + tableName + " ( " +
                  "    id timeuuid PRIMARY KEY, " +
                  "    start_ts timestamp, " +
                  "    stop_ts timestamp, " +
                  "    last_access_ts timestamp, " +
                  "    timeout bigint, " +
                  "    expired boolean, " +
                  "    host varchar, " +
                  "    serialized_value blob " +
                  ") " +
                  "WITH " +
                  "    gc_grace_seconds = 86400 AND " +
                  "    compaction = {'class':'LeveledCompactionStrategy'};";
      cassandraSession.execute(query);
   }
}
 
Example #2
Source File: ConnectionManagerITCase.java    From Rhombus with MIT License 6 votes vote down vote up
@Test
public void testDropKeyspace() throws Exception {
	// Set up a connection manager and build the cluster and keyspace
	ConnectionManager cm = getConnectionManager();
	CKeyspaceDefinition definition = JsonUtil.objectFromJsonResource(CKeyspaceDefinition.class
			, this.getClass().getClassLoader(), "CKeyspaceTestData.js");
	assertNotNull(definition);
	cm.buildKeyspace(definition, false);

	// Drop the keyspace
	cm.dropKeyspace(definition.getName());

	// Make sure it is really dropped
	Session session = cm.getEmptySession();
	boolean caught = false;
	try {
		session.execute("USE " + definition.getName() + ";");
	} catch(InvalidQueryException e) {
		caught = true;
	}
	session.close();
	assertTrue(caught);

	cm.teardown();
}
 
Example #3
Source File: CassandraIntervalCollectionPersistor.java    From brein-time-utilities with Apache License 2.0 6 votes vote down vote up
protected void createKeySpace() {
    try {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Checking for key-space: " + this.keySpace);
        }

        getSession().execute("USE " + this.keySpace);
    } catch (final InvalidQueryException e) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Creating key-space: " + this.keySpace, e);
        } else if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Creating key-space: " + this.keySpace);
        }

        getSession().execute("CREATE KEYSPACE " + this.keySpace + " with replication = " + this.replicator);
        getSession().execute("USE " + this.keySpace);
    }
}
 
Example #4
Source File: NamespaceOverrideMapper.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
private Set<String> getTenants() {
    Set<String> tenants = new HashSet<>();
    ResultSet resultset = session.execute("SELECT * FROM system_schema.keyspaces WHERE keyspace_name = 'hawkular_metrics';");
    if (!resultset.iterator().hasNext()) {
        return tenants;
    }

    try {
        // An invalid query exception will occur if the table does not exists.
        // If the table does not exist, then no tenants have been stored yet so we just return the empty tenant set.
        ResultSet resultSet = session.execute("SELECT DISTINCT tenant_id,type from hawkular_metrics.metrics_idx;");

        Iterator<Row> ri = resultSet.iterator();
        while (ri.hasNext()) {
            Row row = ri.next();
            String tenant = row.getString("tenant_id");
            if (!tenant.startsWith("_") && !tenant.contains(":")) {
                tenants.add(tenant);
            }
        }
    } catch (InvalidQueryException iqe) {
        log.warn(iqe);
    }
    return tenants;
}
 
Example #5
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void addColumnIfNotExists(String tableName, String columnName, String cqlType)
        throws Exception {
    try {
        if (tableExists(tableName) && !columnExists(tableName, columnName)) {
            session.updateSchemaWithRetry(
                    "alter table " + tableName + " add " + columnName + " " + cqlType);
        }
    } catch (InvalidQueryException e) {
        // since there is not a real "if not exists" variant, if updateSchemaWithRetry times
        // out, then it will retry and fail (eventually) with "InvalidQueryException: Invalid
        // column name .. because it conflicts with an existing column"
        if (!columnExists(tableName, columnName)) {
            throw e;
        }
    }
}
 
Example #6
Source File: BookRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = InvalidQueryException.class)
public void whenDeletingATable_thenUnconfiguredTable() {
    bookRepository.createTable();
    bookRepository.deleteTable(BOOKS);

    session.execute("SELECT * FROM " + KEYSPACE_NAME + "." + BOOKS + ";");
}
 
Example #7
Source File: ExecutionEngine.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private boolean metadataTablesExist() {
   try {
      context.getSession().execute("select * from changeset");
      return true;
   } catch(InvalidQueryException iqe) {
      return false;
   }
}
 
Example #8
Source File: QueryCassandraTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorEmptyFlowFileAndExceptions() {
    setUpStandardProcessorConfig();

    // Run with empty flowfile
    testRunner.setIncomingConnection(true);
    processor.setExceptionToThrow(null);
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_SUCCESS, 1);
    testRunner.clearTransferState();

    // Test exceptions
    processor.setExceptionToThrow(new NoHostAvailableException(new HashMap<InetSocketAddress, Throwable>()));
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_RETRY, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(
            new ReadTimeoutException(new InetSocketAddress("localhost", 9042), ConsistencyLevel.ANY, 0, 1, false));
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_RETRY, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(
            new InvalidQueryException(new InetSocketAddress("localhost", 9042), "invalid query"));
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_FAILURE, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(new ProcessException());
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_FAILURE, 1);
}
 
Example #9
Source File: QueryCassandraTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorNoInputFlowFileAndExceptions() {
    setUpStandardProcessorConfig();

    // Test no input flowfile
    testRunner.setIncomingConnection(false);
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_SUCCESS, 1);
    testRunner.clearTransferState();

    // Test exceptions
    processor.setExceptionToThrow(new NoHostAvailableException(new HashMap<InetSocketAddress, Throwable>()));
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_RETRY, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(
            new ReadTimeoutException(new InetSocketAddress("localhost", 9042), ConsistencyLevel.ANY, 0, 1, false));
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_RETRY, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(
            new InvalidQueryException(new InetSocketAddress("localhost", 9042), "invalid query"));
    testRunner.run(1, true, true);
    // No files transferred to failure if there was no incoming connection
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_FAILURE, 0);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(new ProcessException());
    testRunner.run(1, true, true);
    // No files transferred to failure if there was no incoming connection
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_FAILURE, 0);
    testRunner.clearTransferState();
    processor.setExceptionToThrow(null);

}
 
Example #10
Source File: PutCassandraQLTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorInvalidQueryException() {
    setUpStandardTestConfig();

    // Test exceptions
    processor.setExceptionToThrow(
            new InvalidQueryException(new InetSocketAddress("localhost", 9042), "invalid query"));
    testRunner.enqueue("UPDATE users SET cities = [ 'New York', 'Los Angeles' ] WHERE user_id = 'coast2coast';");
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(PutCassandraQL.REL_FAILURE, 1);
    testRunner.clearTransferState();
}
 
Example #11
Source File: PutCassandraQLTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorBadTimestamp() {
    setUpStandardTestConfig();
    processor.setExceptionToThrow(
            new InvalidQueryException(new InetSocketAddress("localhost", 9042), "invalid timestamp"));
    testRunner.enqueue("INSERT INTO users (user_id, first_name, last_name, properties, bits, scaleset, largenum, scale, byteobject, ts) VALUES ?, ?, ?, ?, ?, ?, ?, ?, ?, ?",
            new HashMap<String, String>() {
                {
                    put("cql.args.1.type", "int");
                    put("cql.args.1.value", "1");
                    put("cql.args.2.type", "text");
                    put("cql.args.2.value", "Joe");
                    put("cql.args.3.type", "text");
                    // No value for arg 3 to test setNull
                    put("cql.args.4.type", "map<text,text>");
                    put("cql.args.4.value", "{'a':'Hello', 'b':'World'}");
                    put("cql.args.5.type", "list<boolean>");
                    put("cql.args.5.value", "[true,false,true]");
                    put("cql.args.6.type", "set<double>");
                    put("cql.args.6.value", "{1.0, 2.0}");
                    put("cql.args.7.type", "bigint");
                    put("cql.args.7.value", "20000000");
                    put("cql.args.8.type", "float");
                    put("cql.args.8.value", "1.0");
                    put("cql.args.9.type", "blob");
                    put("cql.args.9.value", "0xDEADBEEF");
                    put("cql.args.10.type", "timestamp");
                    put("cql.args.10.value", "not a timestamp");

                }
            });

    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(PutCassandraQL.REL_FAILURE, 1);
    testRunner.clearTransferState();
}
 
Example #12
Source File: CassandraCqlMapState.java    From storm-cassandra-cql with Apache License 2.0 5 votes vote down vote up
protected void checkCassandraException(Exception e) {
    _mexceptions.incr();
    if (e instanceof AlreadyExistsException ||
            e instanceof AuthenticationException ||
            e instanceof DriverException ||
            e instanceof DriverInternalError ||
            e instanceof InvalidConfigurationInQueryException ||
            e instanceof InvalidQueryException ||
            e instanceof InvalidTypeException ||
            e instanceof QueryExecutionException ||
            e instanceof QueryValidationException ||
            e instanceof ReadTimeoutException ||
            e instanceof SyntaxError ||
            e instanceof TraceRetrievalException ||
            e instanceof TruncateException ||
            e instanceof UnauthorizedException ||
            e instanceof UnavailableException ||
            e instanceof ReadTimeoutException ||
            e instanceof WriteTimeoutException ||
            e instanceof ReadFailureException ||
            e instanceof WriteFailureException ||
            e instanceof FunctionExecutionException) {
        throw new ReportedFailedException(e);
    } else {
        throw new RuntimeException(e);
    }
}
 
Example #13
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void dropColumnIfExists(String tableName, String columnName) throws Exception {
    try {
        if (columnExists(tableName, columnName)) {
            session.updateSchemaWithRetry("alter table " + tableName + " drop " + columnName);
        }
    } catch (InvalidQueryException e) {
        // since there is not a real "if exists" variant, if updateSchemaWithRetry times out,
        // then it will retry and fail (eventually) with "InvalidQueryException: Column .. was
        // not found in table"
        if (columnExists(tableName, columnName)) {
            throw e;
        }
    }
}
 
Example #14
Source File: CassandraHelper.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if Cassandra error occur because of prepared statement created in one session was used in another session.
 *
 * @param e Exception to check.
 * @return {@code true} in case of invalid usage of prepared statement.
 */
public static boolean isPreparedStatementClusterError(Throwable e) {
    while (e != null) {
        if (e instanceof InvalidQueryException && e.getMessage().contains(PREP_STATEMENT_CLUSTER_INSTANCE_ERROR))
            return true;

        e = e.getCause();
    }

    return false;
}
 
Example #15
Source File: CassandraHelper.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if Cassandra table absence error occur.
 *
 * @param e Exception to check.
 * @return {@code true} in case of table absence error.
 */
public static boolean isTableAbsenceError(Throwable e) {
    while (e != null) {
        if (e instanceof InvalidQueryException &&
            (TABLE_EXIST_ERROR1.matcher(e.getMessage()).matches() ||
                TABLE_EXIST_ERROR3.matcher(e.getMessage()).matches() ||
                KEYSPACE_EXIST_ERROR1.matcher(e.getMessage()).matches() ||
                KEYSPACE_EXIST_ERROR2.matcher(e.getMessage()).matches()))
            return true;

        if (e instanceof NoHostAvailableException && ((NoHostAvailableException) e).getErrors() != null) {
            NoHostAvailableException ex = (NoHostAvailableException)e;

            for (Map.Entry<InetSocketAddress, Throwable> entry : ex.getErrors().entrySet()) {
                Throwable error = entry.getValue();

                if (error instanceof DriverException &&
                    (error.getMessage().contains(TABLE_EXIST_ERROR2) ||
                         KEYSPACE_EXIST_ERROR3.matcher(error.getMessage()).matches()))
                    return true;
            }
        }

        e = e.getCause();
    }

    return false;
}
 
Example #16
Source File: CassandraHelper.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if Cassandra keyspace absence error occur.
 *
 * @param e Exception to check.
 * @return {@code true} in case of keyspace absence error.
 */
public static boolean isKeyspaceAbsenceError(Throwable e) {
    while (e != null) {
        if (e instanceof InvalidQueryException &&
            (KEYSPACE_EXIST_ERROR1.matcher(e.getMessage()).matches() ||
                KEYSPACE_EXIST_ERROR2.matcher(e.getMessage()).matches()))
            return true;

        e = e.getCause();
    }

    return false;
}
 
Example #17
Source File: Database.java    From cassandra-migration with MIT License 5 votes vote down vote up
/**
 * Attempts to acquire the lead on a migration through a LightWeight
 * Transaction.
 *
 * @param repositoryLatestVersion
 *            the latest version number in the migration repository
 * @return if taking the lead succeeded
 */
boolean takeLeadOnMigrations(int repositoryLatestVersion) {
    if (!isVersionAtLeastV2(cassandraVersion)) {
        // No LWT before Cassandra 2.0 so leader election can't happen
        return true;
    }

    while (repositoryLatestVersion > getVersion()) {
        try {
            LOGGER.debug("Trying to take lead on schema migrations");
            BoundStatement boundStatement = takeMigrationLeadStatement.bind(getKeyspaceName(), this.instanceId,
                    this.instanceAddress);
            ResultSet lwtResult = session.execute(boundStatement);

            if (lwtResult.wasApplied()) {
                LOGGER.debug("Took lead on schema migrations");
                tookLead = true;
                return true;
            }

            LOGGER.info("Schema migration is locked by another instance. Waiting for it to be released...");
            waitFor(TAKE_LEAD_WAIT_TIME);
        } catch (InvalidQueryException e1) {
            // A little redundant but necessary
            LOGGER.info("All required tables do not exist yet, waiting for them to be created...");
            waitFor(TAKE_LEAD_WAIT_TIME);
        }
    }

    return false;
}
 
Example #18
Source File: ErrorResultIntegrationTest.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldReturnInvalidResult() throws Exception {
  String message = "This is an invalid result";
  server.prime(when(query).then(invalid(message)));

  thrown.expect(InvalidQueryException.class);
  thrown.expectMessage(message);
  query();
}
 
Example #19
Source File: QueryCassandraTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorEmptyFlowFileAndExceptions() {
    setUpStandardProcessorConfig();

    // Run with empty flowfile
    testRunner.setIncomingConnection(true);
    processor.setExceptionToThrow(null);
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_SUCCESS, 1);
    testRunner.clearTransferState();

    // Test exceptions
    processor.setExceptionToThrow(new NoHostAvailableException(new HashMap<InetSocketAddress, Throwable>()));
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_RETRY, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(
            new ReadTimeoutException(new InetSocketAddress("localhost", 9042), ConsistencyLevel.ANY, 0, 1, false));
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_RETRY, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(
            new InvalidQueryException(new InetSocketAddress("localhost", 9042), "invalid query"));
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_FAILURE, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(new ProcessException());
    testRunner.enqueue("".getBytes());
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_FAILURE, 1);
}
 
Example #20
Source File: QueryCassandraTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorNoInputFlowFileAndExceptions() {
    setUpStandardProcessorConfig();

    // Test no input flowfile
    testRunner.setIncomingConnection(false);
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_SUCCESS, 1);
    testRunner.clearTransferState();

    // Test exceptions
    processor.setExceptionToThrow(new NoHostAvailableException(new HashMap<InetSocketAddress, Throwable>()));
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_RETRY, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(
            new ReadTimeoutException(new InetSocketAddress("localhost", 9042), ConsistencyLevel.ANY, 0, 1, false));
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_RETRY, 1);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(
            new InvalidQueryException(new InetSocketAddress("localhost", 9042), "invalid query"));
    testRunner.run(1, true, true);
    // No files transferred to failure if there was no incoming connection
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_FAILURE, 0);
    testRunner.clearTransferState();

    processor.setExceptionToThrow(new ProcessException());
    testRunner.run(1, true, true);
    // No files transferred to failure if there was no incoming connection
    testRunner.assertAllFlowFilesTransferred(QueryCassandra.REL_FAILURE, 0);
    testRunner.clearTransferState();
    processor.setExceptionToThrow(null);

}
 
Example #21
Source File: PutCassandraQLTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorInvalidQueryException() {
    setUpStandardTestConfig();

    // Test exceptions
    processor.setExceptionToThrow(
            new InvalidQueryException(new InetSocketAddress("localhost", 9042), "invalid query"));
    testRunner.enqueue("UPDATE users SET cities = [ 'New York', 'Los Angeles' ] WHERE user_id = 'coast2coast';");
    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(PutCassandraQL.REL_FAILURE, 1);
    testRunner.clearTransferState();
}
 
Example #22
Source File: PutCassandraQLTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorBadTimestamp() {
    setUpStandardTestConfig();
    processor.setExceptionToThrow(
            new InvalidQueryException(new InetSocketAddress("localhost", 9042), "invalid timestamp"));
    testRunner.enqueue("INSERT INTO users (user_id, first_name, last_name, properties, bits, scaleset, largenum, scale, byteobject, ts) VALUES ?, ?, ?, ?, ?, ?, ?, ?, ?, ?",
            new HashMap<String, String>() {
                {
                    put("cql.args.1.type", "int");
                    put("cql.args.1.value", "1");
                    put("cql.args.2.type", "text");
                    put("cql.args.2.value", "Joe");
                    put("cql.args.3.type", "text");
                    // No value for arg 3 to test setNull
                    put("cql.args.4.type", "map<text,text>");
                    put("cql.args.4.value", "{'a':'Hello', 'b':'World'}");
                    put("cql.args.5.type", "list<boolean>");
                    put("cql.args.5.value", "[true,false,true]");
                    put("cql.args.6.type", "set<double>");
                    put("cql.args.6.value", "{1.0, 2.0}");
                    put("cql.args.7.type", "bigint");
                    put("cql.args.7.value", "20000000");
                    put("cql.args.8.type", "float");
                    put("cql.args.8.value", "1.0");
                    put("cql.args.9.type", "blob");
                    put("cql.args.9.value", "0xDEADBEEF");
                    put("cql.args.10.type", "timestamp");
                    put("cql.args.10.value", "not a timestamp");

                }
            });

    testRunner.run(1, true, true);
    testRunner.assertAllFlowFilesTransferred(PutCassandraQL.REL_FAILURE, 1);
    testRunner.clearTransferState();
}
 
Example #23
Source File: CassandraSessionImplTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void executeFailureTest() {
    Session session1 = mock(Session.class);
    Session session2 = mock(Session.class);
    when(session1.prepare(any(String.class))).thenReturn(preparedStatement1);
    when(session2.prepare(any(String.class))).thenReturn(preparedStatement2);

    ResultSetFuture rsFuture = mock(ResultSetFuture.class);
    ResultSet rs = mock(ResultSet.class);
    Iterator it = mock(Iterator.class);
    when(it.hasNext()).thenReturn(true);
    when(it.next()).thenReturn(mock(Row.class));
    when(rs.iterator()).thenReturn(it);
    when(rsFuture.getUninterruptibly()).thenReturn(rs);
    /* @formatter:off */
    when(session1.executeAsync(any(Statement.class)))
        .thenThrow(new InvalidQueryException("You may have used a PreparedStatement that was created with another Cluster instance"))
        .thenThrow(new RuntimeException("this session should be refreshed / recreated"));
    when(session2.executeAsync(boundStatement1))
        .thenThrow(new InvalidQueryException("You may have used a PreparedStatement that was created with another Cluster instance"));
    when(session2.executeAsync(boundStatement2)).thenReturn(rsFuture);
    /* @formatter:on */

    Cluster cluster = mock(Cluster.class);
    when(cluster.connect()).thenReturn(session1).thenReturn(session2);
    when(session1.getCluster()).thenReturn(cluster);
    when(session2.getCluster()).thenReturn(cluster);

    Cluster.Builder builder = mock(Cluster.Builder.class);
    when(builder.build()).thenReturn(cluster);

    CassandraSessionImpl cassandraSession = new CassandraSessionImpl(builder, null,
            ConsistencyLevel.ONE, ConsistencyLevel.ONE, 0, mock(IgniteLogger.class));

    BatchExecutionAssistant<String, String> batchExecutionAssistant = new MyBatchExecutionAssistant();
    ArrayList<String> data = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        data.add(String.valueOf(i));
    }
    cassandraSession.execute(batchExecutionAssistant, data);

    verify(cluster, times(2)).connect();
    verify(session1, times(1)).prepare(any(String.class));
    verify(session2, times(1)).prepare(any(String.class));
    assertEquals(10, batchExecutionAssistant.processedCount());
}
 
Example #24
Source File: BatchTests.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
@Test(expected = InvalidQueryException.class)
public void testMixedInCounterBatch()
{
   sendBatch(BatchStatement.Type.COUNTER, true, true);
}
 
Example #25
Source File: BatchTests.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
@Test(expected = InvalidQueryException.class)
public void testMixedInLoggedBatch()
{
    sendBatch(BatchStatement.Type.LOGGED, true, true);
}
 
Example #26
Source File: BatchTests.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
@Test(expected = InvalidQueryException.class)
public void testMixedInUnLoggedBatch()
{
    sendBatch(BatchStatement.Type.UNLOGGED, true, true);
}
 
Example #27
Source File: BatchTests.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
@Test(expected = InvalidQueryException.class)
public void testNonCounterInCounterBatch()
{
    sendBatch(BatchStatement.Type.COUNTER, false, true);
}
 
Example #28
Source File: BatchTests.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
@Test(expected = InvalidQueryException.class)
public void testCounterInLoggedBatch()
{
    sendBatch(BatchStatement.Type.LOGGED, true, false);
}