Exemple #1
0
    public List<String> getSchema(
        String sourceKeyspace, String destKeyspace, Collection<String> tables) {
      Cluster cluster = peer.getCluster();
      Metadata meta = cluster.getMetadata();
      KeyspaceMetadata kmeta = meta.getKeyspace(keyspace);
      Collection<TableMetadata> tmeta = kmeta.getTables();
      //	    List<String> drops = new ArrayList<>();
      List<String> created = new ArrayList<>();

      for (TableMetadata tab : tmeta) {
        if (tables.size() != 0) {
          String name = tab.getName();
          if (!tables.contains(name)) continue;
        }
        String s = tab.asCQLQuery();
        StringBuilder sb = new StringBuilder();
        sb.append("DROP TABLE IF EXISTS ")
            .append(destKeyspace)
            .append(".")
            .append(tab.getName())
            .append(";\n");

        created.add(sb.toString());
        created.add(s.replaceAll("CREATE TABLE " + sourceKeyspace, "CREATE TABLE " + destKeyspace));
      }
      return created;
    }
  public UserInteractionDao(String[] contactPoints) {

    Cluster cluster = Cluster.builder().addContactPoints(contactPoints).build();
    this.session = cluster.connect();

    KeyspaceMetadata keyspaceMetadata =
        this.session.getCluster().getMetadata().getKeyspace(keyspaceName);

    this.insertUserInteractionStmt = session.prepare(INSERT_INTO_USER_INTERACTION);
  }
 public void connect(String node) {
   cluster = Cluster.builder().addContactPoint(node).build();
   Metadata metadata = cluster.getMetadata();
   System.out.printf("Connected to cluster: %s\n", metadata.getClusterName());
   for (Host host : metadata.getAllHosts()) {
     System.out.printf(
         "Datatacenter: %s; Host: %s; Rack: %s\n",
         host.getDatacenter(), host.getAddress(), host.getRack());
   }
   session = cluster.connect("whoami");
 }
 @BeforeClass
 public static void startCassandra()
     throws TTransportException, IOException, InterruptedException, ConfigurationException {
   EmbeddedCassandraServerHelper.startEmbeddedCassandra(
       CASSANDRA_CONFIG, "build/embeddedCassandra");
   cluster =
       Cluster.builder()
           .addContactPoint(IntegrationTestConfig.HOST)
           .withPort(IntegrationTestConfig.PORT)
           .build();
   system = cluster.connect();
 }
 void callShutDown() {
   for (PersistenceManagerFactory factory : persistenceManagerFactories) {
     log.info("Call shutdown on " + factory);
     factory.shutDown();
   }
   for (Cluster cluster : clusters) {
     log.info(
         String.format(
             "Call shutdown on Cluster instance '%s' of cluster name '%s'",
             cluster, cluster.getClusterName()));
     cluster.closeAsync().force();
   }
 }
  public static synchronized Session getSession(String host, int port) throws UnknownHostException {
    Session session = hostConnectionMap.getIfPresent(host);
    if (session == null || session.isClosed()) {
      Cluster.Builder builder = Cluster.builder().addContactPoint(host).withPort(port);
      Cluster cluster = builder.build();
      session = cluster.connect();
      hostConnectionMap.put(host, session);

      logger.debug("Created connection to {}.", host);
      logger.debug("Number of sessions opened are {}.", hostConnectionMap.size());
    }
    return session;
  }
  public static void main(String[] args) {

    System.out.println("Connecting to db: " + System.getProperty("DB_HOST"));

    Cluster cluster =
        Cluster.builder().addContactPoints(System.getProperty("DB_HOST").split(",")).build();

    Session session = cluster.connect();
    session.execute(
        "CREATE KEYSPACE IF NOT EXISTS todolist WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 3 };");
    session.execute(
        "CREATE TABLE IF NOT EXISTS todolist.todo (" + "id int PRIMARY KEY," + "text text);");
    SpringApplication.run(Application.class, args);
  }
 @Override
 public Object createDataSource(String xmlConfiguration, boolean isDataSourceFactoryReference)
     throws DataSourceException {
   try {
     CassandraConfiguration config = loadConfig(xmlConfiguration);
     Cluster cluster = createCluster(config);
     if (CassandraDataSourceConstants.SESSION_MODE.equalsIgnoreCase(config.getMode())
         && (config.getKeysapce() != null && config.getKeysapce().trim().length() > 0)) {
       return cluster.connect(config.getKeysapce());
     }
     return cluster;
   } catch (Exception ex) {
     throw new DataSourceException(ex);
   }
 }
 public static boolean isClusterActive() {
   try {
     Builder builder =
         Cluster.builder()
             .withQueryOptions(
                 new QueryOptions()
                     .setConsistencyLevel(ConsistencyLevel.QUORUM)
                     .setSerialConsistencyLevel(ConsistencyLevel.LOCAL_SERIAL));
     cluster = builder.addContactPoint("127.0.0.1").build();
     session = cluster.connect();
     return true;
   } catch (Exception e) {
     return false;
   }
 }
  private Cluster buildCluster() {
    cluster =
        Cluster.builder()
            .addContactPoints(contactPoints.split(","))
            .withRetryPolicy(DefaultRetryPolicy.INSTANCE)
            // .withCredentials("cassandra", "cassandra")
            .withLoadBalancingPolicy(
                new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build()))
            .build();

    logger.info(
        "Built Cluster on thread [" + Thread.currentThread().getName() + "]:" + cluster.toString());

    return cluster;
  }
Exemple #11
0
  public boolean validateUser(String username, String password) {
    AeSimpleSHA1 sha1handler = new AeSimpleSHA1();
    String EncodedPassword = null;
    try {
      EncodedPassword = sha1handler.SHA1(password);
    } catch (UnsupportedEncodingException | NoSuchAlgorithmException et) {
      System.out.println("Can't check your password");
      return false;
    }

    Session session = cluster.connect("ducquak");
    PreparedStatement pS = session.prepare("SELECT * FROM users");
    ResultSet rs = null;
    BoundStatement boundStatement = new BoundStatement(pS);
    rs =
        session.execute( // this is where the query is executed
            boundStatement // here you are binding the 'boundStatement'
            );
    if (rs.isExhausted()) {
      System.out.println("Nothing returned");
      return false;
    } else {
      for (Row row : rs) {

        String userName = row.getString("userName");
        if (userName.equals(username)) {
          String StoredPass = row.getString("password");
          if (StoredPass.compareTo(EncodedPassword) == 0) return true;
        }
      }
    }
    return false;
  }
  @PreDestroy
  public void stop() {

    if (cluster != null) {
      cluster.close();
    }
  }
  public java.util.LinkedList<Pic> getPicsForUser(String User) {
    java.util.LinkedList<Pic> Pics = new java.util.LinkedList<>();
    Session session = cluster.connect("instagrAndrew");
    PreparedStatement ps =
        session.prepare("select picid, hashtag, pic_added from userpiclist where user =?");
    ResultSet rs = null;
    BoundStatement boundStatement = new BoundStatement(ps);
    rs =
        session.execute( // this is where the query is executed
            boundStatement.bind( // here you are binding the 'boundStatement'
                User));
    if (rs.isExhausted()) {
      System.out.println("No Images returned");
      return null;
    } else {
      for (Row row : rs) {
        Pic pic = new Pic();
        java.util.UUID UUID = row.getUUID("picid");

        Date d = row.getDate("pic_added");
        java.sql.Timestamp tmp = new java.sql.Timestamp(d.getTime());

        pic.setUUID(UUID);
        pic.setDate(tmp);

        String ht = row.getString("hashtag");
        if (ht != null) {
          pic.setHashtag(ht);
        }
        Pics.add(pic);
      }
    }
    return Pics;
  }
  @Override
  public void output(Collection<Metric> metrics) {
    if (!eventRegistered.getAndSet(true)) {
      EventBusManager.createRegistrationPoint()
          .subscribe(
              WriteToStorageEvent.class,
              w -> {
                MetricStorage storage = w.storageToWriteTo().getSubStorageCalled("cassandra");
                storage.store("metrics-to-cassandra", metricCount.longValue());
              });

      EvilManagerHack.subscribe(this.cluster);
    }

    if (metrics.size() == 0) {
      return;
    }

    Map<RetentionTable, BatchStatement> stms =
        LazyMap.<RetentionTable, BatchStatement>lazyMap(
            new HashMap<>(), () -> new BatchStatement());
    for (Metric metric : metrics) {
      insertMetricIntoBatch(metric, stms);
    }
    KeyspaceMetadata metadata = cluster.getMetadata().getKeyspace(keyspace);
    for (RetentionTable table : stms.keySet()) {
      createTableIfNecessary(table, metadata);
    }
    for (BatchStatement batch : stms.values()) {
      session.execute(batch);
    }

    metricCount.addAndGet(metrics.size());
  }
  /**
   * Creates a new Cluster based on the specified configuration.
   *
   * @param stormConf the storm configuration.
   * @return a new a new {@link Cluster} instance.
   */
  @Override
  protected Cluster make(Map<String, Object> stormConf) {
    CassandraConf cassandraConf = new CassandraConf(stormConf);

    Cluster.Builder cluster =
        Cluster.builder()
            .withoutJMXReporting()
            .withoutMetrics()
            .addContactPoints(cassandraConf.getNodes())
            .withPort(cassandraConf.getPort())
            .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)
            .withReconnectionPolicy(
                new ExponentialReconnectionPolicy(100L, TimeUnit.MINUTES.toMillis(1)))
            .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));

    final String username = cassandraConf.getUsername();
    final String password = cassandraConf.getPassword();

    if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
      cluster.withAuthProvider(new PlainTextAuthProvider(username, password));
    }

    QueryOptions options =
        new QueryOptions().setConsistencyLevel(cassandraConf.getConsistencyLevel());
    cluster.withQueryOptions(options);

    return cluster.build();
  }
 @Before
 public void setUp() throws Exception {
   cluster = CassandraUnitUtils.cassandraCluster();
   session = cluster.connect(CassandraUnitUtils.KEYSPACE);
   idempotentRepository = new CassandraIdempotentRepository<String>(session);
   idempotentRepository.start();
 }
 /**
  * Obtain common cassandra Cluster Builder.
  *
  * @param port port of endpoints
  * @param contactPoints list of cassandra ip addresses
  * @return {@link com.datastax.driver.core.Cluster.Builder}
  */
 private Cluster.Builder getClusterBuilder(int port, String[] contactPoints) {
   return Cluster.builder()
       .addContactPoints(contactPoints)
       .withPort(port)
       .withProtocolVersion(ProtocolVersion.V3)
       .withTimestampGenerator(new AtomicMonotonicTimestampGenerator());
 }
 /** Common initializer. */
 private void init() {
   Metadata metadata = cluster.getMetadata();
   LOGGER.info("Connected to cluster: {}", metadata.getClusterName());
   for (Host h : metadata.getAllHosts()) {
     LOGGER.info(
         "Data center: {}; Hosts: {}; Rack: {}", h.getDatacenter(), h.getAddress(), h.getRack());
   }
 }
  public static Cluster getCluster() {
    System.out.println("getCluster");
    cluster = Cluster.builder().addContactPoint(Host).build();
    getHosts(cluster);
    Keyspaces.SetUpKeySpaces(cluster);

    return cluster;
  }
  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 PersistentCassandraDrain(
      E environment, String username, String password, String[] seeds, String keyspace) {
    Cluster.Builder builder = Cluster.builder().addContactPoints(seeds);
    builder.withReconnectionPolicy(new ExponentialReconnectionPolicy(500, 60_000));
    if (username != null) {
      if (password != null) {
        builder = builder.withCredentials(username, password);
      } else {
        logger.warn("username was set, password was NOT set - IGNORING username!");
      }
    }

    this.environment = environment;
    this.cluster = builder.build();
    this.keyspace = keyspace;
    this.session = cluster.connect(keyspace);
  }
  @Override
  public void start() {
    cluster = Cluster.builder().addContactPoint(address).build();
    Metadata metadata = cluster.getMetadata();
    LOGGER.debug("Connected to cluster: {0}", metadata.getClusterName());
    for (Host host : metadata.getAllHosts()) {
      LOGGER.debug(
          "Datacenter: {0}; Host: {1}; Rack: {2}",
          host.getDatacenter(), host.getAddress(), host.getRack());
    }

    session = cluster.connect();
    try {
      session.execute(
          "CREATE KEYSPACE modeshape WITH replication "
              + "= {'class':'SimpleStrategy', 'replication_factor':3};");
    } catch (AlreadyExistsException e) {
    }

    session.execute("USE modeshape;");

    try {
      session.execute(
          "CREATE TABLE modeshape.binary("
              + "cid text PRIMARY KEY,"
              + "mime_type text,"
              + "ext_text text,"
              + "usage int,"
              + "usage_time timestamp,"
              + "payload blob)");
    } catch (AlreadyExistsException e) {
    }

    try {
      session.execute("CREATE INDEX USAGE_IDX ON modeshape.binary (usage);");
    } catch (InvalidQueryException e) {
      // exists
    }

    try {
      session.execute("CREATE INDEX EXPIRE_IDX ON modeshape.binary (usage_time);");
    } catch (InvalidQueryException e) {
      // exists
    }
  }
 @Before
 public void setUp() throws Exception {
   when(cluster.getMetadata().getKeyspace(keyspaceName)).thenReturn(keyspaceMeta);
   when(keyspaceMeta.getTables()).thenReturn(new ArrayList<TableMetadata>());
   when(keyspaceMeta.getTables()).thenReturn(asList(tableMeta));
   when(tableMeta.getName()).thenReturn("tableName");
   when(meta.config().getQualifiedTableName()).thenReturn("tableName");
   when(meta.config().isSchemaUpdateEnabled()).thenReturn(true);
 }
  @PostConstruct
  public void start() throws Exception {

    loadConfig(CONFIG_RESOURCE_NAME);

    cluster = Cluster.builder().addContactPoints(nodes).withPort(port).build();
    String clusterName = cluster.getMetadata().getClusterName();
    log.info("Connected to Cassandra cluster %s", clusterName);

    session = cluster.connect();
    try {
      session.execute(
          String.format(CREATE_KEYSPACE_CQL, keyspaceName, strategyClass, replicationFactor));
      log.info("Created keyspace %s in cluster %s", keyspaceName, clusterName);
    } catch (AlreadyExistsException e) {
      log.info("Found keyspace %s in cluster %s", keyspaceName, clusterName);
    }
    session.execute(String.format(USE_KEYSPACE_CQL, keyspaceName));
  }
  /**
   * Constructor. Use it when your Cassandra cluster does not support authentication.
   *
   * @param hosts cassandra node hosts, comma separated
   * @param port cassandra node cql service port
   * @param keyspaceName name of keyspace
   */
  public CassandraConnectionProvider(String hosts, int port, String keyspaceName) {
    this.hosts = hosts;
    this.port = String.valueOf(port);
    this.keyspaceName = keyspaceName;

    String[] contactPoints = hosts.split(",");
    cluster = getClusterBuilder(port, contactPoints).build();
    init();
    session = cluster.connect(keyspaceName);
  }
  private Map<String, TableMetadata> fetchTableMetaData() {
    Map<String, TableMetadata> tableMetas = new HashMap<String, TableMetadata>();
    KeyspaceMetadata keyspaceMeta = cluster.getMetadata().getKeyspace(keyspaceName);

    Validator.validateTableTrue(
        keyspaceMeta != null, "Keyspace '%s' doest not exist or cannot be found", keyspaceName);

    for (TableMetadata tableMeta : keyspaceMeta.getTables()) {
      tableMetas.put(tableMeta.getName(), tableMeta);
    }
    return tableMetas;
  }
Exemple #27
0
 public void createKeyspace(String keyspaceName, String keyclassType, int replicationFactor) {
   cluster
       .connect()
       .execute(
           "CREATE KEYSPACE "
               + keyspaceName
               + " WITH replication "
               + "= {'class':'"
               + keyclassType
               + "', 'replication_factor':"
               + replicationFactor
               + "};");
 }
    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();
      }
    }
  public static String[] getHosts(Cluster cluster) {

    if (cluster == null) {
      System.out.println("Creating cluster connection");
      cluster = Cluster.builder().addContactPoint(Host).build();
    }
    System.out.println("Cluster Name " + cluster.getClusterName());
    Metadata mdata = cluster.getMetadata();
    Set<Host> hosts = mdata.getAllHosts();
    String sHosts[] = new String[hosts.size()];

    Iterator<Host> it = hosts.iterator();
    int i = 0;
    while (it.hasNext()) {
      Host ch = it.next();
      sHosts[i] = (String) ch.getAddress().toString();

      System.out.println("Hosts" + ch.getAddress().toString());
      i++;
    }

    return sHosts;
  }
Exemple #30
0
 public void changePassword(String username, String newPassword) {
   Session session = cluster.connect("ducquak");
   Statement s00;
   s00 = QueryBuilder.select().all().from("ducquak", "users");
   ResultSet rs = session.execute(s00);
   for (Row row : rs) {
     String olduserName = row.getString("userName");
     if (olduserName.equals(username)) {
       Statement s01 =
           QueryBuilder.update("ducquak", "users")
               .with(set("password", username))
               .where(eq("password", olduserName));
       session.execute(s01);
     }
   }
 }