0

My application connects with Cassandra Cluster using Credentials. I am creating an instance of TestCassandra as follows:

val testCassandra = cqlStatementsOption.map(cqlStatements =>{
    new TestCassandra(factory,cqlStatements)})
    .getOrElse(new TestCassandra())

I suppose above statement will create a cluster. How can I specify a username and password for the created cluster ? One of my test cases is that application should not start if the username/password to cassandra database are incorrect.

Manu Chadha
  • 15,555
  • 19
  • 91
  • 184

1 Answers1

0
class SecureCassandra {

    private final TestCassandra testCassandra = new TestCassandra(createCassandraFactory(), createConnectionFactory(),
            CqlScript.classpath("init.cql"));

    private ConnectionFactory createConnectionFactory() {
        ClusterFactory clusterFactory = new ClusterFactory();
        clusterFactory.setUsername("cassandra");
        clusterFactory.setPassword("cassandra");
        return new ClusterConnectionFactory(clusterFactory);
    }

    private CassandraFactory createCassandraFactory() {
        LocalCassandraFactory cassandraFactory = new LocalCassandraFactory();
        cassandraFactory.setConfigurationFile(getClass().getResource("/cassandra-secure.yaml"));
        cassandraFactory.getJvmOptions().add("-Dcassandra.superuser_setup_delay_ms=0");
        return cassandraFactory;
    }

    @Test
    void testSecureCassandra() {
        this.testCassandra.start();

        try {
            Settings settings = this.testCassandra.getSettings();
            ClusterFactory clusterFactory = new ClusterFactory();
            clusterFactory.setUsername("test_user");
            clusterFactory.setPassword("test_pass");
            try (Cluster cluster = clusterFactory.create(settings)) {
                try (Session session = cluster.connect("test")) {
                    //
                }
            }

        }
        finally {
            this.testCassandra.stop();
        }
    }

}

init.cql:

CREATE KEYSPACE test  WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
CREATE ROLE test_user with SUPERUSER = true AND LOGIN = true and PASSWORD = 'test_pass';

cassandra-secure.yaml:

cluster_name: "Test Cluster"
num_tokens: 256
commitlog_sync: periodic
commitlog_sync_period_in_ms: 5000
seed_provider:
  - class_name: org.apache.cassandra.locator.SimpleSeedProvider
    parameters:
      - seeds: "127.0.0.1"
listen_address: localhost
rpc_address: localhost
start_native_transport: true
endpoint_snitch: SimpleSnitch
partitioner: org.apache.cassandra.dht.Murmur3Partitioner
authenticator: PasswordAuthenticator
role_manager: CassandraRoleManager
authorizer: CassandraAuthorizer
Dmytro Nosan
  • 161
  • 1
  • 5