@PreDestroy
  public void stop() {

    if (cluster != null) {
      cluster.close();
    }
  }
    public void discard() {
      if (cluster != null) cluster.close();

      if (cassandraCluster == null) {
        logger.error("No cluster to discard");
      } else if (erroredOut) {
        cassandraCluster.stop();
        logger.info("Error during tests, kept C* logs in " + cassandraCluster.ccmDir);
      } else {
        cassandraCluster.remove();
        cassandraCluster.ccmDir.delete();
      }
    }
  @Override
  public void afterTestClass(TestContext testContext) throws Exception {
    JUnitNewtsCassandra config = findNewtsCassandraAnnotation(testContext);
    if (config == null) {
      return;
    }

    if (m_session != null) {
      LOG.debug("session shutdown");
      CloseFuture closeFuture = m_session.closeAsync();
      closeFuture.force();
    }
    if (m_cluster != null) {
      LOG.debug("cluster shutdown");
      m_cluster.close();
    }
  }
  public CassandraClient() {
    //		String cashost = "ec2-52-193-198-108.ap-northeast-1.compute.amazonaws.com";
    String cashost = "133.162.209.156";
    String keyspace = "iot";

    Cluster cluster;
    Session session;

    // Connect to the cluster and keyspace "demo"
    //		cluster = Cluster.builder().addContactPoint(cashost).build();
    AuthProvider auth = new PlainTextAuthProvider("iotapp", "pwdiotapp");
    cluster = Cluster.builder().addContactPoint(cashost).withAuthProvider(auth).build();
    session = cluster.connect(keyspace);

    // INSERT Test
    this.insert(session);

    // SELECT Test
    this.select(session);

    // // Update the same user with a new age
    // session.execute("update users set age = 36 where lastname =
    // 'Jones'");
    //
    // // Select and show the change
    // results = session.execute("select * from users where
    // lastname='Jones'");
    // for (Row row : results) {
    // System.out.format("%s %d\n", row.getString("firstname"),
    // row.getInt("age"));
    // }
    //
    // // Delete the user from the users table
    // session.execute("DELETE FROM users WHERE lastname = 'Jones'");
    //
    // // Show that the user is gone
    // results = session.execute("SELECT * FROM users");
    // for (Row row : results) {
    // System.out.format("%s %d %s %s %s\n", row.getString("lastname"),
    // row.getInt("age"), row.getString("city"),
    // row.getString("email"), row.getString("firstname"));
    // }

    // Clean up the connection by closing it
    cluster.close();
  }
 public void close() {
   cluster.close();
 }
 @After
 public void tearDown() throws Exception {
   idempotentRepository.stop();
   session.close();
   cluster.close();
 }
  public static void main(String args[]) {
    String[] calles_28001 = {"Alcala", "Preciados", "Gran Via", "Princesa"};
    String[] calles_28002 = {"Castellana", "Goya", "Serrano", "Velazquez"};

    String addres = "Alcala";
    String cpCode = "28001";

    int index_28001 = 0;
    int index_28002 = 0;

    List<User> users = new ArrayList<User>();

    for (int i = 0; i < 2000; i++) {

      String id = (i + 1) + "";
      String email = "user" + id + "@void.com";
      String nombre = "nombre_" + id;
      String cp;
      String calle;
      if (i % 2 == 0) {
        cp = "28001";
        calle = calles_28001[index_28001];
        index_28001++;
        index_28001 = index_28001 % 4;
      } else {
        cp = "28002";
        calle = calles_28002[index_28002];
        index_28002++;
        index_28002 = index_28002 % 4;
      }

      User user = new User(id, email, nombre, cp, calle);
      users.add(user);
    }

    // conectar y crear column family
    Cluster cluster;
    String node = "127.0.0.1";

    cluster = Cluster.builder().addContactPoint(node).build();

    Session session;
    session = cluster.connect();

    session.execute("drop keyspace utad_cql");

    session.execute(
        "CREATE KEYSPACE utad_cql WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};");

    // Creo la tabla con la PK compuesta por CP, Calle, e Id Usuario, para
    // asegurarme que cada registro que inserto es único (lo discrimino por
    // id_usuario)
    session.execute(
        "CREATE TABLE utad_cql.usersByCPAddress (id_usuario int, cp int, nombre text, email text, calle text, primary key(cp, calle, id_usuario));");

    PreparedStatement ps1 =
        session.prepare(
            "Insert into utad_cql.usersByCPAddress(id_usuario, cp, nombre, email, calle) values (?, ?, ?, ?, ?)");

    BatchStatement batch = new BatchStatement();

    // Realizamos las inserciones en BD
    for (User user : users) {
      int id = Integer.parseInt(user.id);
      int cp = Integer.parseInt(user.cp);
      String nombre = user.nombre;
      String email = user.email;
      String calle = user.calle;

      batch.add(ps1.bind(id, cp, nombre, email, calle));
    }

    session.execute(batch);
    System.out.println("\nRegistros insertados en Cassandra");

    // Muestro el resultado correspondiente, pero comento los campos que no
    // se piden en el resultado, para confirmar, descomentandolos, que los
    // datos son los correctos. Limitamos la muestra resultado a 20 registros.
    StringBuilder sbQuery = new StringBuilder();
    sbQuery.append("select id_usuario, nombre, email ");
    // sbQuery.append(",cp, calle  ");
    sbQuery.append("from utad_cql.usersByCPAddress where calle='").append(addres);
    sbQuery.append("' and cp=").append(cpCode);
    sbQuery.append(" limit 20");

    ResultSet results = session.execute(sbQuery.toString());

    // Leemos los datos recuperados.
    for (Row row : results) {
      System.out.println("\nid : " + row.getInt("id_usuario"));
      System.out.println("nombre : " + row.getString("nombre"));
      System.out.println("email : " + row.getString("email"));
      //			System.out.println("cp : " + row.getInt("cp"));
      //			System.out.println("calle : " + row.getString("calle"));
    }

    cluster.close();
    System.out.println("\nFin de la ejecución");
  }
 @AfterClass
 public static void cleanup() {
   cluster.close();
   EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
 }
 public void cleanup() {
   cassandra.close();
 }
Example #10
0
  public static void main(String[] args) {

    for (int i = 0; i < args.length; ++i) {
      if ("-endpoint".equals(args[i])) {
        endpoint = args[++i];
      } else if ("-keyspace".equals(args[i])) {
        keyspace = args[++i];
      } else if ("-table".equals(args[i])) {
        table = args[++i];
      } else {
        System.err.println("ConsistencyTest -endpoint hostname -keyspace keyspace -table table");
      }
    }
    if (endpoint == null || keyspace == null || table == null) {
      System.err.println("ConsistencyTest -endpoint hostname -keyspace keyspace -table table");
      System.exit(1);
    }

    String[] endpoints = endpoint.split(":");

    try {
      cluster =
          Cluster.builder()
              .addContactPoints(endpoints)
              .withRetryPolicy(DefaultRetryPolicy.INSTANCE)
              .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy()))
              .build();
      session = cluster.connect(keyspace);

      // work with ONE for both write and read
      long s1 = System.currentTimeMillis();
      Statement insert =
          QueryBuilder.insertInto(table)
              .value("user_id", 100)
              .value("fname", "john")
              .value("lname", "yamada")
              .value("number", 100);
      insert.setConsistencyLevel(ConsistencyLevel.ONE);
      session.execute(insert);
      long e1 = System.currentTimeMillis();
      System.out.println("write ONE time taken (ms) : " + (e1 - s1));

      long s2 = System.currentTimeMillis();
      Statement select =
          QueryBuilder.select().all().from(table).where(QueryBuilder.eq("user_id", 100));
      select.setConsistencyLevel(ConsistencyLevel.ONE);
      results = session.execute(select);
      for (Row row : results) {
        System.out.format(
            "%d %s %s %d\n",
            row.getInt("user_id"),
            row.getString("fname"),
            row.getString("lname"),
            row.getInt("number"));
      }
      long e2 = System.currentTimeMillis();
      System.out.println("read ONE time taken (ms) : " + (e2 - s2));

      Statement delete = QueryBuilder.delete().from(table).where(QueryBuilder.eq("user_id", 100));
      results = session.execute(delete);

      // work with QUORUM for both write and read
      long s3 = System.currentTimeMillis();
      Statement insert2 =
          QueryBuilder.insertInto(table)
              .value("user_id", 200)
              .value("fname", "john")
              .value("lname", "yamada")
              .value("number", 100);
      insert2.setConsistencyLevel(ConsistencyLevel.QUORUM);
      session.execute(insert2);
      long e3 = System.currentTimeMillis();
      System.out.println("write QUORUM time taken (ms) : " + (e3 - s3));

      long s4 = System.currentTimeMillis();
      Statement select2 =
          QueryBuilder.select().all().from(table).where(QueryBuilder.eq("user_id", 200));
      select2.setConsistencyLevel(ConsistencyLevel.QUORUM);
      results = session.execute(select2);
      for (Row row : results) {
        System.out.format(
            "%d %s %s %d\n",
            row.getInt("user_id"),
            row.getString("fname"),
            row.getString("lname"),
            row.getInt("number"));
      }
      long e4 = System.currentTimeMillis();
      System.out.println("read QUORUM time taken (ms) : " + (e4 - s4));

      Statement delete2 = QueryBuilder.delete().from(table).where(QueryBuilder.eq("user_id", 200));
      results = session.execute(delete2);

      // Clean up the connection by closing it
      cluster.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 @Override
 public void shutdown() {
   session.close();
   cluster.close();
 }
 @PreDestroy
 private void closeConnections() {
   LOGGER.info("Cluster is shutting down.");
   cluster.close();
 }