congrats Icon
New! Announcing Tabnine Chat Beta
Learn More
Tabnine Logo
Cluster.close
Code IndexAdd Tabnine to your IDE (free)

How to use
close
method
in
com.datastax.driver.core.Cluster

Best Java code snippets using com.datastax.driver.core.Cluster.close (Showing top 20 results out of 837)

Refine searchRefine arrow

  • Cluster.Builder.build
origin: kaaproject/kaa

 /**
  * Add field use_raw_configuration_schema to endpointProfile that used to support devices using
  * SDK version 0.9.0
  */
 public void transform() {
  //mongo
  MongoClient client = new MongoClient(host);
  MongoDatabase database = client.getDatabase(dbName);
  MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile");
  endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false)));

  //cassandra
  Cluster cluster = Cluster.builder().addContactPoint(host).build();
  Session session = cluster.connect(dbName);
  session.execute("ALTER TABLE ep_profile ADD use_raw_schema boolean");
  session.close();
  cluster.close();

 }
}
origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Validates that a Cluster that was never able to successfully establish connection a session can
 * be closed properly.
 *
 * @test_category connection
 * @expected_result Cluster closes within 1 second.
 */
@Test(groups = "short")
public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
 Cluster cluster =
   Cluster.builder()
     .addContactPointsWithPorts(new InetSocketAddress("127.0.0.1", 65534))
     .withNettyOptions(nonQuietClusterCloseOptions)
     .build();
 try {
  cluster.connect();
  fail("Should not have been able to connect.");
 } catch (NoHostAvailableException e) {
  // Expected.
  CloseFuture closeFuture = cluster.closeAsync();
  try {
   closeFuture.get(1, TimeUnit.SECONDS);
  } catch (TimeoutException e1) {
   fail("Close Future did not complete quickly.");
  }
 } finally {
  cluster.close();
 }
}
origin: spring-projects/spring-data-examples

@Override
protected void before() throws Throwable {
  dependency.before();
  Cluster cluster = Cluster.builder().addContactPoint(getHost()).withPort(getPort())
      .withNettyOptions(new NettyOptions() {
        @Override
        public void onClusterClose(EventLoopGroup eventLoopGroup) {
          eventLoopGroup.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS).syncUninterruptibly();
        }
      }).build();
  Session session = cluster.newSession();
  try {
    if (requiredVersion != null) {
      Version cassandraReleaseVersion = CassandraVersion.getReleaseVersion(session);
      if (cassandraReleaseVersion.isLessThan(requiredVersion)) {
        throw new AssumptionViolatedException(
            String.format("Cassandra at %s:%s runs in Version %s but we require at least %s", getHost(), getPort(),
                cassandraReleaseVersion, requiredVersion));
      }
    }
    session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s \n"
        + "WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };", keyspaceName));
  } finally {
    session.close();
    cluster.close();
  }
}
origin: jooby-project/jooby

Cluster cluster = builder.build();
   .onFailure(x -> log.error("session.close() resulted in exception", x));
 cluster.close();
origin: pulsarIO/realtime-analytics

private void connectInternal() {
  try {
    Cluster cluster = config.createBuilder().build();
    cassandraSession = cluster.connect(keySpace);
    cassandraMetrics = cluster.getMetrics();
    connected.set(true);
  } catch (Exception e) {
    LOGGER.error("Error connection to Cassandra" + e.getMessage());
    if (pool != null) {
      pool.shutdownNow();
      pool = null;
    }
    if (cassandraSession != null) {
      cassandraSession.close();
      if (cassandraSession.getCluster() != null)
        cassandraSession.getCluster().close();
    }
    connected.set(false);
  }
}
origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Ensures that if the core connection pool is full that borrowConnection will create and use a
 * new connection.
 *
 * @jira_ticket JAVA-419
 * @test_category connection:connection_pool
 * @since 2.0.10, 2.1.6
 */
@Test(groups = "short")
public void should_add_extra_connection_when_core_full() throws Exception {
 Cluster cluster = createClusterBuilder().build();
 List<MockRequest> allRequests = newArrayList();
 try {
  HostConnectionPool pool = createPool(cluster, 1, 2);
  Connection.Factory factory = spy(cluster.manager.connectionFactory);
  cluster.manager.connectionFactory = factory;
  Connection core = pool.connections.get(0);
  // Fill core connection + 1
  List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
  assertBorrowedConnection(requests, core);
  allRequests.addAll(requests);
  allRequests.add(MockRequest.send(pool));
  // Reaching the threshold should have triggered the creation of an extra one
  verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
  assertPoolSize(pool, 2);
 } finally {
  MockRequest.completeAll(allRequests);
  cluster.close();
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Validates that when a Cluster is initialized that {@link
 * SpeculativeExecutionPolicy#init(Cluster)} is called and that when a Cluster is closed {@link
 * SpeculativeExecutionPolicy#close()} is called.
 *
 * @test_category queries:speculative_execution
 * @expected_result init and close are called on cluster init and close.
 * @jira_ticket JAVA-796
 * @since 2.0.11, 2.1.7, 2.2.1
 */
@Test(groups = "short")
public void should_init_and_close_policy_on_cluster() {
 SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class);
 Cluster cluster =
   Cluster.builder()
     .addContactPoints(scassandras.address(2).getAddress())
     .withPort(scassandras.getBinaryPort())
     .withSpeculativeExecutionPolicy(mockPolicy)
     .build();
 verify(mockPolicy, times(0)).init(cluster);
 verify(mockPolicy, times(0)).close();
 try {
  cluster.init();
  verify(mockPolicy, times(1)).init(cluster);
 } finally {
  cluster.close();
  verify(mockPolicy, times(1)).close();
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

Cluster cluster = createClusterBuilder().build();
List<MockRequest> allRequests = newArrayList();
try {
 cluster.close();
origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Ensures that if a fixed-sized pool has filled its core connections and reached a number of
 * requests to cause it to be enqueued, that if the request is not serviced within 100ms, a
 * BusyPoolException is raised with a timeout.
 *
 * @jira_ticket JAVA-1371
 * @test_category connection:connection_pool
 * @since 3.0.7 3.1.4 3.2.0
 */
@Test(groups = "short")
public void should_reject_if_enqueued_and_timeout_reached() {
 Cluster cluster = createClusterBuilder().build();
 List<MockRequest> allRequests = newArrayList();
 try {
  HostConnectionPool pool = createPool(cluster, 1, 1);
  List<MockRequest> requests = MockRequest.sendMany(128, pool);
  allRequests.addAll(requests);
  // pool is now full, this request will be enqueued
  MockRequest failedBorrow = MockRequest.send(pool, 100, 128);
  try {
   failedBorrow.getConnection();
   fail("Expected a BusyPoolException");
  } catch (BusyPoolException e) {
   assertThat(e).hasMessageContaining("timed out");
  }
 } finally {
  MockRequest.completeAll(allRequests);
  cluster.close();
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

/**
 * When no consistency level is defined the default of LOCAL_ONE should be used.
 *
 * @test_category consistency
 */
@Test(groups = "short")
public void should_use_global_default_cl_when_none_specified() throws Throwable {
 // Build a cluster with no CL level set in the query options.
 Cluster cluster = builder().build();
 try {
  Session session = cluster.connect();
  // Construct unique simple statement query, with no CL defined.
  // Check to ensure
  String queryString = "default_cl";
  Query clQuery = executeSimple(session, queryString, null, null);
  assertTrue(clQuery.getConsistency().equals(ConsistencyLevel.LOCAL_ONE.toString()));
  // Check prepared statement default CL
  String prepareString = "prepared_default_cl";
  PreparedStatementExecution pse = executePrepared(session, prepareString, null, null);
  assertTrue(pse.getConsistency().equals(ConsistencyLevel.LOCAL_ONE.toString()));
  // Check batch statement default CL
  String batchStateString = "batch_default_cl";
  BatchExecution batch = executeBatch(session, batchStateString, null, null);
  assertTrue(batch.getConsistency().equals(ConsistencyLevel.LOCAL_ONE.toString()));
 } finally {
  cluster.close();
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

Cluster cluster = builder().build();
try {
 Session session = cluster.connect();
 assertTrue(batch.getConsistency().equals(cl.toString()));
} finally {
 cluster.close();
origin: com.datastax.cassandra/cassandra-driver-core

@Test(groups = "short")
public void should_init_cluster_and_session_if_needed() throws Exception {
 // For this test we need an uninitialized cluster, so we can't reuse the one provided by the
 // parent class. Rebuild a new one with the same (unique) host.
 Host host = cluster().getMetadata().allHosts().iterator().next();
 Cluster cluster2 =
   register(
     Cluster.builder()
       .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress()))
       .build());
 try {
  Session session2 = cluster2.newSession();
  // Neither cluster2 nor session2 are initialized at this point
  assertThat(cluster2.manager.metadata).isNull();
  ResultSetFuture future = session2.executeAsync("select release_version from system.local");
  Row row = Uninterruptibles.getUninterruptibly(future).one();
  assertThat(row.getString(0)).isNotEmpty();
 } finally {
  cluster2.close();
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

  builder().withQueryOptions(new QueryOptions().setConsistencyLevel(cl)).build();
try {
 Session session = cluster.connect();
 assertTrue(batch.getConsistency().equals(cl.toString()));
} finally {
 cluster.close();
origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Ensures that if a connection on a host is lost but other connections remain intact in the Pool
 * that the host is not marked down.
 *
 * @jira_ticket JAVA-544
 * @test_category connection:connection_pool
 * @since 2.0.11
 */
@Test(groups = "short")
public void should_keep_host_up_when_one_connection_lost() throws Exception {
 Cluster cluster = createClusterBuilder().build();
 try {
  HostConnectionPool pool = createPool(cluster, 2, 2);
  Connection core0 = pool.connections.get(0);
  Connection core1 = pool.connections.get(1);
  // Drop a connection and ensure the host stays up.
  currentClient.disableListener();
  currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
  Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
  // connection 0 should be down, while connection 1 and the Host should remain up.
  assertThat(core0.isClosed()).isTrue();
  assertThat(core1.isClosed()).isFalse();
  assertThat(pool.connections).doesNotContain(core0);
  assertThat(cluster).host(1).hasState(Host.State.UP);
  assertThat(cluster).hasOpenControlConnection();
 } finally {
  cluster.close();
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

@Test(groups = "short")
public void should_count_inflight_requests_metrics() {
 sCluster
   .node(1)
   .primingClient()
   .prime(
     PrimingRequest.queryBuilder()
       .withQuery("mock query")
       .withThen(then().withFixedDelay(100000L))
       .build());
 Cluster cluster = null;
 try {
  cluster = builder().build();
  Session session = cluster.connect();
  assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0);
  session.executeAsync("mock query");
  session.executeAsync("mock query");
  assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(2);
 } finally {
  if (cluster != null) {
   cluster.close();
  }
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

 @Test(groups = "short")
 public void should_countdown_inflight_requests_metrics() {
  sCluster
    .node(1)
    .primingClient()
    .prime(PrimingRequest.queryBuilder().withQuery("mock query").withThen(then()).build());

  Cluster cluster = null;
  try {
   cluster = builder().build();
   Session session = cluster.connect();

   assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0);
   session.executeAsync("mock query").getUninterruptibly();
   session.executeAsync("mock query").getUninterruptibly();
   assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0);

  } finally {
   if (cluster != null) {
    cluster.close();
   }
  }
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

 private void deleteNode2RpcAddressFromNode1() throws Exception {
  InetSocketAddress firstHost = ccm().addressOfNode(1);
  Cluster cluster =
    register(
      Cluster.builder()
        .addContactPoints(firstHost.getAddress())
        .withPort(ccm().getBinaryPort())
        // ensure we will only connect to node1
        .withLoadBalancingPolicy(
          new WhiteListPolicy(
            Policies.defaultLoadBalancingPolicy(), Lists.newArrayList(firstHost)))
        .build());
  Session session = cluster.connect();
  String deleteStmt =
    String.format(
      "DELETE rpc_address FROM system.peers WHERE peer = '%s'",
      ccm().addressOfNode(2).getHostName());
  session.execute(deleteStmt);
  session.close();
  cluster.close();
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

public void useNamedValuesWithProtocol(ProtocolVersion version) {
 Cluster vCluster =
   createClusterBuilder()
     .addContactPoints(getContactPoints())
     .withPort(ccm().getBinaryPort())
     .withProtocolVersion(version)
     .build();
 try {
  Session vSession = vCluster.connect(this.keyspace);
  // Given - A simple statement with named parameters.
  SimpleStatement statement =
    new SimpleStatement(
      "SELECT * FROM users WHERE id = :id", ImmutableMap.<String, Object>of("id", 1));
  // When - Executing that statement against a Cluster instance using Protocol Version V2.
  vSession.execute(statement).one();
  // Then - Should throw an UnsupportedFeatureException
 } finally {
  vCluster.close();
 }
}
origin: com.datastax.cassandra/cassandra-driver-core

   .withPort(sCluster.getBinaryPort())
   .withLoadBalancingPolicy(policy)
   .build();
cluster.close();
sCluster.stop();
origin: com.datastax.cassandra/cassandra-driver-core

    .addContactPointsWithPorts(new InetSocketAddress("127.0.0.1", 65534))
    .withNettyOptions(nonQuietClusterCloseOptions)
    .build();
try {
 cluster.connect();
 cluster.close();
com.datastax.driver.coreClusterclose

Javadoc

Initiates a shutdown of this cluster instance and blocks until that shutdown completes.

This method is a shortcut for closeAsync().get().

Popular methods of Cluster

  • connect
    Creates a new session on this cluster, initialize it and sets the keyspace to the provided one. Note
  • builder
    Creates a new Cluster.Builder instance. This is a convenience method for new Cluster.Builder().
  • getMetadata
    Returns read-only metadata on the connected cluster. This includes the known nodes with their status
  • getConfiguration
    The cluster configuration.
  • isClosed
    Whether this Cluster instance has been closed. Note that this method returns true as soon as one of
  • getClusterName
    The name of this cluster object. Note that this is not the Cassandra cluster name, but rather a name
  • closeAsync
    Initiates a shutdown of this cluster instance. This method is asynchronous and return a future on th
  • register
    Registers the provided listener to be updated with schema change events. Registering the same liste
  • newSession
    Creates a new session on this cluster but does not initialize it. Because this method does not perfo
  • getMetrics
    The cluster metrics.
  • init
    Initialize this Cluster instance. This method creates an initial connection to one of the contact po
  • connectAsync
    Creates a new session on this cluster, and initializes it to the given keyspace asynchronously. This
  • init,
  • connectAsync,
  • unregister,
  • <init>,
  • buildFrom,
  • checkNotEmpty,
  • timeSince,
  • checkNotClosed,
  • getDriverVersion

Popular in Java

  • Finding current android device location
  • onRequestPermissionsResult (Fragment)
  • getContentResolver (Context)
  • getSharedPreferences (Context)
  • FileInputStream (java.io)
    An input stream that reads bytes from a file. File file = ...finally if (in != null) in.clos
  • TimeZone (java.util)
    TimeZone represents a time zone offset, and also figures out daylight savings. Typically, you get a
  • TimerTask (java.util)
    The TimerTask class represents a task to run at a specified time. The task may be run once or repeat
  • Collectors (java.util.stream)
  • JComboBox (javax.swing)
  • JTable (javax.swing)
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now