com.datastax.driver.core.Metadata Java Examples

The following examples show how to use com.datastax.driver.core.Metadata. 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: ClusterManagerTest.java    From scalardb with Apache License 2.0 6 votes vote down vote up
@Test
public void getMetadata_ExistingKeyspaceAndTableGiven_ShouldReturnMetadata() {
  // Arrange
  manager.getSession();
  Metadata metadata = mock(Metadata.class);
  KeyspaceMetadata keyspaceMetadata = mock(KeyspaceMetadata.class);
  TableMetadata tableMetadata = mock(TableMetadata.class);
  when(cluster.getMetadata()).thenReturn(metadata);
  when(metadata.getKeyspace(anyString())).thenReturn(keyspaceMetadata);
  when(keyspaceMetadata.getTable(anyString())).thenReturn(tableMetadata);

  // Act
  TableMetadata actual = manager.getMetadata(ANY_KEYSPACE_NAME, ANY_TABLE_NAME);

  // Assert
  assertThat(actual).isEqualTo(tableMetadata);
}
 
Example #2
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 #3
Source File: ClusterHintsPollerTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testClusterHintsPollerWhenNodeDown() throws UnknownHostException {
    ClusterHintsPoller clusterHintsPoller = new ClusterHintsPoller();
    Session mockSession = mock(Session.class);
    Cluster mockCluster = mock(Cluster.class);
    Metadata mockMetadata = mock(Metadata.class);
    when(mockCluster.getMetadata()).thenReturn(mockMetadata);
    when(mockCluster.getClusterName()).thenReturn("test-cluster");
    Host node1 = mock(Host.class);
    when(node1.getAddress()).thenReturn(InetAddress.getByName("127.0.0.1"));
    Host node2 = mock(Host.class);
    when(node2.getAddress()).thenReturn(InetAddress.getByName("127.0.0.2"));
    Host node3 = mock(Host.class);
    when(node3.getAddress()).thenReturn(InetAddress.getByName("127.0.0.3"));

    when(mockSession.getCluster()).thenReturn(mockCluster);
    // The first node queried is down
    when(mockSession.execute(any(Statement.class))).thenThrow(new NoHostAvailableException(ImmutableMap.<InetSocketAddress, Throwable>of()));

    when(mockMetadata.getAllHosts()).thenReturn(ImmutableSet.of(node1, node2, node3));
    HintsPollerResult actualResult = clusterHintsPoller.getOldestHintsInfo(mockSession);

    // Make sure HintsPollerResult fails
    assertFalse(actualResult.areAllHostsPolling(), "Result should show hosts failing");
    assertEquals(actualResult.getHostFailure(), ImmutableSet.of(InetAddress.getByName("127.0.0.1")), "Node 1 should return with host failure");
}
 
Example #4
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 #5
Source File: CassandraConnector.java    From tutorials with MIT License 6 votes vote down vote up
public void connect(final String node, final Integer port) {

        Builder b = Cluster.builder().addContactPoint(node);

        if (port != null) {
            b.withPort(port);
        }
        cluster = b.build();

        Metadata metadata = cluster.getMetadata();
        LOG.info("Cluster name: " + metadata.getClusterName());

        for (Host host : metadata.getAllHosts()) {
            LOG.info("Datacenter: " + host.getDatacenter() + " Host: " + host.getAddress() + " Rack: " + host.getRack());
        }

        session = cluster.connect();
    }
 
Example #6
Source File: SmartThriftClient.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public SmartThriftClient(StressSettings settings, String keyspace, Metadata metadata)
{
    this.metadata = metadata;
    this.keyspace = keyspace;
    this.settings = settings;
    if (!settings.node.isWhiteList)
    {
        whiteset = null;
        whitelist = null;
    }
    else
    {
        whiteset = settings.node.resolveAllSpecified();
        whitelist = Arrays.asList(whiteset.toArray(new InetAddress[0]));
    }
}
 
Example #7
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 #8
Source File: ClusterManagerTest.java    From scalardb with Apache License 2.0 6 votes vote down vote up
@Test
public void getMetadata_TableNotExists_ShouldThrowStorageRuntimeException() {
  // Arrange
  manager.getSession();
  Metadata metadata = mock(Metadata.class);
  KeyspaceMetadata keyspaceMetadata = mock(KeyspaceMetadata.class);
  when(cluster.getMetadata()).thenReturn(metadata);
  when(metadata.getKeyspace(anyString())).thenReturn(keyspaceMetadata);
  when(keyspaceMetadata.getTable(anyString())).thenReturn(null);

  // Act
  assertThatThrownBy(
          () -> {
            manager.getMetadata(ANY_KEYSPACE_NAME, ANY_TABLE_NAME);
          })
      .isInstanceOf(StorageRuntimeException.class);
}
 
Example #9
Source File: CassandraPersistWriter.java    From streams with Apache License 2.0 5 votes vote down vote up
private void createKeyspaceAndTable() {
  Metadata metadata = client.cluster().getMetadata();
  if (Objects.isNull(metadata.getKeyspace(config.getKeyspace()))) {
    LOGGER.info("Keyspace {} does not exist. Creating Keyspace", config.getKeyspace());
    Map<String, Object> replication = new HashMap<>();
    replication.put("class", "SimpleStrategy");
    replication.put("replication_factor", 1);

    String createKeyspaceStmt = SchemaBuilder.createKeyspace(config.getKeyspace()).with()
        .replication(replication).getQueryString();
    client.cluster().connect().execute(createKeyspaceStmt);
  }

  session = client.cluster().connect(config.getKeyspace());

  KeyspaceMetadata ks = metadata.getKeyspace(config.getKeyspace());
  TableMetadata tableMetadata = ks.getTable(config.getTable());

  if (Objects.isNull(tableMetadata)) {
    LOGGER.info("Table {} does not exist in Keyspace {}. Creating Table", config.getTable(), config.getKeyspace());
    String createTableStmt = SchemaBuilder.createTable(config.getTable())
                              .addPartitionKey(config.getPartitionKeyColumn(), DataType.varchar())
                              .addColumn(config.getColumn(), DataType.blob()).getQueryString();

    session.execute(createTableStmt);
  }
}
 
Example #10
Source File: CQLService.java    From Doradus with Apache License 2.0 5 votes vote down vote up
private void displayClusterInfo() {
    Metadata metadata = m_cluster.getMetadata();
    m_logger.info("Connected to cluster with topography:");
    RoundRobinPolicy policy = new RoundRobinPolicy();
    for (Host host : metadata.getAllHosts()) {
        m_logger.info("   Host {}: datacenter: {}, rack: {}, distance: {}",
                      new Object[]{host.getAddress(), host.getDatacenter(), 
            host.getRack(), policy.distance(host)});
    }
    m_logger.info("Database contains {} keyspaces", metadata.getKeyspaces().size());
}
 
Example #11
Source File: TestCassandraUtils.java    From ingestion with Apache License 2.0 5 votes vote down vote up
@Test
public void getTableMetadata() {
  final Session session = mock(Session.class);
  final Cluster cluster = mock(Cluster.class);
  final Metadata metadata = mock(Metadata.class);
  final KeyspaceMetadata keyspaceMetadata = mock(KeyspaceMetadata.class);
  final TableMetadata tableMetadata = mock(TableMetadata.class);
  when(session.getCluster()).thenReturn(cluster);
  when(cluster.getMetadata()).thenReturn(metadata);
  when(metadata.getKeyspace("keyspace")).thenReturn(keyspaceMetadata);
  when(keyspaceMetadata.getTable("table")).thenReturn(tableMetadata);
  assertThat(CassandraUtils.getTableMetadata(session, "keyspace", "table")).isNotNull();
}
 
Example #12
Source File: CassandraDeepJobConfig.java    From deep-spark with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches table metadata from the underlying datastore, using DataStax java driver.
 *
 * @return the table metadata as returned by the driver.
 */
public TableMetadata fetchTableMetadata() {

    Metadata metadata = getSession().getCluster().getMetadata();
    KeyspaceMetadata ksMetadata = metadata.getKeyspace(quote(this.catalog));

    if (ksMetadata != null) {
        return ksMetadata.getTable(quote(this.table));
    } else {
        return null;
    }
}
 
Example #13
Source File: CassandraMetricBatch.java    From monasca-persister with Apache License 2.0 5 votes vote down vote up
public CassandraMetricBatch(Metadata metadata, ProtocolOptions protocol, CodecRegistry codec,
    TokenAwarePolicy lbPolicy, int batchLimit) {
  this.protocol = protocol;
  this.codec = codec;
  this.metadata = metadata;
  this.policy = lbPolicy;
  metricQueries = new HashMap<>();
  this.batchLimit = batchLimit;

  metricQueries = new HashMap<>();
  dimensionQueries = new HashMap<>();
  dimensionMetricQueries = new HashMap<>();
  metricDimensionQueries = new HashMap<>();
  measurementQueries = new HashMap<>();
}
 
Example #14
Source File: DescribeKeySpaceAnyExecutor.java    From Explorer with Apache License 2.0 5 votes vote down vote up
/**
 *  Execute when shCQL is DESCRIBE KEYSPACE anyvalue
 *  @param metaData
 * @return  table
 */
@Override
public Table execute(Metadata metaData) {
    KeyspaceMetadata keySpaceMetada = metaData.getKeyspace(param);
    FunctionalList<TableMetadata,RowData> functionalList = new FunctionalList<>(new ArrayList<>(keySpaceMetada.getTables()));
    List<RowData> rows = functionalList.map(new TableMetadataToRowDataFunction());
    rows.add(0,buildFirst(keySpaceMetada.toString()));
    return new Table(new ListUtils<String>().buildList(),rows);
}
 
Example #15
Source File: DescribeKeyspacesExecutor.java    From Explorer with Apache License 2.0 5 votes vote down vote up
/**
 * Execute Describe Keysapces
 * @param metaData
 * @return  table
 */
@Override
public Table execute(Metadata metaData) {
    FunctionalList<KeyspaceMetadata,RowData> functional = new FunctionalList<>(metaData.getKeyspaces());
    List<RowData> rowDatas = functional.map(new KeyspacestoRowDataFuntion());
    return new Table(new ListUtils<String>().buildList(), rowDatas);
}
 
Example #16
Source File: TestCassandraUtils.java    From ingestion with Apache License 2.0 5 votes vote down vote up
@Test
public void getTableMetadataOnUnexistentKeyspace() {
  // session.getCluster().getMetadata().getKeyspace(keyspace);
  final Session session = mock(Session.class);
  final Cluster cluster = mock(Cluster.class);
  final Metadata metadata = mock(Metadata.class);
  when(session.getCluster()).thenReturn(cluster);
  when(cluster.getMetadata()).thenReturn(metadata);
  when(metadata.getKeyspace("keyspace")).thenReturn(null);
  thrown.expect(IllegalStateException.class);
  thrown.expectMessage("Keyspace keyspace does not exist");
  CassandraUtils.getTableMetadata(session, "keyspace", "table");
}
 
Example #17
Source File: DescribeTablesExecutor.java    From Explorer with Apache License 2.0 5 votes vote down vote up
/**
 * Execute DESCRIBE TABLES .
 * @param metaData
 * @return table
 */
@Override
public Table execute(Metadata metaData) {
    FunctionalList<KeyspaceMetadata,RowData> functional = new FunctionalList<>( metaData.getKeyspaces());
    List<RowData> rows = functional.map(new KeyspaceTablestoRowData());
    return new Table(new ListUtils<String>().buildList(), rows);
}
 
Example #18
Source File: TestCassandraUtils.java    From ingestion with Apache License 2.0 5 votes vote down vote up
@Test
public void getTableMetadataOnUnexistentTable() {
  final Session session = mock(Session.class);
  final Cluster cluster = mock(Cluster.class);
  final Metadata metadata = mock(Metadata.class);
  final KeyspaceMetadata keyspaceMetadata = mock(KeyspaceMetadata.class);
  when(session.getCluster()).thenReturn(cluster);
  when(cluster.getMetadata()).thenReturn(metadata);
  when(metadata.getKeyspace("keyspace")).thenReturn(keyspaceMetadata);
  when(keyspaceMetadata.getTable("table")).thenReturn(null);
  thrown.expect(IllegalStateException.class);
  thrown.expectMessage("Table keyspace.table does not exist");
  CassandraUtils.getTableMetadata(session, "keyspace", "table");
}
 
Example #19
Source File: DescribeClusterExecutor.java    From Explorer with Apache License 2.0 5 votes vote down vote up
/**
 * Excute DESCRIBE CLUSTER
 * @param params attributtes describe
 * @return
 */
@Override
public Table execute(Metadata metaData) {
    List<NameValue> list = new ListUtils<NameValue>().buildList(new NameValue(CT_CLUSTER, metaData.getClusterName()),
                                                                 new NameValue(CT_PARTIRIONER, metaData.getPartitioner()));
    FunctionalList<NameValue,RowData> functionalList =
            new FunctionalList<NameValue,RowData>(list);

    List<RowData> data = functionalList.map(new NameValueToRowData());
    return new Table(new ListUtils<String>().buildList(),data);
}
 
Example #20
Source File: PutCassandraRecordTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Cluster createCluster(List<InetSocketAddress> contactPoints, SSLContext sslContext,
                                String username, String password, String compressionType) {
    Cluster mockCluster = mock(Cluster.class);
    try {
        Metadata mockMetadata = mock(Metadata.class);
        when(mockMetadata.getClusterName()).thenReturn("cluster1");
        when(mockCluster.getMetadata()).thenReturn(mockMetadata);
        when(mockCluster.connect()).thenReturn(mockSession);
        when(mockCluster.connect(anyString())).thenReturn(mockSession);
        Configuration config = Configuration.builder().build();
        when(mockCluster.getConfiguration()).thenReturn(config);
        ResultSetFuture future = mock(ResultSetFuture.class);
        ResultSet rs = CassandraQueryTestUtil.createMockResultSet();
        PreparedStatement ps = mock(PreparedStatement.class);
        when(mockSession.prepare(anyString())).thenReturn(ps);
        BoundStatement bs = mock(BoundStatement.class);
        when(ps.bind()).thenReturn(bs);
        when(future.getUninterruptibly()).thenReturn(rs);
        try {
            doReturn(rs).when(future).getUninterruptibly(anyLong(), any(TimeUnit.class));
        } catch (TimeoutException te) {
            throw new IllegalArgumentException("Mocked cluster doesn't time out");
        }
        if (exceptionToThrow != null) {
            doThrow(exceptionToThrow).when(mockSession).executeAsync(anyString());
            doThrow(exceptionToThrow).when(mockSession).executeAsync(any(Statement.class));

        } else {
            when(mockSession.executeAsync(anyString())).thenReturn(future);
            when(mockSession.executeAsync(any(Statement.class))).thenReturn(future);
        }
        when(mockSession.getCluster()).thenReturn(mockCluster);
    } catch (Exception e) {
        fail(e.getMessage());
    }
    return mockCluster;
}
 
Example #21
Source File: PutCassandraQLTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Cluster createCluster(List<InetSocketAddress> contactPoints, SSLContext sslContext,
                                String username, String password, String compressionType) {
    Cluster mockCluster = mock(Cluster.class);
    try {
        Metadata mockMetadata = mock(Metadata.class);
        when(mockMetadata.getClusterName()).thenReturn("cluster1");
        when(mockCluster.getMetadata()).thenReturn(mockMetadata);
        when(mockCluster.connect()).thenReturn(mockSession);
        when(mockCluster.connect(anyString())).thenReturn(mockSession);
        Configuration config = Configuration.builder().build();
        when(mockCluster.getConfiguration()).thenReturn(config);
        ResultSetFuture future = mock(ResultSetFuture.class);
        ResultSet rs = CassandraQueryTestUtil.createMockResultSet();
        PreparedStatement ps = mock(PreparedStatement.class);
        when(mockSession.prepare(anyString())).thenReturn(ps);
        BoundStatement bs = mock(BoundStatement.class);
        when(ps.bind()).thenReturn(bs);
        when(future.getUninterruptibly()).thenReturn(rs);
        try {
            doReturn(rs).when(future).getUninterruptibly(anyLong(), any(TimeUnit.class));
        } catch (TimeoutException te) {
            throw new IllegalArgumentException("Mocked cluster doesn't time out");
        }
        if (exceptionToThrow != null) {
            doThrow(exceptionToThrow).when(mockSession).executeAsync(anyString());
            doThrow(exceptionToThrow).when(mockSession).executeAsync(any(Statement.class));

        } else {
            when(mockSession.executeAsync(anyString())).thenReturn(future);
            when(mockSession.executeAsync(any(Statement.class))).thenReturn(future);
        }
        when(mockSession.getCluster()).thenReturn(mockCluster);
    } catch (Exception e) {
        fail(e.getMessage());
    }
    return mockCluster;
}
 
Example #22
Source File: AbstractCassandraProcessorTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Cluster createCluster(List<InetSocketAddress> contactPoints, SSLContext sslContext,
                                String username, String password, String compressionType) {
    Cluster mockCluster = mock(Cluster.class);
    Metadata mockMetadata = mock(Metadata.class);
    when(mockMetadata.getClusterName()).thenReturn("cluster1");
    when(mockCluster.getMetadata()).thenReturn(mockMetadata);
    Configuration config = Configuration.builder().build();
    when(mockCluster.getConfiguration()).thenReturn(config);
    return mockCluster;
}
 
Example #23
Source File: QueryCassandraTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Cluster createCluster(List<InetSocketAddress> contactPoints, SSLContext sslContext,
                                String username, String password, String compressionType) {
    Cluster mockCluster = mock(Cluster.class);
    try {
        Metadata mockMetadata = mock(Metadata.class);
        when(mockMetadata.getClusterName()).thenReturn("cluster1");
        when(mockCluster.getMetadata()).thenReturn(mockMetadata);
        Session mockSession = mock(Session.class);
        when(mockCluster.connect()).thenReturn(mockSession);
        when(mockCluster.connect(anyString())).thenReturn(mockSession);
        Configuration config = Configuration.builder().build();
        when(mockCluster.getConfiguration()).thenReturn(config);
        ResultSetFuture future = mock(ResultSetFuture.class);
        ResultSet rs = CassandraQueryTestUtil.createMockResultSet();
        when(future.getUninterruptibly()).thenReturn(rs);
        try {
            doReturn(rs).when(future).getUninterruptibly(anyLong(), any(TimeUnit.class));
        } catch (TimeoutException te) {
            throw new IllegalArgumentException("Mocked cluster doesn't time out");
        }
        if (exceptionToThrow != null) {
            when(mockSession.executeAsync(anyString())).thenThrow(exceptionToThrow);
        } else {
            when(mockSession.executeAsync(anyString())).thenReturn(future);
        }
    } catch (Exception e) {
        fail(e.getMessage());
    }
    return mockCluster;
}
 
Example #24
Source File: MetadataOperations.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private List<TokenRange> buildTokenRanges() {
    List<TokenRange> result = new ArrayList<>();
    Metadata metadata = session.getCluster().getMetadata();
    for (TokenRange range : metadata.getTokenRanges()) {
        for (TokenRange split : range.splitEvenly(split)) {
            result.addAll(split.unwrap());
        }
    }
    logger.info("Configured with {} token ranges, and {} splits", metadata.getTokenRanges(), result.size());
    return result;
}
 
Example #25
Source File: CassandraShard.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
private TokenRange rangeToTokenRange(Range<Token> range) {
    TokenFactory tokenFactory = this.partitioner.getTokenFactory();
    Metadata metadata = this.session.metadata();
    return metadata.newTokenRange(
                    metadata.newToken(tokenFactory.toString(range.left)),
                    metadata.newToken(tokenFactory.toString(range.right)));
}
 
Example #26
Source File: QueryCassandraTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Cluster createCluster(List<InetSocketAddress> contactPoints, SSLContext sslContext,
                                String username, String password) {
    Cluster mockCluster = mock(Cluster.class);
    try {
        Metadata mockMetadata = mock(Metadata.class);
        when(mockMetadata.getClusterName()).thenReturn("cluster1");
        when(mockCluster.getMetadata()).thenReturn(mockMetadata);
        Session mockSession = mock(Session.class);
        when(mockCluster.connect()).thenReturn(mockSession);
        when(mockCluster.connect(anyString())).thenReturn(mockSession);
        Configuration config = Configuration.builder().build();
        when(mockCluster.getConfiguration()).thenReturn(config);
        ResultSetFuture future = mock(ResultSetFuture.class);
        ResultSet rs = CassandraQueryTestUtil.createMockResultSet();
        when(future.getUninterruptibly()).thenReturn(rs);
        try {
            doReturn(rs).when(future).getUninterruptibly(anyLong(), any(TimeUnit.class));
        } catch (TimeoutException te) {
            throw new IllegalArgumentException("Mocked cluster doesn't time out");
        }
        if (exceptionToThrow != null) {
            when(mockSession.executeAsync(anyString())).thenThrow(exceptionToThrow);
        } else {
            when(mockSession.executeAsync(anyString())).thenReturn(future);
        }
    } catch (Exception e) {
        fail(e.getMessage());
    }
    return mockCluster;
}
 
Example #27
Source File: AbstractCassandraProcessorTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Cluster createCluster(List<InetSocketAddress> contactPoints, SSLContext sslContext,
                                String username, String password) {
    Cluster mockCluster = mock(Cluster.class);
    Metadata mockMetadata = mock(Metadata.class);
    when(mockMetadata.getClusterName()).thenReturn("cluster1");
    when(mockCluster.getMetadata()).thenReturn(mockMetadata);
    Configuration config = Configuration.builder().build();
    when(mockCluster.getConfiguration()).thenReturn(config);
    return mockCluster;
}
 
Example #28
Source File: PutCassandraQLTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Cluster createCluster(List<InetSocketAddress> contactPoints, SSLContext sslContext,
                                String username, String password) {
    Cluster mockCluster = mock(Cluster.class);
    try {
        Metadata mockMetadata = mock(Metadata.class);
        when(mockMetadata.getClusterName()).thenReturn("cluster1");
        when(mockCluster.getMetadata()).thenReturn(mockMetadata);
        when(mockCluster.connect()).thenReturn(mockSession);
        when(mockCluster.connect(anyString())).thenReturn(mockSession);
        Configuration config = Configuration.builder().build();
        when(mockCluster.getConfiguration()).thenReturn(config);
        ResultSetFuture future = mock(ResultSetFuture.class);
        ResultSet rs = CassandraQueryTestUtil.createMockResultSet();
        PreparedStatement ps = mock(PreparedStatement.class);
        when(mockSession.prepare(anyString())).thenReturn(ps);
        BoundStatement bs = mock(BoundStatement.class);
        when(ps.bind()).thenReturn(bs);
        when(future.getUninterruptibly()).thenReturn(rs);
        try {
            doReturn(rs).when(future).getUninterruptibly(anyLong(), any(TimeUnit.class));
        } catch (TimeoutException te) {
            throw new IllegalArgumentException("Mocked cluster doesn't time out");
        }
        if (exceptionToThrow != null) {
            doThrow(exceptionToThrow).when(mockSession).executeAsync(anyString());
            doThrow(exceptionToThrow).when(mockSession).executeAsync(any(Statement.class));

        } else {
            when(mockSession.executeAsync(anyString())).thenReturn(future);
            when(mockSession.executeAsync(any(Statement.class))).thenReturn(future);
        }
        when(mockSession.getCluster()).thenReturn(mockCluster);
    } catch (Exception e) {
        fail(e.getMessage());
    }
    return mockCluster;
}
 
Example #29
Source File: ClusterManagerTest.java    From scalardb with Apache License 2.0 5 votes vote down vote up
@Test
public void getMetadata_KeyspaceNotExists_ShouldThrowStorageRuntimeException() {
  // Arrange
  manager.getSession();
  Metadata metadata = mock(Metadata.class);
  when(cluster.getMetadata()).thenReturn(metadata);
  when(metadata.getKeyspace(anyString())).thenReturn(null);

  // Act Assert
  assertThatThrownBy(
          () -> {
            manager.getMetadata(ANY_KEYSPACE_NAME, ANY_TABLE_NAME);
          })
      .isInstanceOf(StorageRuntimeException.class);
}
 
Example #30
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);
    }
}