org.cassandraunit.utils.EmbeddedCassandraServerHelper Java Examples

The following examples show how to use org.cassandraunit.utils.EmbeddedCassandraServerHelper. 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: EmbeddedCassandraStoreFactory.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private Session createEmbeddedCassandra() {
    // Disable fsync for a massive speedup on old platters. This improves boot time by a few seconds.
    System.setProperty("cassandra.unsafesystem", "true");

    try {
        File cassandraTmpDir = Files.createTempDir();
        EmbeddedCassandraServerHelper.startEmbeddedCassandra(CASSANDRA_CONFIG, cassandraTmpDir.getAbsolutePath(), STARTUP_TIMEOUT);
    } catch (Exception e) {
        throw new IllegalStateException("Cannot initialize the embedded Cassandra", e);
    }

    Session session = EmbeddedCassandraServerHelper.getSession();
    session.execute("CREATE KEYSPACE " + CASSANDRA_KEYSPACE + " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 3 }");
    session.execute("USE " + CASSANDRA_KEYSPACE);

    CQLDataLoader dataLoader = new CQLDataLoader(session);
    dataLoader.load(new ClassPathCQLDataSet(CASSANDRA_SCHEMA, "Titus"));

    return session;
}
 
Example #2
Source File: Cassandra.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
@Override
protected void before() throws Throwable {

	if (runtimeMode == RuntimeMode.REQUIRE_RUNNING_INSTANCE) {
		if (!CassandraSocket.isConnectable(getHost(), getPort())) {
			throw new AssumptionViolatedException(
					String.format("Cassandra is not reachable at %s:%s.", getHost(), getPort()));
		}
	}

	if (runtimeMode == RuntimeMode.EMBEDDED_IF_NOT_RUNNING) {
		if (CassandraSocket.isConnectable(getHost(), getPort())) {
			return;
		}
	}

	EmbeddedCassandraServerHelper.startEmbeddedCassandra("embedded-cassandra.yaml", "target/embeddedCassandra",
			TimeUnit.SECONDS.toMillis(60));
	super.before();
}
 
Example #3
Source File: CassandraInterpreterTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_display_statistics_for_non_select_statement() throws Exception {
  //Given
  String query = "USE zeppelin;\nCREATE TABLE IF NOT EXISTS no_select(id int PRIMARY KEY);";
  final String rawResult = reformatHtml(readTestResource(
          "/scalate/NoResultWithExecutionInfo.html"));

  //When
  final InterpreterResult actual = interpreter.interpret(query, intrContext);
  final int port = EmbeddedCassandraServerHelper.getNativeTransportPort();
  final String address = EmbeddedCassandraServerHelper.getHost();
  //Then
  final String expected = rawResult.replaceAll("TRIED_HOSTS", address + ":" + port)
          .replaceAll("QUERIED_HOSTS", address + ":" + port);

  assertThat(actual.code()).isEqualTo(Code.SUCCESS);
  assertThat(reformatHtml(actual.message().get(0).getData())).isEqualTo(expected);
}
 
Example #4
Source File: CassandraExtension.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Extract {@link CassandraDaemon} instance using reflection. It will be used
 * to shutdown the cluster
 */
private static CassandraDaemon extractDaemon() {
  try {
    Field field = EmbeddedCassandraServerHelper.class.getDeclaredField("cassandraDaemon");
    field.setAccessible(true);
    CassandraDaemon daemon = (CassandraDaemon) field.get(null);

    if (daemon == null) {
      throw new IllegalStateException("Cassandra daemon was not initialized by "
          + EmbeddedCassandraServerHelper.class.getSimpleName());
    }
    return daemon;
  } catch (NoSuchFieldException | IllegalAccessException e) {
    throw new RuntimeException(e);
  }
}
 
Example #5
Source File: ColumnFamilyApp.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String... args) throws Exception {

        EmbeddedCassandraServerHelper.startEmbeddedCassandra();

        ColumnConfiguration configuration = new CassandraConfiguration();
        try(ColumnFamilyManagerFactory entityManagerFactory = configuration.get()) {
            ColumnFamilyManager entityManager = entityManagerFactory.get(KEY_SPACE);
            ColumnEntity columnEntity = ColumnEntity.of(COLUMN_FAMILY);
            Column key = Columns.of("id", 10L);
            Column name = Columns.of("name", "JNoSQL in Acion");
            columnEntity.add(key);
            columnEntity.add(name);
            ColumnEntity saved = entityManager.insert(columnEntity);
            System.out.println(saved);
        }

        EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
        EmbeddedCassandraServerHelper.stopEmbeddedCassandra();
    }
 
Example #6
Source File: CassandraClientTestBase.java    From vertx-cassandra-client with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startEmbeddedCassandra() throws Exception {
  String version = System.getProperty("java.version");
  // this statement can be removed only when this issue[https://github.com/jsevellec/cassandra-unit/issues/249] will be resolved
  if (!version.startsWith("1.8")) {
    throw new IllegalStateException("Only Java 8 is allowed for running tests. Your java version: " + version);
  }
  EmbeddedCassandraServerHelper.startEmbeddedCassandra();
}
 
Example #7
Source File: CassandraTemplateIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
    EmbeddedCassandraServerHelper.startEmbeddedCassandra();
    final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
    LOGGER.info("Server Started at 127.0.0.1:9142... ");
    final Session session = cluster.connect();
    session.execute(KEYSPACE_CREATION_QUERY);
    session.execute(KEYSPACE_ACTIVATE_QUERY);
    LOGGER.info("KeySpace created and activated.");
    Thread.sleep(5000);
}
 
Example #8
Source File: CassandraTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@After
public void after() {
  if (isJdkSupported) {
    try {
      EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
    }
    catch (final Exception e) {
      logger.log(Level.WARNING, e.getMessage(), e);
    }
  }
}
 
Example #9
Source File: CassandraTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Before
public void before(final MockTracer tracer) throws Exception {
  if (isJdkSupported) {
    tracer.reset();
    EmbeddedCassandraServerHelper.startEmbeddedCassandra();
    //EmbeddedCassandraServerHelper.getSession();
  }
}
 
Example #10
Source File: CassandraInterpreterTest.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_execute_statement_with_timestamp_option() throws Exception {
  //Given
  String statement1 = "INSERT INTO zeppelin.ts(key,val) VALUES('k','v1');";
  String statement2 = "@timestamp=15\n" +
          "INSERT INTO zeppelin.ts(key,val) VALUES('k','v2');";

  CqlSession session = EmbeddedCassandraServerHelper.getSession();
  // Insert v1 with current timestamp
  interpreter.interpret(statement1, intrContext);
  System.out.println("going to read data from zeppelin.ts;");
  session.execute("SELECT val FROM zeppelin.ts LIMIT 1")
          .forEach(x -> System.out.println("row " + x ));

  Thread.sleep(1);

  //When
  // Insert v2 with past timestamp
  interpreter.interpret(statement2, intrContext);
  System.out.println("going to read data from zeppelin.ts;");
  session.execute("SELECT val FROM zeppelin.ts LIMIT 1")
          .forEach(x -> System.out.println("row " + x ));
  final String actual = session.execute("SELECT val FROM zeppelin.ts LIMIT 1").one()
          .getString("val");

  //Then
  assertThat(actual).isEqualTo("v1");
}
 
Example #11
Source File: CassandraInterpreterTest.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static synchronized void setUp() throws IOException, InterruptedException {
  System.setProperty("cassandra.skip_wait_for_gossip_to_settle", "0");
  System.setProperty("cassandra.load_ring_state", "false");
  System.setProperty("cassandra.initial_token", "0");
  System.setProperty("cassandra.num_tokens", "nil");
  System.setProperty("cassandra.allocate_tokens_for_local_replication_factor", "nil");
  EmbeddedCassandraServerHelper.startEmbeddedCassandra();
  CqlSession session = EmbeddedCassandraServerHelper.getSession();
  new CQLDataLoader(session).load(new ClassPathCQLDataSet("prepare_all.cql", "zeppelin"));

  Properties properties = new Properties();
  properties.setProperty(CASSANDRA_CLUSTER_NAME, EmbeddedCassandraServerHelper.getClusterName());
  properties.setProperty(CASSANDRA_COMPRESSION_PROTOCOL, "NONE");
  properties.setProperty(CASSANDRA_CREDENTIALS_USERNAME, "none");
  properties.setProperty(CASSANDRA_CREDENTIALS_PASSWORD, "none");

  properties.setProperty(CASSANDRA_LOAD_BALANCING_POLICY, "DEFAULT");
  properties.setProperty(CASSANDRA_RETRY_POLICY, "DEFAULT");
  properties.setProperty(CASSANDRA_RECONNECTION_POLICY, "DEFAULT");
  properties.setProperty(CASSANDRA_SPECULATIVE_EXECUTION_POLICY, "DEFAULT");

  properties.setProperty(CASSANDRA_POOLING_CONNECTION_PER_HOST_LOCAL, "2");
  properties.setProperty(CASSANDRA_POOLING_CONNECTION_PER_HOST_REMOTE, "1");
  properties.setProperty(CASSANDRA_POOLING_MAX_REQUESTS_PER_CONNECTION, "1024");

  properties.setProperty(CASSANDRA_POOLING_POOL_TIMEOUT_MILLIS, "5000");
  properties.setProperty(CASSANDRA_POOLING_HEARTBEAT_INTERVAL_SECONDS, "30");

  properties.setProperty(CASSANDRA_QUERY_DEFAULT_CONSISTENCY, "ONE");
  properties.setProperty(CASSANDRA_QUERY_DEFAULT_SERIAL_CONSISTENCY, "SERIAL");
  properties.setProperty(CASSANDRA_QUERY_DEFAULT_FETCH_SIZE, "5000");

  properties.setProperty(CASSANDRA_SOCKET_CONNECTION_TIMEOUT_MILLIS, "5000");
  properties.setProperty(CASSANDRA_SOCKET_READ_TIMEOUT_MILLIS, "12000");
  properties.setProperty(CASSANDRA_SOCKET_TCP_NO_DELAY, "true");

  properties.setProperty(CASSANDRA_HOSTS, EmbeddedCassandraServerHelper.getHost());
  properties.setProperty(CASSANDRA_PORT,
          Integer.toString(EmbeddedCassandraServerHelper.getNativeTransportPort()));
  properties.setProperty("datastax-java-driver.advanced.connection.pool.local.size", "1");
  interpreter = new CassandraInterpreter(properties);
  interpreter.open();
}
 
Example #12
Source File: NewtsInstance.java    From newts with Apache License 2.0 5 votes vote down vote up
@Override
public void before() throws Throwable {
    cassandraUnit = new MyCassandraCQLUnit(getDataSet(CASSANDRA_KEYSPACE, 1));
    cassandraUnit.before();
    host = EmbeddedCassandraServerHelper.getHost();
    port = EmbeddedCassandraServerHelper.getNativeTransportPort();
}
 
Example #13
Source File: Cassandra4Test.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@After
public void after() {
  try {
    EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
  }
  catch (final Exception e) {
    logger.log(Level.WARNING, e.getMessage(), e);
  }
}
 
Example #14
Source File: CassandraTransactionManagerTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startCassandra() {
    try {
        EmbeddedCassandraServerHelper.startEmbeddedCassandra();
        cqlSession = EmbeddedCassandraServerHelper.getSession();
        CqlOperations.createKeyspace(cqlSession).accept(CassandraTransactionManager.KEYSPACE);
        cqlSession.execute(CassandraTransactionManager.CREATE_TABLE);
    } catch (Exception exception) {
        exception.printStackTrace();
        throw new RuntimeException(exception);
    }
}
 
Example #15
Source File: ExampleCassandraAsyncEndpoint.java    From riposte-microservice-template with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("UnusedReturnValue")
private static Session startEmbeddedCassandra(boolean disableCassandra) {
    if (disableCassandra) {
        logger.warn("Embedded cassandra is NOT starting up because your app configuration explicitly requests "
                    + "that it be disabled.");
        return null;
    }

    if (cassandraSession == null) {
        File cassandraWorkDir = new File(embeddedClusterWorkDirectory);
        String cassandraWorkDirAbsolutePath = cassandraWorkDir.getAbsolutePath();
        if (!cassandraWorkDir.exists()) {
            logger.info("Creating the  embedded Cassandra folders...{}", cassandraWorkDirAbsolutePath);
            if (!cassandraWorkDir.mkdirs()) {
                throw new RuntimeException("Unable to create working directory " + cassandraWorkDirAbsolutePath);
            }
        }
        // Start embedded cassandra
        logger.info("Finished Creating the  embedded Cassandra folders...{}", cassandraWorkDirAbsolutePath);
        logger.info("Starting embedded Cassandra");

        try {
            EmbeddedCassandraServerHelper.startEmbeddedCassandra(cassandraYamlFile,
                                                                 embeddedClusterWorkDirectory);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }

        Cluster cassandraCluster = Cluster.builder()
                                          .addContactPoint(embeddedClusterContactPointHost)
                                          .withPort(embeddedClusterContactPointPort)
                                          .build();
        cassandraSession = cassandraCluster.connect();
    }

    return cassandraSession;
}
 
Example #16
Source File: AbstractCassandraTest.java    From gpmr with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startServer() throws InterruptedException, TTransportException, ConfigurationException, IOException, URISyntaxException  {
    EmbeddedCassandraServerHelper.startEmbeddedCassandra();
    Cluster cluster = new Cluster.Builder().addContactPoints("127.0.0.1").withPort(9142).build();
    Session session = cluster.connect();
    CQLDataLoader dataLoader = new CQLDataLoader(session);
    dataLoader.load(new ClassPathCQLDataSet("config/cql/create-tables.cql", true, CASSANDRA_UNIT_KEYSPACE));
    applyScripts(dataLoader, "config/cql/changelog/", "*.cql");
}
 
Example #17
Source File: _AbstractCassandraTest.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void startServer() throws InterruptedException, TTransportException, ConfigurationException, IOException {
    EmbeddedCassandraServerHelper.startEmbeddedCassandra();
    Cluster cluster = new Cluster.Builder().addContactPoints("127.0.0.1").withPort(9142).build();
    Session session = cluster.connect();
    CQLDataLoader dataLoader = new CQLDataLoader(session);
    dataLoader.load(new ClassPathCQLDataSet("config/cql/create-tables.cql", true, "cassandra_unit_keyspace"));
}
 
Example #18
Source File: EmbeddedCassandra.java    From conductor with Apache License 2.0 5 votes vote down vote up
private void startEmbeddedCassandra() throws Exception {
    try {
        EmbeddedCassandraServerHelper.startEmbeddedCassandra();
    } catch (Exception e) {
        LOGGER.error("Error starting embedded cassandra server", e);
        throw e;
    }
}
 
Example #19
Source File: BookRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
    EmbeddedCassandraServerHelper.startEmbeddedCassandra();
    final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
    LOGGER.info("Server Started at 127.0.0.1:9142... ");
    final Session session = cluster.connect();
    session.execute(KEYSPACE_CREATION_QUERY);
    session.execute(KEYSPACE_ACTIVATE_QUERY);
    LOGGER.info("KeySpace created and activated.");
    Thread.sleep(5000);
}
 
Example #20
Source File: CassandraClientTestBase.java    From vertx-cassandra-client with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown(TestContext testContext) {
  final Async async = testContext.async();
  client.close(testContext.asyncAssertSuccess(close -> async.countDown()));
  async.await();
  EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
  vertx.close(testContext.asyncAssertSuccess());
}
 
Example #21
Source File: CasquatchTestDaoBuilder.java    From casquatch with Apache License 2.0 5 votes vote down vote up
/**
 * Create DAO with embedded cassandra
 * @return builder using embedded cassandra
 */
public CasquatchTestDaoBuilder withEmbedded() {
    try {

        EmbeddedCassandraServerHelper.startEmbeddedCassandra(EmbeddedCassandraServerHelper.CASSANDRA_RNDPORT_YML_FILE, EmbeddedCassandraServerHelper.DEFAULT_STARTUP_TIMEOUT);
        log.info("Embedded Cassandra Started");
        return (CasquatchTestDaoBuilder) this.withBasicContactPoints(EmbeddedCassandraServerHelper.getHost()+":"+EmbeddedCassandraServerHelper.getNativeTransportPort())
                        .withBasicLoadBalancingPolicyLocalDatacenter("datacenter1")
                        .withBasicRequestConsistency("LOCAL_ONE");
    }
    catch(Exception e) {
        throw new DriverException(e);
    }
}
 
Example #22
Source File: EmbeddedCassandraConnectorTestBase.java    From debezium-incubator with Apache License 2.0 5 votes vote down vote up
/**
 * Drop all tables in TEST_KEYSPACE
 */
protected static void deleteTestKeyspaceTables() {
    Session session = EmbeddedCassandraServerHelper.getSession();
    Cluster cluster = EmbeddedCassandraServerHelper.getCluster();
    for (TableMetadata tm : cluster.getMetadata().getKeyspace(TEST_KEYSPACE).getTables()) {
        session.execute("DROP TABLE IF EXISTS " + keyspaceTable(tm.getName()));
    }
}
 
Example #23
Source File: SpringContextTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
    EmbeddedCassandraServerHelper.startEmbeddedCassandra();
    final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
    final Session session = cluster.connect();
    session.execute(KEYSPACE_CREATION_QUERY);
    session.execute(KEYSPACE_ACTIVATE_QUERY);
    Thread.sleep(5000);
}
 
Example #24
Source File: CqlQueriesIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
    EmbeddedCassandraServerHelper.startEmbeddedCassandra(25000);
    final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
    LOGGER.info("Server Started at 127.0.0.1:9142... ");
    final Session session = cluster.connect();
    session.execute(KEYSPACE_CREATION_QUERY);
    session.execute(KEYSPACE_ACTIVATE_QUERY);
    LOGGER.info("KeySpace created and activated.");
    Thread.sleep(5000);
}
 
Example #25
Source File: CassandraAuditRepositoryTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setup() {
    try {
        EmbeddedCassandraServerHelper.startEmbeddedCassandra("cassandra_test.yml");
        eventRepository = new CassandraBasedAuditRepository();
        Configuration atlasConf = new MapConfiguration(getClusterProperties());
        ((CassandraBasedAuditRepository) eventRepository).setApplicationProperties(atlasConf);
        ((CassandraBasedAuditRepository) eventRepository).start();

        ensureClusterCreation();
    }
    catch (Exception ex) {
        throw new SkipException("setup: failed!", ex);
    }
}
 
Example #26
Source File: TitusCassandraResource.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {
    // This improves boot time by a few seconds
    System.setProperty("cassandra.unsafesystem", "true");

    EmbeddedCassandraServerHelper.startEmbeddedCassandra(STARTUP_TIMEOUT);
}
 
Example #27
Source File: TitusCassandraResource.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public Session getSession() {
    if (session == null) {
        loadSchema();
        session = EmbeddedCassandraServerHelper.getSession();
    }
    return session;
}
 
Example #28
Source File: BookRepositoryIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@BeforeClass
public static void init() throws ConfigurationException, TTransportException, IOException, InterruptedException {
    // Start an embedded Cassandra Server
    EmbeddedCassandraServerHelper.startEmbeddedCassandra(20000L);
}
 
Example #29
Source File: KeyspaceRepositoryIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@AfterClass
public static void cleanup() {
    EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
}
 
Example #30
Source File: BookRepositoryIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@AfterClass
public static void cleanup() {
    EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
}