Java Code Examples for com.datastax.driver.core.Session#close()

The following examples show how to use com.datastax.driver.core.Session#close() . 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: CaseController.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/healthCheck")
@ResponseBody
public String healthCheck() {
    Cluster cluster = null;
    Session session = null;
    try {
        cluster = Cluster.builder().addContactPoint(host).withPort(port).withoutJMXReporting().build();
        session = cluster.connect();
        logger.info("cassandra connection open");

        PreparedStatement testPreparedStatement = session.prepare(TEST_EXIST_SQL);
        logger.info("Test result:" + testPreparedStatement.toString());
    } finally {
        if (session != null) {
            session.close();
        }
        if (cluster != null) {
            cluster.close();
        }
        logger.info("cassandra connection close");
    }
    return SUCCESS;
}
 
Example 2
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 3
Source File: CassandraTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private boolean checkCassandraReachable(List<ConfigIssue> issues) {
  boolean isReachable = true;
  try (Cluster validationCluster = getCluster()) {
    Session validationSession = validationCluster.connect();
    validationSession.close();
  } catch (NoHostAvailableException | AuthenticationException | IllegalStateException | StageException e) {
    isReachable = false;
    Target.Context context = getContext();
    LOG.error(Errors.CASSANDRA_05.getMessage(), e.toString(), e);
    issues.add(
        context.createConfigIssue(
        Groups.CASSANDRA.name(),
        CONTACT_NODES_LABEL,
        Errors.CASSANDRA_05, e.toString()
        )
    );
  }
  return isReachable;
}
 
Example 4
Source File: CassandraHealthIndicator.java    From micro-service with MIT License 6 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	
	Session session = null;
	
	try {
		session = cluster.connect();
		ResultSet rs = session.execute("SELECT dateof(now()) FROM system.local");
		Date date = rs.one().getTimestamp(0);
		logger.info("cassandra is working, the time is ", date);
		builder.up().withDetail("description", "cassandra is working, the time is " + date);
	} catch (Exception e) {
		logger.error("cassandra launch has error, {}", e.getMessage());
		builder.outOfService().withDetail("description", "cassandra launch has error, " + e.getMessage());
	} finally {
		if(null != session) {
			session.close();
		}
	}
}
 
Example 5
Source File: CaseController.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/cassandra")
@ResponseBody
public String testcase() {
    logger.info("cassandra contact points: {}:{}", host, port);

    Cluster cluster = null;
    Session session = null;
    try {
        cluster = Cluster.builder().addContactPoint(host).withPort(port).withoutJMXReporting().build();
        session = cluster.connect();
        logger.info("cassandra connection open");

        execute(session);
        executeAsync(session);

        return SUCCESS;
    } finally {
        if (session != null) {
            session.close();
        }
        if (cluster != null) {
            cluster.close();
        }
        logger.info("cassandra connection close");
    }
}
 
Example 6
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 7
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 8
Source File: HintsPollerTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test
public void oldestHintIsPickedFromOneNode() {

    long hintTimestamp = System.currentTimeMillis();

    Cluster cluster = Cluster.builder()
            .addContactPoint("127.0.0.1")
            .withPort(9164)
            .withClusterName("Test Cluster")
            .build();

    Session clusterSession = cluster.connect("system");

    // Insert two hints with different timestamps on the same node.
    clusterSession.execute(getInsertHintsQuery(hintTimestamp));
    clusterSession.execute(getInsertHintsQuery(hintTimestamp + 10000));

    // Get oldestHint
    ClusterHintsPoller clusterHintsPoller = new ClusterHintsPoller();
    HintsPollerResult oldestHintsInfo = clusterHintsPoller.getOldestHintsInfo(clusterSession);
    Assert.assertNotNull(oldestHintsInfo);

    // Since we know there should be only one entry
    long retrievedHintTimeStamp = oldestHintsInfo.getOldestHintTimestamp().or(Long.MAX_VALUE);

    Assert.assertEquals(retrievedHintTimeStamp, hintTimestamp);

    cluster.close();
    clusterSession.close();
}
 
Example 9
Source File: MetricsServiceCassandra.java    From realtime-analytics with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void shutDown() {
    if(session.isPresent()) {
        Session s = session.get();
        s.close();
        s.getCluster().close();
    }
}
 
Example 10
Source File: CassandraStore.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
protected void clearKeyspace() {
    // Drop keyspace with non-keyspace-session
    Statement stmt = SchemaBuilder.dropKeyspace(this.keyspace).ifExists();
    LOG.debug("Drop keyspace: {}", stmt);

    Session session = this.cluster().connect();
    try {
        session.execute(stmt);
    } finally {
        if (!session.isClosed()) {
            session.close();
        }
    }
}
 
Example 11
Source File: SessionWithInitializedTablesFactory.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Session createSession(Cluster cluster, String keyspace) {
    Session session = cluster.connect(keyspace);
    try {
        if (allOperationsAreFullyPerformed(session, module)) {
            new CassandraSchemaVersionDAO(session)
                .updateVersion(CassandraSchemaVersionManager.MAX_VERSION)
                .block();
        }
        return session;
    } catch (Exception e) {
        session.close();
        throw e;
    }
}
 
Example 12
Source File: CassandraClientProvider.java    From deep-spark with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    synchronized (CLIENTS_CACHE) {
        if (CLIENTS_CACHE != null && !CLIENTS_CACHE.isEmpty()) {
            LOG.info("Closing clients ");
            for (Session entry : CLIENTS_CACHE.values()) {
                if (entry != null) {
                    entry.close();
                }
            }
        }
    }
}
 
Example 13
Source File: CassandraStore.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
protected void initKeyspace() {
    Statement stmt = SchemaBuilder.createKeyspace(this.keyspace)
                                  .ifNotExists().with()
                                  .replication(parseReplica(this.conf));
    // Create keyspace with non-keyspace-session
    LOG.debug("Create keyspace: {}", stmt);
    Session session = this.cluster().connect();
    try {
        session.execute(stmt);
    } finally {
        if (!session.isClosed()) {
            session.close();
        }
    }
}
 
Example 14
Source File: CassandraJUnitRule.java    From cassandra-migration with MIT License 4 votes vote down vote up
private void load() {
    Session session = cluster.connect();
    CQLDataLoader dataLoader = new CQLDataLoader(session);
    dataLoader.load(dataSet);
    session.close();
}
 
Example 15
Source File: CassandraMigrationAutoConfigurationTest.java    From cassandra-migration with MIT License 4 votes vote down vote up
private void loadTestData() {
    Session session = cluster.connect();
    CQLDataLoader dataLoader = new CQLDataLoader(session);
    dataLoader.load(dataSet);
    session.close();
}
 
Example 16
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 17
Source File: ExecutionEngine.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public void execute() throws CommandExecutionException, XMLStreamException, ChecksumInvalidException {
   try {
      if(!metadataTablesExist()) {
         createMetadataTables();
      }

      ChangeLogSet xmlChanges = loadXML();
      ChangeLogSet dbState = loadDB();

      try {
      	xmlChanges.verify(dbState);
      }
      catch(ChecksumInvalidException e) {
      	if(context.getManagerContext().isAuto()) {
      		throw e;
      	}
      	else {
       	System.out.println("Invalid checksum: " + e.getMessage());
       	System.out.println("WARNING: This schema appears to be corrupt, continuing execution could result in data loss, are you sure you want to continue?");
       	if(promptToContinue()) {
       		xmlChanges = loadXML();
       		xmlChanges.verify(dbState, false);
       	}
       	else {
       		System.exit(0);
       	}
      	}
      }

      List<ChangeLog> changesToApply = identifyChanges(xmlChanges, dbState);

      dumpChanges(changesToApply);

      if(!promptToContinue()) {
         System.exit(0);
      }

      List<ExecutionCommand> commands = new LinkedList<ExecutionCommand>();
      for(ChangeLog cl : changesToApply) {
         commands.add(new ChangeLogExecutionCommand(cl));
      }
      commands.add(new ImportLocalizationKeysCommand());

      System.out.println("\nExecuting...");

      executeCommands(commands);

      // if we've rolled back make sure that the target version is now the latest version installed
      if(context.getManagerContext().getOperation() == Operation.ROLLBACK) {
         VersionHistory history = new VersionHistory();
         history.setStatus(Status.APPLIED);
         history.setTimestamp(new Date());
         history.setUsername(context.getManagerContext().getProfile().getUsername());
         history.setVersion(context.getManagerContext().getRollbackTarget());
         context.getVersionHistoryDAO().insert(history);
      }


      System.out.println("...Done!");

   } finally {
      Session session = context.getSession();
      if(session != null) {
         Cluster cluster = session.getCluster();
         session.close();
         cluster.close();
      }
   }
}
 
Example 18
Source File: CassandraProvider.java    From dropwizard-cassandra with Apache License 2.0 4 votes vote down vote up
@Override
public void dispose(Session session) {
	session.close();
}
 
Example 19
Source File: Sessions.java    From glowroot with Apache License 2.0 4 votes vote down vote up
static void closeSession(Session session) {
    Cluster cluster = session.getCluster();
    session.close();
    cluster.close();
}
 
Example 20
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());
}