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

The following examples show how to use com.datastax.driver.core.Cluster#getMetadata() . 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: ClusterFactory.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected Cluster createCluster() {
   Cluster.Builder builder = Cluster.builder();

   if (this.contactPoints != null && !this.contactPoints.isEmpty()) {
      String[] values = new String[this.contactPoints.size()];
      this.contactPoints.toArray(values);
      builder.addContactPoints(values);
   }

   builder.withPort(this.port);

   Cluster cluster = builder.build();

   Metadata metadata = cluster.getMetadata();

   LOG.info("Connected to Cassandra cluster: " + metadata.getClusterName());
   for (Host host : metadata.getAllHosts()) {
      LOG.info("DataCenter: {}, Rack: {}, Host: {}",
               new Object[]{host.getDatacenter(), host.getRack(), host.getAddress()});
   }

   return cluster;
}
 
Example 2
Source File: CassandraClusterProvider.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public Cluster get() {
    String host = configuration.getHostAddress();
    int port = configuration.getPort();

    LOGGER.info("Connecting to cassandra cluster with host:{}, port:{}", host, port);

    Cluster cluster = Cluster.builder()
            .addContactPoint(host)
            .withPort(port)
            .build();

    Metadata metadata = cluster.getMetadata();
    LOGGER.info("Connected to cluster: {}", metadata.getClusterName());
    metadata.getAllHosts().forEach(h -> {
        LOGGER.info("Datacenter:{}, host:{}, rack: {}", h.getDatacenter(), h.getAddress(), h.getRack());
    });
    return cluster;
}
 
Example 3
Source File: CassandraUtils.java    From sstable-tools with Apache License 2.0 6 votes vote down vote up
public static Cluster loadTablesFromRemote(String host, int port, String cfidOverrides) throws IOException {
    Map<String, UUID> cfs = parseOverrides(cfidOverrides);
    Cluster.Builder builder = Cluster.builder().addContactPoints(host).withPort(port);
    Cluster cluster = builder.build();
    Metadata metadata = cluster.getMetadata();
    IPartitioner partitioner = FBUtilities.newPartitioner(metadata.getPartitioner());
    if (DatabaseDescriptor.getPartitioner() == null)
        DatabaseDescriptor.setPartitionerUnsafe(partitioner);
    for (com.datastax.driver.core.KeyspaceMetadata ksm : metadata.getKeyspaces()) {
        if (!ksm.getName().equals("system")) {
            for (TableMetadata tm : ksm.getTables()) {
                String name = ksm.getName()+"."+tm.getName();
                try {
                    CassandraUtils.tableFromCQL(
                            new ByteArrayInputStream(tm.asCQLQuery().getBytes()),
                            cfs.get(name) != null ? cfs.get(name) : tm.getId());
                } catch(SyntaxException e) {
                    // ignore tables that we cant parse (probably dse)
                    logger.debug("Ignoring table " + name + " due to syntax exception " + e.getMessage());
                }
            }
        }
    }
    return cluster;
}
 
Example 4
Source File: AbstractCassandraProcessor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected void connectToCassandra(ProcessContext context) {
    if (cluster.get() == null) {
        ComponentLog log = getLogger();
        final String contactPointList = context.getProperty(CONTACT_POINTS).getValue();
        final String consistencyLevel = context.getProperty(CONSISTENCY_LEVEL).getValue();
        List<InetSocketAddress> contactPoints = getContactPoints(contactPointList);

        // Set up the client for secure (SSL/TLS communications) if configured to do so
        final SSLContextService sslService =
                context.getProperty(PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
        final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue();
        final SSLContext sslContext;

        if (sslService != null) {
            final SSLContextService.ClientAuth clientAuth;
            if (StringUtils.isBlank(rawClientAuth)) {
                clientAuth = SSLContextService.ClientAuth.REQUIRED;
            } else {
                try {
                    clientAuth = SSLContextService.ClientAuth.valueOf(rawClientAuth);
                } catch (final IllegalArgumentException iae) {
                    throw new ProviderCreationException(String.format("Unrecognized client auth '%s'. Possible values are [%s]",
                            rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", ")));
                }
            }
            sslContext = sslService.createSSLContext(clientAuth);
        } else {
            sslContext = null;
        }

        final String username, password;
        PropertyValue usernameProperty = context.getProperty(USERNAME);
        PropertyValue passwordProperty = context.getProperty(PASSWORD);

        if (usernameProperty != null && passwordProperty != null) {
            username = usernameProperty.getValue();
            password = passwordProperty.getValue();
        } else {
            username = null;
            password = null;
        }

        // Create the cluster and connect to it
        Cluster newCluster = createCluster(contactPoints, sslContext, username, password);
        PropertyValue keyspaceProperty = context.getProperty(KEYSPACE);
        final Session newSession;
        if (keyspaceProperty != null) {
            newSession = newCluster.connect(keyspaceProperty.getValue());
        } else {
            newSession = newCluster.connect();
        }
        newCluster.getConfiguration().getQueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf(consistencyLevel));
        Metadata metadata = newCluster.getMetadata();
        log.info("Connected to Cassandra cluster: {}", new Object[]{metadata.getClusterName()});
        cluster.set(newCluster);
        cassandraSession.set(newSession);
    }
}
 
Example 5
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 6
Source File: AbstractCassandraProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
void connectToCassandra(ProcessContext context) {
    if (cluster.get() == null) {
        ComponentLog log = getLogger();
        final String contactPointList = context.getProperty(CONTACT_POINTS).evaluateAttributeExpressions().getValue();
        final String consistencyLevel = context.getProperty(CONSISTENCY_LEVEL).getValue();
        final String compressionType = context.getProperty(COMPRESSION_TYPE).getValue();
        List<InetSocketAddress> contactPoints = getContactPoints(contactPointList);

        // Set up the client for secure (SSL/TLS communications) if configured to do so
        final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
        final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue();
        final SSLContext sslContext;

        if (sslService != null) {
            final SslContextFactory.ClientAuth clientAuth;

            if (StringUtils.isBlank(rawClientAuth)) {
                clientAuth = SslContextFactory.ClientAuth.REQUIRED;
            } else {
                try {
                    clientAuth = SslContextFactory.ClientAuth.valueOf(rawClientAuth);
                } catch (final IllegalArgumentException iae) {
                    throw new IllegalStateException(String.format("Unrecognized client auth '%s'. Possible values are [%s]",
                            rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", ")));
                }
            }

            sslContext = sslService.createSSLContext(clientAuth);
        } else {
            sslContext = null;
        }

        final String username, password;
        PropertyValue usernameProperty = context.getProperty(USERNAME).evaluateAttributeExpressions();
        PropertyValue passwordProperty = context.getProperty(PASSWORD).evaluateAttributeExpressions();

        if (usernameProperty != null && passwordProperty != null) {
            username = usernameProperty.getValue();
            password = passwordProperty.getValue();
        } else {
            username = null;
            password = null;
        }

        // Create the cluster and connect to it
        Cluster newCluster = createCluster(contactPoints, sslContext, username, password, compressionType);
        PropertyValue keyspaceProperty = context.getProperty(KEYSPACE).evaluateAttributeExpressions();

        final Session newSession;
        // For Java 11, the getValue() call was added so the test could pass
        if (keyspaceProperty != null && keyspaceProperty.getValue() != null) {
            newSession = newCluster.connect(keyspaceProperty.getValue());
        } else {
            newSession = newCluster.connect();
        }

        newCluster.getConfiguration().getQueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf(consistencyLevel));
        Metadata metadata = newCluster.getMetadata();

        log.info("Connected to Cassandra cluster: {}", new Object[]{metadata.getClusterName()});

        cluster.set(newCluster);
        cassandraSession.set(newSession);
    }
}
 
Example 7
Source File: CassandraSessionProvider.java    From nifi with Apache License 2.0 4 votes vote down vote up
private void connectToCassandra(ConfigurationContext context) {
    if (cluster == null) {
        ComponentLog log = getLogger();
        final String contactPointList = context.getProperty(CONTACT_POINTS).evaluateAttributeExpressions().getValue();
        final String consistencyLevel = context.getProperty(CONSISTENCY_LEVEL).getValue();
        final String compressionType = context.getProperty(COMPRESSION_TYPE).getValue();

        List<InetSocketAddress> contactPoints = getContactPoints(contactPointList);

        // Set up the client for secure (SSL/TLS communications) if configured to do so
        final SSLContextService sslService =
                context.getProperty(PROP_SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
        final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue();
        final SSLContext sslContext;

        if (sslService != null) {
            final SslContextFactory.ClientAuth clientAuth;
            if (StringUtils.isBlank(rawClientAuth)) {
                clientAuth = SslContextFactory.ClientAuth.REQUIRED;
            } else {
                try {
                    clientAuth = SslContextFactory.ClientAuth.valueOf(rawClientAuth);
                } catch (final IllegalArgumentException iae) {
                    throw new ProviderCreationException(String.format("Unrecognized client auth '%s'. Possible values are [%s]",
                            rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", ")));
                }
            }
            sslContext = sslService.createSSLContext(clientAuth);
        } else {
            sslContext = null;
        }

        final String username, password;
        PropertyValue usernameProperty = context.getProperty(USERNAME).evaluateAttributeExpressions();
        PropertyValue passwordProperty = context.getProperty(PASSWORD).evaluateAttributeExpressions();

        if (usernameProperty != null && passwordProperty != null) {
            username = usernameProperty.getValue();
            password = passwordProperty.getValue();
        } else {
            username = null;
            password = null;
        }

        PropertyValue readTimeoutMillisProperty = context.getProperty(READ_TIMEOUT_MS).evaluateAttributeExpressions();
        Optional<Integer> readTimeoutMillisOptional = Optional.ofNullable(readTimeoutMillisProperty)
            .filter(PropertyValue::isSet)
            .map(PropertyValue::asInteger);

        PropertyValue connectTimeoutMillisProperty = context.getProperty(CONNECT_TIMEOUT_MS).evaluateAttributeExpressions();
        Optional<Integer> connectTimeoutMillisOptional = Optional.ofNullable(connectTimeoutMillisProperty)
            .filter(PropertyValue::isSet)
            .map(PropertyValue::asInteger);

        // Create the cluster and connect to it
        Cluster newCluster = createCluster(contactPoints, sslContext, username, password, compressionType, readTimeoutMillisOptional, connectTimeoutMillisOptional);
        PropertyValue keyspaceProperty = context.getProperty(KEYSPACE).evaluateAttributeExpressions();
        final Session newSession;
        if (keyspaceProperty != null) {
            newSession = newCluster.connect(keyspaceProperty.getValue());
        } else {
            newSession = newCluster.connect();
        }
        newCluster.getConfiguration().getQueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf(consistencyLevel));
        Metadata metadata = newCluster.getMetadata();
        log.info("Connected to Cassandra cluster: {}", new Object[]{metadata.getClusterName()});

        cluster = newCluster;
        cassandraSession = newSession;
    }
}