Java Code Examples for com.datastax.driver.core.Cluster#connect()

The following examples show how to use com.datastax.driver.core.Cluster#connect() . 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: DefaultCommandContext.java    From titus-control-plane with Apache License 2.0 7 votes vote down vote up
public static CommandContext newCommandContext(CommandLine commandLine) {
    List<String> ips = StringExt.splitByComma(commandLine.getOptionValue("H"));
    int sourcePort = Integer.parseInt(commandLine.getOptionValue("p"));

    QueryOptions queryOptions = new QueryOptions()
            .setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);

    Cluster cluster = Cluster.builder()
            .addContactPoints((String[]) ips.toArray())
            .withPort(sourcePort)
            .withQueryOptions(queryOptions)
            .build();

    return new DefaultCommandContext(
            commandLine,
            cluster.newSession(),
            sourceKeySpace -> cluster.connect('"' + sourceKeySpace + '"'),
            targetKeySpace -> cluster.connect('"' + targetKeySpace + '"')
    ) {
        @Override
        public void shutdown() {
            cluster.close();
        }
    };
}
 
Example 2
Source File: CassandraMigrationAutoConfigurationTest.java    From cassandra-migration with MIT License 6 votes vote down vote up
@Test
public void shouldMigrateDatabaseWhenClusterGivenWithPrefix() {
    AnnotationConfigApplicationContext context =
            new AnnotationConfigApplicationContext();
    addEnvironment(context, "cassandra.migration.keyspace-name:test_keyspace");
    addEnvironment(context, "cassandra.migration.table-prefix:test");
    context.register(ClusterConfig.class, CassandraMigrationAutoConfiguration.class);
    context.refresh();
    Cluster cluster = context.getBean(Cluster.class);
    context.getBean(MigrationTask.class);
    try (Session session = cluster.connect(TEST_KEYSPACE)) {
        List<Row> rows = session.execute("SELECT * FROM test_schema_migration").all();
        assertThat(rows.size(), is(equalTo(1)));
        Row migration = rows.get(0);
        assertThat(migration.getBool("applied_successful"), is(true));
        assertThat(migration.getTimestamp("executed_at"), is(not(nullValue())));
        assertThat(migration.getString("script_name"), is(CoreMatchers.equalTo("001_create_person_table.cql")));
        assertThat(migration.getString("script"), startsWith("CREATE TABLE"));
    }
}
 
Example 3
Source File: KeyspaceFactory.java    From james-project with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public static boolean keyspaceExist(Cluster cluster, String keyspaceName) {
    try (Session session = cluster.connect(SYSTEM_SCHEMA)) {
        long numberOfKeyspaces = session.execute(select()
                .countAll()
                .from(KEYSPACES)
                .where(eq(KEYSPACE_NAME, keyspaceName)))
            .one()
            .getLong("count");

        if (numberOfKeyspaces > 1 || numberOfKeyspaces < 0) {
            throw new IllegalStateException(String.format("unexpected keyspace('%s') count being %d", keyspaceName, numberOfKeyspaces));
        }

        return numberOfKeyspaces == 1;
    }
}
 
Example 4
Source File: Sessions.java    From glowroot with Apache License 2.0 6 votes vote down vote up
static Session createSession() throws Exception {
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1")
            // long read timeout is sometimes needed on slow travis ci machines
            .withSocketOptions(new SocketOptions().setReadTimeoutMillis(30000))
            .withQueryOptions(getQueryOptions())
            .build();
    Session session = cluster.connect();
    session.execute("CREATE KEYSPACE IF NOT EXISTS test WITH REPLICATION ="
            + " { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }");
    session.execute("CREATE TABLE IF NOT EXISTS test.users"
            + " (id int PRIMARY KEY, fname text, lname text)");
    try {
        session.execute("TRUNCATE test.users");
    } catch (NoHostAvailableException e) {
        // sometimes slow, so give it a second chance
        session.execute("TRUNCATE test.users");
    }
    for (int i = 0; i < 10; i++) {
        session.execute("INSERT INTO test.users (id, fname, lname) VALUES (" + i + ", 'f" + i
                + "', 'l" + i + "')");
    }
    return session;
}
 
Example 5
Source File: CassandraSinkIT.java    From ingestion with Apache License 2.0 6 votes vote down vote up
@Test
public void initializeCqlTwice() throws TTransportException, IOException, InterruptedException {
  final InetSocketAddress contactPoint = CassandraTestHelper.getCassandraContactPoint();
  Cluster cluster = Cluster.builder()
      .addContactPointsWithPorts(Collections.singletonList(contactPoint))
      .build();
  Session session = cluster.connect();

  session.execute("DROP KEYSPACE IF EXISTS keyspaceTestCassandraSinkIT");
  Assert.assertNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT"));
  _do();
  Assert.assertNotNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT"));
  Assert.assertNotNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT")
      .getTable("tableTestCassandraSinkIT"));
  _do();
  Assert.assertNotNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT"));
  Assert.assertNotNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT")
      .getTable("tableTestCassandraSinkIT"));
  session.execute("DROP KEYSPACE IF EXISTS keyspaceTestCassandraSinkIT");

  session.close();
  cluster.close();
}
 
Example 6
Source File: CassandraServer.java    From deep-spark with Apache License 2.0 6 votes vote down vote up
private void initKeySpace() {
    if (startupCommands == null || startupCommands.length == 0) {
        return;
    }
    Cluster cluster = Cluster.builder().withPort(CASSANDRA_CQL_PORT)
            .addContactPoint(Constants.DEFAULT_CASSANDRA_HOST).build();

    try (Session session = cluster.connect()) {
        for (String command : startupCommands) {
            try {

                if (StringUtils.isNotEmpty(command)) {
                    session.execute(command);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
 
Example 7
Source File: JobSchedulerTest.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
@BeforeSuite
public static void initSuite() {
    Cluster cluster = Cluster.builder()
            .addContactPoints("127.0.0.01")
            .withQueryOptions(new QueryOptions().setRefreshSchemaIntervalMillis(0))
            .build();
    String keyspace = System.getProperty("keyspace", "hawkulartest");
    session = cluster.connect("system");
    rxSession = new RxSessionImpl(session);

    boolean resetdb = Boolean.valueOf(System.getProperty("resetdb", "true"));

    SchemaService schemaService = new SchemaService(session, keyspace);
    schemaService.run( resetdb);

    session.execute("USE " + keyspace);

    jobsService = new JobsService(rxSession);

    findFinishedJobs = session.prepare("SELECT job_id FROM finished_jobs_idx WHERE time_slice = ?");
    getActiveTimeSlices = session.prepare("SELECT distinct time_slice FROM active_time_slices");
    addActiveTimeSlice = session.prepare("INSERT INTO active_time_slices (time_slice) VALUES (?)");
}
 
Example 8
Source File: NamespaceOverrideMapper.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
private Session createSession() {
    Cluster.Builder clusterBuilder = new Cluster.Builder();

    String nodes = System.getProperty("hawkular.metrics.cassandra.nodes", "hawkular-cassandra");
    Arrays.stream(nodes.split(",")).forEach(clusterBuilder::addContactPoint);

    if (System.getProperty("hawkular.metrics.cassandra.use-ssl") != null && !System.getProperty("hawkular.metrics.cassandra.use-ssl").equals("false")) {
        SSLOptions sslOptions = null;
        try {
            String[] defaultCipherSuites = {"TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"};
            sslOptions = JdkSSLOptions.builder().withSSLContext(SSLContext.getDefault())
                    .withCipherSuites(defaultCipherSuites).build();
            clusterBuilder.withSSL(sslOptions);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SSL support is required but is not available in the JVM.", e);
        }
    }

    Cluster cluster = clusterBuilder.build();
    cluster.init();

    Session session = cluster.connect();

    return session;
}
 
Example 9
Source File: CassandraAuditRepositoryTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
private void ensureClusterCreation() throws InterruptedException {
    // Retry the connection until we either connect or timeout
    Cluster.Builder cassandraClusterBuilder = Cluster.builder();
    Cluster cluster =
            cassandraClusterBuilder.addContactPoint(CLUSTER_HOST).withClusterName(CLUSTER_NAME_TEST).withPort(CLUSTER_PORT)
                    .build();
    int retryCount = 0;

    while (retryCount < MAX_RETRIES) {
        try {
            Session cassSession = cluster.connect();
            if (cassSession.getState().getConnectedHosts().size() > 0) {
                cassSession.close();
                return;
            }
        } catch (Exception e) {
            Thread.sleep(1000);
        }
        retryCount++;
    }

    throw new SkipException("Unable to connect to embedded Cassandra after " + MAX_RETRIES + " seconds.");
}
 
Example 10
Source File: CQLSession.java    From cassandra-sidecar with Apache License 2.0 5 votes vote down vote up
/**
 * Provides a Session connected only to the local node from configuration. If null it means the the connection was
 * not able to be established. The session still might throw a NoHostAvailableException if the local host goes
 * offline or otherwise unavailable.
 *
 * @return Session
 */
@Nullable
public synchronized Session getLocalCql()
{
    Cluster cluster = null;
    try
    {
        if (localSession == null)
        {
            cluster = Cluster.builder()
                             .addContactPointsWithPorts(inet)
                             .withLoadBalancingPolicy(wlp)
                             .withQueryOptions(queryOptions)
                             .withReconnectionPolicy(reconnectionPolicy)
                             .withoutMetrics()
                             // tests can create a lot of these Cluster objects, to avoid creating HWTs and
                             // event thread pools for each we have the override
                             .withNettyOptions(nettyOptions)
                             .build();
            localSession = cluster.connect();
        }
    }
    catch (Exception e)
    {
        logger.debug("Failed to reach Cassandra", e);
        if (cluster != null)
        {
            try
            {
                cluster.close();
            }
            catch (Exception ex)
            {
                logger.debug("Failed to close cluster in cleanup", ex);
            }
        }
    }
    return localSession;
}
 
Example 11
Source File: CustomerEnrichedInfoCassandraRepo.java    From examples with Apache License 2.0 5 votes vote down vote up
protected void load() throws ClassNotFoundException, SQLException
{
  Cluster cluster = Cluster.builder().addContactPoint(dataWarehouseConfig.getHost()).build();
  Session session = cluster.connect(dataWarehouseConfig.getDatabase());

  List<SingleRecord> customerInfoList = Lists.newArrayList();

  try {
    ResultSet rs = session.execute("select id, imsi, isdn, imei, operatorName, operatorCode, deviceBrand, deviceModel from "
        + dataWarehouseConfig.getDatabase() + "." + dataWarehouseConfig.getTableName());

    Map<String, String> nameValueMap = new HashMap<String, String>();

    Iterator<Row> rowIter = rs.iterator();
    while (!rs.isFullyFetched() && rowIter.hasNext()) {
      Row row = rowIter.next();
      nameValueMap.put("id", row.getString(0));
      nameValueMap.put("imsi", row.getString(1));
      nameValueMap.put("isdn", row.getString(2));
      nameValueMap.put("imei", row.getString(3));
      nameValueMap.put("operatorName", row.getString(4));
      nameValueMap.put("operatorCode", row.getString(5));
      nameValueMap.put("deviceBrand", row.getString(6));
      nameValueMap.put("deviceModel", row.getString(7));

      SingleRecord record = new SingleRecord(nameValueMap);
      customerInfoList.add(record);
    }

  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    if (session != null) {
      session.close();
    }
  }

  customerInfoArray = customerInfoList.toArray(new SingleRecord[0]);
}
 
Example 12
Source File: CassandraWrapper.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static void waitForCassandra() throws InterruptedException {
    while (true) {
        Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
        try {
            cluster.connect();
            cluster.close();
            return;
        } catch (NoHostAvailableException e) {
            cluster.close();
            SECONDS.sleep(1);
        }
    }
}
 
Example 13
Source File: CassandraSessionFactory.java    From jmeter-cassandra with Apache License 2.0 5 votes vote down vote up
public static synchronized Session createSession(String sessionKey, Set<InetAddress> host, String keyspace, String username, String password, LoadBalancingPolicy loadBalancingPolicy) {

    instance = getInstance();
    Session session = instance.sessions.get(sessionKey);
      if (session == null) {

          Cluster.Builder cb = Cluster.builder()
                  .addContactPoints(host)
                  .withReconnectionPolicy(new ConstantReconnectionPolicy(10000)) ;

          if (loadBalancingPolicy != null ) {
              cb = cb.withLoadBalancingPolicy(loadBalancingPolicy);
          }

          if ( username != null && ! username.isEmpty()) {
              cb = cb.withCredentials(username, password);
          }

          Cluster cluster = cb.build();


          if (keyspace != null && !keyspace.isEmpty())
        session = cluster.connect(keyspace);
      else
        session = cluster.connect();

        instance.sessions.put(sessionKey, session);
    }
    return session;
  }
 
Example 14
Source File: HintsPollerTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Ignore
@Test
public void queryIsExecutedOnAllClusterNodesAndAlsoTheOldestHintIsPicked() {

    // ***** TODO: Get a cluster with 2 nodes. (RUN WITH PERFTEST LATER.....) ******
    // Ignoring this test for now

    // Insert hints on all the cluster nodes.
    Cluster cluster = Cluster.builder()
            .addContactPoint("127.0.0.1")
            .withPort(9164)
            .withLoadBalancingPolicy(new SelectedHostLoadBalancingPolicyForTest())
            .build();
    Metadata metadata = cluster.getMetadata();
    Session clusterSession = cluster.connect();

    long hintTimestamp = System.currentTimeMillis();
    for (Host host : metadata.getAllHosts()) {
        SelectedHostStatement selectedHostStatement = new SelectedHostStatement(new SimpleStatement(getInsertHintsQuery(hintTimestamp)), host);
        clusterSession.execute(selectedHostStatement);
        hintTimestamp = hintTimestamp + 10000;
    }

    // Now check if the query ran on EVERY node of the cluster.
    Assert.assertEquals(ALL_SELECTED_HOSTS.size(), 2);

    // Get the oldest hint Timestamp of the cluster
    ClusterHintsPoller clusterHintsPoller = new ClusterHintsPoller();
    HintsPollerResult oldestHintsInfo = clusterHintsPoller.getOldestHintsInfo(clusterSession);

    // Note: ?? - This will make the test fail even if one node is down or a connection problem with just one node.
    Assert.assertNotNull(oldestHintsInfo);
    Assert.assertEquals(oldestHintsInfo.getAllPolledHosts().size(), 2);

    long retrievedHintTimeStamp = oldestHintsInfo.getOldestHintTimestamp().or(Long.MAX_VALUE);

    Assert.assertEquals(retrievedHintTimeStamp, hintTimestamp);

    cluster.close();
    clusterSession.close();
}
 
Example 15
Source File: CassandraDataTypesIT.java    From ingestion with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws TTransportException, IOException,
    InterruptedException {
  final Context context = new Context();
  final InetSocketAddress contactPoint = CassandraTestHelper.getCassandraContactPoint();
  context.put("tables", KEYSPACE + "." + TABLE);
  context.put("hosts", contactPoint.getAddress().getHostAddress());
  context.put("batchSize", "1");
  context.put("consistency", "QUORUM");

  Cluster cluster = Cluster.builder()
      .addContactPointsWithPorts(Collections.singletonList(contactPoint))
      .build();
  Session session = cluster.connect();
  session.execute(
      "CREATE KEYSPACE IF NOT EXISTS keyspaceTest WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
  session.execute("CREATE TABLE if not exists keyspaceTest.tableTest ("
      + PRIMARY_KEY + " uuid, " + TEXT_FIELD + " text, "
      + VARCHAR_FIELD + " varchar, " + VARINT_FIELD
      + " varint, " + ASCII_FIELD + " ascii, "
      + BOOLEAN_FIELD + " boolean, " + DECIMAL_FIELD
      + " decimal, " + DOUBLE_FIELD + " double, "
      + FLOAT_FIELD + " float, " + INET_FIELD + " inet, "
      + INT_FIELD + " int, " + LIST_FIELD + " list<TEXT>, "
      + MAP_FIELD + " map<TEXT,INT>, " + SET_FIELD
      + " set<TEXT>, " + TIMESTAMP_FIELD + " timestamp, "
      + UUID_FIELD + " uuid, " + BIGINT_FIELD
      + " bigint, PRIMARY KEY (" + PRIMARY_KEY + "));");
  session.close();
  cluster.close();

  sink = new CassandraSink();
  sink.configure(context);

  Context channelContext = new Context();
  channelContext.put("capacity", "10000");
  channelContext.put("transactionCapacity", "200");
  channel = new MemoryChannel();
  channel.setName("junitChannel");
  Configurables.configure(channel, channelContext);
  sink.setChannel(channel);

  sink.start();
  headers = new HashMap<String, String>();
  headers.put(PRIMARY_KEY, UUID.randomUUID().toString());
}
 
Example 16
Source File: CassandraRegistryConfig.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
@Bean
public Session session() {

    try {

        final Cluster cluster = cluster();
        final Metadata metadata = cluster().getMetadata();

        LOGGER.info("Connected to cluster: {}\n", metadata.getClusterName());

        for (final Host host : metadata.getAllHosts()) {
            LOGGER.info("Datacenter: {}; Host: {}; Rack: {}\n", host.getDatacenter(), host.getAddress(),
                    host.getRack());
        }

        return cluster.connect(getKeyspace());

    } catch (NoHostAvailableException e) {
        LOGGER.info("NoHostAvailableException: {}", e.getMessage());

        return null;
    }

}
 
Example 17
Source File: CassandraLoader.java    From swblocks-decisiontree with Apache License 2.0 4 votes vote down vote up
private CassandraLoader(final Cluster cluster, final String keyspace, final String ruleSetName) {
    this.keyspace = keyspace;
    this.ruleSetName = ruleSetName;
    cluster.getConfiguration().getCodecRegistry().register(InstantCodec.instance);
    this.session = cluster.connect(this.keyspace);
}
 
Example 18
Source File: CassandraKeyUtilsTest.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateSchema() {

  String keyspace = "mykeyspace";
  String table = "mytable";

  String query = CassandraKeyUtils.primarykeyCQL(keyspace, table).toString();

  Map<String, Object> row0 =
      ImmutableMap.of(
          "column_name", "col0",
          "kind", "partition_key",
          "position", 0);

  PrimingRequest primingRequest =
      PrimingRequest.queryBuilder()
          .withQuery(query)
          .withThen(
              then()
                  .withColumnTypes(
                      column("column_name", TEXT), column("kind", TEXT), column("position", INT))
                  .withRows(row0))
          .build();
  primingClient.prime(primingRequest);

  Map<String, ?> row = ImmutableMap.of("col0", "primary key", "col1", "normal column");
  primingRequest =
      PrimingRequest.queryBuilder()
          .withQuery("select * from testing")
          .withThen(
              then()
                  .withColumnTypes(column("col0", VARCHAR), column("col1", VARCHAR))
                  .withRows(row))
          .build();
  primingClient.prime(primingRequest);

  Cluster cluster =
      Cluster.builder().addContactPoint("localhost").withPort(scassandra.getBinaryPort()).build();
  Session session = cluster.connect();

  CassandraRowMapperFn mapper =
      new CassandraRowMapperFn(
          session,
          ValueProvider.StaticValueProvider.of(keyspace),
          ValueProvider.StaticValueProvider.of(table));
  ResultSet rs = session.execute("select * from testing");
  Iterator<Row> rows = mapper.map(rs);
  Row next = rows.next();

  Field field = next.getSchema().getField("col0"); 
  assertEquals("0", field.getType().getMetadataString(CassandraRowMapperFn.KEY_ORDER_METADATA_KEY));
}
 
Example 19
Source File: CassandraTest.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
private static Session createSession() {
  final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
  return cluster.connect();
}
 
Example 20
Source File: CassandraZuulProxyStoreTest.java    From zuul-route-cassandra-spring-cloud-starter with Apache License 2.0 3 votes vote down vote up
@Bean
public CassandraOperations cassandraTemplate(Cluster cluster) {
    return new CassandraTemplate(cluster.connect("zuul"));
}