private Statement createStatementToSaveFollowing(User user, Application app) {
    UUID userId = UUID.fromString(user.userId);
    UUID appId = UUID.fromString(app.applicationId);

    BatchStatement batch = new BatchStatement();

    Statement insertIntoAppFollowersTable =
        QueryBuilder.insertInto(Follow.TABLE_NAME_APP_FOLLOWERS)
            .value(APP_ID, appId)
            .value(USER_ID, userId)
            .value(APP_NAME, app.name)
            .value(USER_FIRST_NAME, user.firstName)
            .value(TIME_OF_FOLLOW, Instant.now().toEpochMilli());

    batch.add(insertIntoAppFollowersTable);

    Statement insertIntoUserFollowingsTable =
        QueryBuilder.insertInto(Follow.TABLE_NAME_USER_FOLLOWING)
            .value(APP_ID, appId)
            .value(USER_ID, userId)
            .value(APP_NAME, app.name)
            .value(USER_FIRST_NAME, user.firstName)
            .value(TIME_OF_FOLLOW, Instant.now().toEpochMilli());

    batch.add(insertIntoUserFollowingsTable);

    return batch;
  }
  public List<LogEvent> findByAppIdContains(
      final String appId, String token, LogEvent lastRow, int limit, boolean isPrevPaging) {
    Select sel = QueryBuilder.select().from(table).limit(limit);
    Where w = sel.where(QueryBuilder.eq(pkCols[0], appId));

    w.and(
        QueryBuilder.eq(
            luceneCol,
            Builder.search()
                .filter(Builder.phrase(logTextCol, token))
                .sort(SortField.field(timeuuidCol).reverse(isPrevPaging))
                .build()));

    if (lastRow != null) {
      w.and(
          isPrevPaging
              ? QueryBuilder.gt(timeuuidCol, lastRow.getId().getTimestamp())
              : QueryBuilder.lt(timeuuidCol, lastRow.getId().getTimestamp()));
    }

    log.debug(">>>>>>>>> Firing select query: " + sel.toString());
    List<LogEvent> events = cassandraOperations.select(sel, LogEvent.class);
    if (isPrevPaging) {
      Collections.sort(
          events,
          new Comparator<LogEvent>() {

            @Override
            public int compare(LogEvent o1, LogEvent o2) {
              return o2.getId().getTimestamp().compareTo(o1.getId().getTimestamp());
            }
          });
    }
    return events;
  }
Exemplo n.º 3
0
  public Collection<PlayerMention> retrievePlayerMentionsForPlayer(String player) {

    Select select = QueryBuilder.select().from("player_mention");
    select.where(QueryBuilder.eq("player", player));

    return this.cassandraOperations.select(select, PlayerMention.class);
  }
  public List<LogEvent> findByAppId(
      final String appId, LogEvent lastRow, int limit, boolean isPrevPaging) {
    Select sel = QueryBuilder.select().from(table).limit(limit);
    Where w = sel.where(QueryBuilder.eq(pkCols[0], appId));
    if (lastRow != null) {
      w.and(
          isPrevPaging
              ? QueryBuilder.gt(timeuuidCol, lastRow.getId().getTimestamp())
              : QueryBuilder.lt(timeuuidCol, lastRow.getId().getTimestamp()));
    }

    if (isPrevPaging) sel.orderBy(QueryBuilder.asc(timeuuidCol));

    log.debug(">>>>>>>>> Firing select query: " + sel.toString());
    List<LogEvent> events = cassandraOperations.select(sel, LogEvent.class);
    if (isPrevPaging) {
      Collections.sort(
          events,
          new Comparator<LogEvent>() {

            @Override
            public int compare(LogEvent o1, LogEvent o2) {
              return o2.getId().getTimestamp().compareTo(o1.getId().getTimestamp());
            }
          });
    }
    return events;
  }
Exemplo n.º 5
0
  public UserSelection retrieveUserSelectionForEmail(String email) {

    Select select = QueryBuilder.select().from("user_selection");
    select.where(QueryBuilder.eq("email", email));

    return this.cassandraOperations.selectOne(select, UserSelection.class);
  }
  public Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds) {
    ResultSet rs = null;
    Set<String> localUserIds = null;
    Statement getUserIds = null;
    try {
      getUserIds =
          QueryBuilder.select()
              .column("userid")
              .from(keyspace, table)
              .where(QueryBuilder.eq("providerId", providerId))
              .and(QueryBuilder.in("providerUserId", providerUserIds));

      rs = session.execute(getUserIds);
      if (rs.all().size() > 0) {
        localUserIds = new HashSet<String>();
      }
      for (Row row : rs.all()) {
        localUserIds.add(row.getString("userId"));
      }
      return localUserIds;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  public List<String> findUserIdsWithConnection(Connection<?> connection) {
    ResultSet rs = null;
    List<String> localUserIds = null;
    ConnectionKey key = connection.getKey();
    Statement getUserIds = null;
    try {
      getUserIds =
          QueryBuilder.select()
              .column("userid")
              .from(keyspace, table)
              .allowFiltering()
              .where(QueryBuilder.eq("providerId", key.getProviderId()))
              .and(QueryBuilder.eq("providerUserId", key.getProviderUserId()));

      rs = session.execute(getUserIds);
      List<Row> rows = rs.all();
      if (rows.size() > 0) {
        localUserIds = new LinkedList<String>();
      }
      for (Row row : rows) {
        localUserIds.add(row.getString("userId"));
      }
      return localUserIds;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  private Statement createDeleteStatementFor(String userId, String applicationId) {
    UUID appUuid = UUID.fromString(applicationId);
    UUID userUuid = UUID.fromString(userId);

    BatchStatement batch = new BatchStatement();

    Statement deleteFromAppFollowersTable =
        QueryBuilder.delete()
            .all()
            .from(Follow.TABLE_NAME_APP_FOLLOWERS)
            .where(eq(APP_ID, appUuid))
            .and(eq(USER_ID, userUuid));

    batch.add(deleteFromAppFollowersTable);

    Statement deleteFromUserFollowingsTable =
        QueryBuilder.delete()
            .all()
            .from(Follow.TABLE_NAME_USER_FOLLOWING)
            .where(eq(APP_ID, appUuid))
            .and(eq(USER_ID, userUuid));

    batch.add(deleteFromUserFollowingsTable);

    return batch;
  }
  @Override
  public List<DocumentMetadata> searchByUploader(String uploader) {
    Select select = QueryBuilder.select().from("documents");
    select.where(QueryBuilder.eq("uploaded_by", uploader));

    return DocumentMetadataMapping.unwrapList(
        cassandraOperations.select(select, DocumentMetadataMapping.class));
  }
  @Override
  public List<DocumentMetadata> searchByUploadTime(long from, long to) {
    Select select = QueryBuilder.select().from("documents");
    select.where(QueryBuilder.gte("upload_time", from)).and(QueryBuilder.lte("upload_time", to));
    select.allowFiltering();

    return DocumentMetadataMapping.unwrapList(
        cassandraOperations.select(select, DocumentMetadataMapping.class));
  }
Exemplo n.º 11
0
  public PlayerMention retrievePlayerMentionForPlayerAndSelectioner(
      String player, String selectioner) {

    Select select = QueryBuilder.select().from("player_mention");
    select.where(QueryBuilder.eq("player", player));
    select.where(QueryBuilder.eq("selectioner_email", selectioner));

    return this.cassandraOperations.selectOne(select, PlayerMention.class);
  }
  public List<SocialUserConnection> findConnectionsByUserId(String userId) {
    try {
      Statement selectConnections =
          QueryBuilder.select()
              .all()
              .from(keyspace, table)
              .where(QueryBuilder.eq("userid", userId));

      ResultSet rs = session.execute(selectConnections);
      return mapper.map(rs).all();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Exemplo n.º 13
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);
     }
   }
 }
  @Test
  public void testBuiltStatementOptionValues() {

    MockSession session = new MockSession();
    Insert insert = QueryBuilder.insertInto("myTable");
    insert.values(new String[] {"arg"}, new Object[] {"stringvalue"});

    Insert.Options using = insert.using(timestamp(100));
    using.values(new String[] {"another"}, new Object[] {"value"});

    Operation operation = CassandraOperationFinalizer.get(insert);
    assertNotNull(operation);

    session.execute(insert);

    assertNotNull(operation.getLabel());
    assertEquals("OperationType", CassandraExternalResourceAnalyzer.TYPE, operation.getType());
    String cql = operation.get("cql", String.class);
    assertEquals("cql", insert.getQueryString(), cql);
    OperationMap params =
        operation.get(CassandraOperationFinalizer.PARAMS_VALUES, OperationMap.class);
    assertNotNull(params);
    assertEquals("params", params.size(), 2);
    assertNull(CassandraOperationFinalizer.remove(insert));
  }
  @Test
  public void testCassandraBatchIngest() throws Exception {
    List<Book> books = getBookList(5);
    List<List<?>> ingestBooks = new ArrayList<>();
    for (Book b : books) {

      List<Object> l = new ArrayList<>();
      l.add(b.getIsbn());
      l.add(b.getTitle());
      l.add(b.getAuthor());
      l.add(b.getPages());
      l.add(b.getSaleDate());
      l.add(b.isInStock());
      ingestBooks.add(l);
    }

    Message<List<List<?>>> message = MessageBuilder.withPayload(ingestBooks).build();
    this.cassandraMessageHandler3.handleMessage(message);

    Select select = QueryBuilder.select().all().from("book");
    books = this.template.select(select, Book.class);
    assertEquals(5, books.size());

    this.template.delete(books);
  }
  public List<SocialUserConnection> findPrimaryConnections(String userId, String providerId) {
    try {
      Statement selectConnections =
          QueryBuilder.select()
              .all()
              .from(keyspace, table)
              .where(QueryBuilder.eq("userid", userId))
              .and(
                  QueryBuilder.eq(
                      "providerid", providerId)) /*.orderBy(QueryBuilder.desc("rank"))*/;

      ResultSet rs = session.execute(selectConnections);
      return mapper.map(rs).all();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Exemplo n.º 17
0
  @Override
  public void migrate(Session session) throws Exception {
    Insert insert = QueryBuilder.insertInto("test1");
    insert.value("space", "web");
    insert.value("key", "google");
    insert.value("value", "google.com");

    session.execute(insert);
  }
Exemplo n.º 18
0
 @Override
 public void processMessage(Message message) throws MessageProcessingException {
   String payload = message.getPayload();
   String dttm = message.getHeader().getDttm();
   try {
     Map<String, String> payloadMap = mapper.readValue(payload, Map.class);
     Integer userId = Integer.valueOf(payloadMap.get("UserId"));
     String tracker = payloadMap.get("Tracker");
     HeartTracker heartTracker = null;
     Select select = QueryBuilder.select().from("heart_tracker");
     select.where(QueryBuilder.eq("user_id", userId));
     select.where(QueryBuilder.eq("httr_tracker", tracker));
     select.allowFiltering();
     List<HeartTracker> heartTrackers = cassandraTemplate.select(select, HeartTracker.class);
     if (heartTrackers.size() == 0) {
       heartTracker = new HeartTracker();
       heartTracker.setHttrId(UUID.randomUUID());
       heartTracker.setUserId(userId);
       heartTracker.setHttrTracker(tracker);
       heartTracker.setCreatedDttm(new Date());
       heartTracker.setDeleteFl(Boolean.FALSE);
       heartTracker.setPtnId(1);
       cassandraTemplate.insert(heartTracker);
     } else {
       heartTracker = heartTrackers.get(0);
     }
     HeartRate heartRate = new HeartRate();
     heartRate.setHtrtId(UUID.randomUUID());
     heartRate.setHttrId(heartTracker.getHttrId());
     heartRate.setHtrtDttm(formatter.parse(dttm));
     heartRate.setHtrtValue(Integer.valueOf(payloadMap.get("Value")));
     heartRate.setUserId(userId);
     heartRate.setCreatedDttm(new Date());
     heartRate.setDeleteFl(Boolean.FALSE);
     heartRate.setPtnId(1);
     cassandraTemplate.insert(heartRate);
   } catch (IOException e) {
     logger.error("Exception occured in Heart Rate Message Processing. ", e);
     throw new MessageProcessingException(e);
   } catch (ParseException e) {
     logger.error("Exception occured in Date Conversion. Invalid Date. " + dttm, e);
     throw new MessageProcessingException(e);
   }
 }
 private void insertMetricIntoBatch(Metric metric, Map<RetentionTable, BatchStatement> map) {
   Object[] values = {metric.name(), metric.timestamp(), metric.value()};
   Optional<RetentionTable> table = environment.retentions().findAccessTableForMetric(metric);
   if (!table.isPresent()) {
     logger.warn("No retention defined - not outputting metric! {}", metric);
   } else {
     map.get(table.get())
         .add(QueryBuilder.insertInto(table.get().tableName()).values(COLUMNS, values));
   }
 }
  private Statement createStatementToCheckIfFollowingExists(String userId, String applicationId) {
    UUID appUuid = UUID.fromString(applicationId);
    UUID userUuid = UUID.fromString(userId);

    return QueryBuilder.select()
        .countAll()
        .from(Follow.TABLE_NAME_APP_FOLLOWERS)
        .where(eq(USER_ID, userUuid))
        .and(eq(APP_ID, appUuid));
  }
Exemplo n.º 21
0
  /**
   * @deprecated This method needs additional testing and thus isn't recommended to use as of
   *     October, 2015.
   */
  public ByteBuffer[] getEpIdsBySdkToken(String sdkToken) {
    LOG.debug("Trying to find a list of enpoint key hash values by SDK token {}", sdkToken);

    Statement query =
        QueryBuilder.select()
            .from(this.getColumnFamilyName())
            .where(QueryBuilder.eq(EP_BY_SDK_TOKEN_SDK_TOKEN_PROPERTY, sdkToken));

    List<CassandraEpBySdkToken> queryResult = this.findListByStatement(query);
    ByteBuffer[] result = new ByteBuffer[queryResult.size()];

    int pos = 0;
    for (CassandraEpBySdkToken endpointProfile : queryResult) {
      result[pos++] = endpointProfile.getEndpointKeyHash();
    }

    LOG.debug("Endpoint profile hash values found: {}", Arrays.toString(result));

    return result;
  }
  /** {@inheritDoc} */
  @Override
  protected final void handleMessages(List<T> messages) {
    long start = System.nanoTime();
    // Create a batch of message that we want to write.
    List<RegularStatement> statements = new ArrayList<>();
    for (T t : messages) {
      try {
        handleMessage(statements, t);
      } catch (RuntimeException e) {
        LOG.warn("Failed to write message: " + t, e); // Just in case we cannot process a message
      }
    }

    // Try writing the batch
    try {
      Batch batch = QueryBuilder.batch(statements.toArray(new RegularStatement[statements.size()]));

      long beforeSend = System.nanoTime();

      ResultSetFuture f = connection.getSession().executeAsync(batch);
      f.getUninterruptibly(); // throws QueryValidationExecption etc

      long total = System.nanoTime();
      // Is this an abnormal slow batch?
      boolean isSlow =
          TimeUnit.MILLISECONDS.convert(total - start, TimeUnit.NANOSECONDS) > 200
              || messages.size() >= getBatchSize();
      if (isSlow || lastSlowBatch > 0) {
        LOG.info(
            "Total time: "
                + DurationFormatter.DEFAULT.formatNanos(total - start)
                + ", prepping="
                + DurationFormatter.DEFAULT.formatNanos(beforeSend - start)
                + ", sending="
                + DurationFormatter.DEFAULT.formatNanos(total - beforeSend)
                + ", size="
                + messages.size());
        // makes sure we write 10 info statements after the last slow batch we insert
        lastSlowBatch = isSlow ? 10 : lastSlowBatch - 1;
      }
      persistedCount.mark(messages.size());
      // sink.onSucces(messages);
    } catch (QueryValidationException e) {
      LOG.error("Could not execute query, this is an internal error", e);
    } catch (Exception e) {
      onFailure(messages, e);
      try {
        sleepUntilShutdown(2, TimeUnit.SECONDS);
      } catch (InterruptedException ignore) {
        Thread.interrupted();
      }
    }
  }
Exemplo n.º 23
0
 Indexer(
     Session session,
     @Nullable Integer indexTtl,
     @Nullable ConcurrentMap<PartitionKeyToTraceId, Pair<Long>> sharedState,
     IndexSupport index) {
   this.index = index;
   this.boundName = UPPER_CAMEL.to(LOWER_HYPHEN, index.getClass().getSimpleName());
   Insert insert =
       index.declarePartitionKey(
           QueryBuilder.insertInto(index.table())
               .value("ts", QueryBuilder.bindMarker("ts"))
               .value("trace_id", QueryBuilder.bindMarker("trace_id")));
   if (indexTtl != null) {
     insert.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_")));
   }
   this.prepared = session.prepare(insert);
   this.indexTtl = indexTtl;
   this.session = session;
   this.timestampCodec = new TimestampCodec(session);
   this.sharedState = sharedState;
 }
  public void delete(CassandraPersistenceSession session, EventSubscriptionEntity entity) {
    session.addStatement(
        QueryBuilder.delete()
            .mapElt("event_subscriptions", entity.getId())
            .from(ProcessInstanceTableHandler.TABLE_NAME)
            .where(eq("id", entity.getProcessInstanceId())),
        entity.getProcessInstanceId());

    for (IndexHandler<EventSubscriptionEntity> index : indexHandlers.values()) {
      session.addIndexStatement(
          index.getDeleteStatement(session, entity), entity.getProcessInstanceId());
    }
  }
  private void controlCassandra() {
    Insert insert = QueryBuilder.insertInto("usuario");
    insert.setConsistencyLevel(ConsistencyLevel.ONE);
    insert.value("id", UUID.randomUUID());
    insert.value("nombre", "Alison");
    insert.value("email", "gmailalgo");

    cassandraOperations.execute(insert);

    Select select = QueryBuilder.select().from("demo", "usuario");

    select.limit(100);

    List<usuario> results = cassandraOperations.select(select, usuario.class);

    results.forEach(r -> System.out.println(r));

    Map<String, String> p = new HashMap<String, String>();
    p.putIfAbsent("hola", "caracola");

    Insert insertSample = QueryBuilder.insertInto("sample");
    insertSample.setConsistencyLevel(ConsistencyLevel.ONE);
    insertSample.value("userid", UUID.randomUUID().toString());
    insertSample.value("todo", p);

    cassandraOperations.execute(insertSample);

    Select selectSample = QueryBuilder.select().from("demo", "sample");

    selectSample.limit(100);

    List<sample> resultsSample = cassandraOperations.select(selectSample, sample.class);

    for (sample s : resultsSample) {
      System.out.println(s);
      s.getTodo().entrySet().forEach(e -> System.out.println(" " + e));
    }
  }
  protected Statement createUpdateStatement(
      CassandraPersistenceSession session, EventSubscriptionEntity entity) {
    Session s = session.getSession();
    UDTypeHandler typeHander = session.getTypeHander(EventSubscriptionEntity.class);
    CassandraSerializer<EventSubscriptionEntity> serializer =
        session.getSerializer(EventSubscriptionEntity.class);

    UDTValue value = typeHander.createValue(s);
    serializer.write(value, entity);

    return QueryBuilder.update(ProcessInstanceTableHandler.TABLE_NAME)
        .with(put("event_subscriptions", entity.getId(), value))
        .where(eq("id", entity.getProcessInstanceId()));
  }
  private Statement createQueryForFollowersOfApp(String applicationId) {
    UUID appUuid = UUID.fromString(applicationId);

    return QueryBuilder.select()
        .column(Follow.APP_NAME)
        .as(Applications.APP_NAME)
        .column(Follow.APP_ID)
        .as(Applications.APP_ID)
        .column(Follow.USER_FIRST_NAME)
        .as(Users.FIRST_NAME)
        .column(Follow.TIME_OF_FOLLOW)
        .column(Follow.USER_ID)
        .from(Follow.TABLE_NAME_APP_FOLLOWERS)
        .where(eq(APP_ID, appUuid));
  }
  private Statement createQueryForAppsFollowedBy(String userId) {
    UUID userUuid = UUID.fromString(userId);

    return QueryBuilder.select()
        .column(Follow.APP_NAME)
        .as(Applications.APP_NAME)
        .column(Follow.APP_ID)
        .as(Applications.APP_ID)
        .column(Follow.USER_FIRST_NAME)
        .as(Users.FIRST_NAME)
        .column(Follow.TIME_OF_FOLLOW)
        .column(Follow.USER_ID)
        .from(Follow.TABLE_NAME_USER_FOLLOWING)
        .where(eq(USER_ID, userUuid));
  }
 @Test
 public void doAppendTest() throws IOException, InterruptedException {
   DeliveryCallback callback = new DeliveryCallback();
   logAppender.doAppend(generateLogEventPack(20), callback);
   Thread.sleep(3000);
   CassandraLogEventDao logEventDao =
       (CassandraLogEventDao) ReflectionTestUtils.getField(logAppender, "logEventDao");
   Session session = (Session) ReflectionTestUtils.getField(logEventDao, "session");
   ResultSet resultSet =
       session.execute(
           QueryBuilder.select()
               .countAll()
               .from(
                   KEY_SPACE_NAME, "logs_" + appToken + "_" + Math.abs(configuration.hashCode())));
   Row row = resultSet.one();
   Assert.assertEquals(20L, row.getLong(0));
   Assert.assertEquals(1, callback.getSuccessCount());
 }
  @Test
  public void testBasicCassandraInsert() throws Exception {
    Book b1 = new Book();
    b1.setIsbn("123456-1");
    b1.setTitle("Spring Integration Cassandra");
    b1.setAuthor("Cassandra Guru");
    b1.setPages(521);
    b1.setSaleDate(new Date());
    b1.setInStock(true);

    Message<Book> message = MessageBuilder.withPayload(b1).build();
    this.cassandraMessageHandler1.handleMessage(message);

    Select select = QueryBuilder.select().all().from("book");
    List<Book> books = this.template.select(select, Book.class);
    assertEquals(1, books.size());

    this.template.delete(b1);
  }