Java Code Examples for com.datastax.driver.core.Row#getUUID()

The following examples show how to use com.datastax.driver.core.Row#getUUID() . 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: CassandraSessionDAO.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected Session doReadSession(Serializable sessionId) {

   UUID id = toUuid(sessionId);

   PreparedStatement ps = prepareReadStatement();
   BoundStatement bs = new BoundStatement(ps);
   bs.bind(id);

   ResultSet results = cassandraSession.execute(bs);

   for(Row row : results) {
      UUID rowId = row.getUUID("id");
      if (id.equals(rowId)) {
         ByteBuffer buffer = row.getBytes("serialized_value");
         if (buffer != null) { //could be null if a tombstone due to TTL removal
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            return serializer.deserialize(bytes);
         }
      }
   }

   return null;
}
 
Example 2
Source File: UpdateIpcdStateColumns.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void execute(ExecutionContext context, boolean autoRollback) throws CommandExecutionException {
   Session session = context.getSession();
   PreparedStatement update = session.prepare(UPDATE_STATES);

   BoundStatement select = session.prepare(SELECT).bind();
   select.setConsistencyLevel(ConsistencyLevel.ALL);
   ResultSet rs = context.getSession().execute(select);
   for(Row row: rs) {
      String protocolAddress = row.getString("protocoladdress");
      UUID placeId = row.getUUID("placeid");
      BoundStatement bs = new BoundStatement(update);
      bs.setString("connState", "ONLINE");
      bs.setString("registrationState", placeId == null ? "UNREGISTERED" : "REGISTERED");
      bs.setString("protocolAddress", protocolAddress);
      session.execute(bs);
   }
}
 
Example 3
Source File: UpdateSecurityQuestions.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ExecutionContext context, boolean autoRollback) throws CommandExecutionException {
   Session session = context.getSession();
   PreparedStatement update = session.prepare(UPDATE);
   
   ResultSet rs = context.getSession().execute(SELECT);
   for(Row row: rs) {
      UUID id = row.getUUID("id");
      Map<String, String> oldQuestions = row.getMap("securityAnswers", String.class, String.class);
      Map<String, String> newQuestions = rewrite(oldQuestions);

      logger.debug("Remapping security answers for [{}]...", id);

      BoundStatement bs = update.bind(newQuestions, id);
      session.execute(bs);
   }
}
 
Example 4
Source File: BookRepository.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Select book by id.
 * 
 * @return
 */
public Book selectByTitle(String title) {
    StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';");

    final String query = sb.toString();

    ResultSet rs = session.execute(query);

    List<Book> books = new ArrayList<Book>();

    for (Row r : rs) {
        Book s = new Book(r.getUUID("id"), r.getString("title"), null, null);
        books.add(s);
    }

    return books.get(0);
}
 
Example 5
Source File: CassandraTweetRepository.java    From twissandra-j with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
public List<Tweet> getUserline(String username, Date start, int limit) {
	ResultSet queryResult = execute(
			"SELECT tweetid, body FROM userline WHERE username = '%s' AND tweetid < maxTimeuuid('%d') ORDER BY tweetid DESC LIMIT %d",
			username,
			start.getTime(),
			limit);
	List<Tweet> tweets = new ArrayList<Tweet>();
	
	for (Row row : queryResult) {
		UUID id = row.getUUID("tweetid");
		tweets.add(new Tweet(username, row.getString("body"), id, fromUUID1(id)));
	}

	return tweets;
}
 
Example 6
Source File: Common.java    From glowroot with Apache License 2.0 6 votes vote down vote up
static List<NeedsRollupFromChildren> getNeedsRollupFromChildrenList(String agentRollupId,
        PreparedStatement readNeedsRollupFromChild, Session session) throws Exception {
    BoundStatement boundStatement = readNeedsRollupFromChild.bind();
    boundStatement.setString(0, agentRollupId);
    ResultSet results = session.read(boundStatement);
    Map<Long, NeedsRollupFromChildren> needsRollupFromChildrenMap = new LinkedHashMap<>();
    for (Row row : results) {
        int i = 0;
        long captureTime = checkNotNull(row.getTimestamp(i++)).getTime();
        UUID uniqueness = row.getUUID(i++);
        String childAgentRollupId = checkNotNull(row.getString(i++));
        Set<String> keys = checkNotNull(row.getSet(i++, String.class));
        NeedsRollupFromChildren needsRollup = needsRollupFromChildrenMap.get(captureTime);
        if (needsRollup == null) {
            needsRollup = new NeedsRollupFromChildren(captureTime);
            needsRollupFromChildrenMap.put(captureTime, needsRollup);
        }
        for (String key : keys) {
            needsRollup.keys.put(key, childAgentRollupId);
        }
        needsRollup.uniquenessKeysForDeletion.add(uniqueness);
    }
    return ImmutableList.copyOf(needsRollupFromChildrenMap.values());
}
 
Example 7
Source File: AgentConfigDao.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<AgentConfigAndUpdateToken> load(String agentRollupId) throws Exception {
    BoundStatement boundStatement = readPS.bind();
    boundStatement.setString(0, agentRollupId);
    ResultSet results = session.read(boundStatement);
    Row row = results.one();
    if (row == null) {
        // agent must have been manually deleted
        return Optional.absent();
    }
    int i = 0;
    ByteBuffer bytes = checkNotNull(row.getBytes(i++));
    UUID updateToken = row.getUUID(i++);
    return Optional.of(ImmutableAgentConfigAndUpdateToken.builder()
            .config(AgentConfig.parseFrom(bytes))
            .updateToken(updateToken)
            .build());
}
 
Example 8
Source File: CassandraIpcdDeviceDao.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void parseOptimisticResult(ResultSet rs, String protocolAddress, UUID requiredPlace) throws IpcdDaoException {
   // not applied could imply that the device doesn't exist or the place didn't match
   if(!rs.wasApplied()) {
      Row r = rs.one();
      ColumnDefinitions colDef = r.getColumnDefinitions();

      if(colDef.contains(IpcdDeviceTable.Columns.PLACE_ID)) {
         // if the returned row contains a place id, the place id didn't match
         UUID actualPlaceId = r.getUUID(IpcdDeviceTable.Columns.PLACE_ID);
         if(!Objects.equal(requiredPlace, actualPlaceId)) {
            throw new PlaceMismatchException(requiredPlace, actualPlaceId);
         }
      }
      // special case for claiming device that is offline
      if(colDef.contains(IpcdDeviceTable.Columns.CONN_STATE) && IpcdDevice.ConnState.OFFLINE.name().equals(r.getString(IpcdDeviceTable.Columns.CONN_STATE))) {
         throw new DeviceNotFoundException(protocolAddress);
      }
      throw new DeviceNotFoundException(protocolAddress);
   }
}
 
Example 9
Source File: TransferLogSerializationImpl.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public Result<TransferLog> getAllTransferLogs(PagingState pagingState, int fetchSize ) {

    Statement query = QueryBuilder.select().all().from(TABLE_TRANSFER_LOG);

    query.setFetchSize( fetchSize );
    if ( pagingState != null ) {
        query.setPagingState( pagingState );
    }

    ResultSet rs = cassandraClient.getApplicationSession().execute( query );
    final PagingState newPagingState = rs.getExecutionInfo().getPagingState();

    final List<TransferLog> transferLogs = new ArrayList<>();
    int numReturned = rs.getAvailableWithoutFetching();
    for ( int i=0; i<numReturned; i++ ) {
        Row row = rs.one();
        TransferLog tlog = new TransferLog(
                row.getString( COLUMN_QUEUE_NAME ),
                row.getString( COLUMN_SOURCE_REGION ),
                row.getString( COLUMN_DEST_REGION ),
                row.getUUID( COLUMN_MESSAGE_ID ),
                row.getLong( COLUMN_TRANSFER_TIME ));
        transferLogs.add( tlog );
    }

    return new Result<TransferLog>() {

        @Override
        public PagingState getPagingState() {
            return newPagingState;
        }

        @Override
        public List<TransferLog> getEntities() {
            return transferLogs;
        }
    };
}
 
Example 10
Source File: PurgeRecordingV2Table.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected PurgeRecord buildEntity(Row row) {
	String storageStr = row.getString(COL_STORAGE);
	boolean purgePreview = false;
	if(StringUtils.isNotBlank(storageStr) && storageStr.endsWith(PURGE_PREVIEW_SUFFIX)) {
		storageStr = storageStr.substring(0, storageStr.length()-2);
		purgePreview = true;
	}
	return new PurgeRecord(row.getTimestamp(COL_DELETETIME), row.getInt(COL_PARTITIONID), row.getUUID(COL_RECORDINGID), row.getUUID(COL_PLACEID), storageStr, true, purgePreview);
}
 
Example 11
Source File: InvitationDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private Invitation build(Row r) {
   if(r == null) {
      return null;
   }
   Invitation invitation = new Invitation();
   invitation.setAccepted(r.getTimestamp(Column.accepted.name()));
   invitation.setCity(r.getString(Column.city.name()));
   invitation.setCode(r.getString(Column.code.name()));
   invitation.setCreated(r.getTimestamp(Column.created.name()));
   invitation.setInvitationText(r.getString(Column.invitationText.name()));
   invitation.setInviteeEmail(r.getString(Column.inviteeEmail.name()));
   invitation.setInviteeFirstName(r.getString(Column.inviteeFirstName.name()));

   UUID inviteeId = r.getUUID(Column.inviteeId.name());
   invitation.setInviteeId(inviteeId == null ? null : inviteeId.toString());

   invitation.setInviteeLastName(r.getString(Column.inviteeLastName.name()));
   invitation.setInvitorFirstName(r.getString(Column.invitorFirstName.name()));
   invitation.setInvitorId(r.getUUID(Column.invitorId.name()).toString());
   invitation.setInvitorLastName(r.getString(Column.invitorLastName.name()));
   invitation.setPersonalizedGreeting(r.getString(Column.personalizedGreeting.name()));
   invitation.setPlaceId(r.getUUID(Column.placeId.name()).toString());
   invitation.setPlaceName(r.getString(Column.placeName.name()));
   invitation.setPlaceOwnerFirstName(r.getString(Column.placeOwnerFirstName.name()));
   invitation.setPlaceOwnerId(r.getUUID(Column.placeOwnerId.name()).toString());
   invitation.setPlaceOwnerLastName(r.getString(Column.placeOwnerLastName.name()));
   invitation.setRejected(r.getTimestamp(Column.rejected.name()));
   invitation.setRejectReason(r.getString(Column.rejectReason.name()));
   invitation.setRelationship(r.getString(Column.relationship.name()));
   invitation.setStateProv(r.getString(Column.stateProv.name()));
   invitation.setStreetAddress1(r.getString(Column.streetAddress1.name()));
   invitation.setStreetAddress2(r.getString(Column.streetAddress2.name()));
   invitation.setZipCode(r.getString(Column.zipCode.name()));

   return invitation;
}
 
Example 12
Source File: GenerateIpcdPartitionId.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public void execute(ExecutionContext context, boolean autoRollback) throws CommandExecutionException {
   Session session = context.getSession();
   PreparedStatement update = session.prepare(UPSERT_PARTITIONID);

   BoundStatement select = session.prepare(SELECT).bind();
   select.setConsistencyLevel(ConsistencyLevel.ALL);
   ResultSet rs = context.getSession().execute(select);
   int count = 0;
   int [] devsPerPartition = new int[partitionCount];
   logger.info("Preparing to partition ipcd devices...");
   long startTimeNs = System.nanoTime();
   for(Row row: rs) {
      String protocolAddress = row.getString("protocoladdress");
      UUID placeId = row.getUUID("placeid");
      int partitionId;
      if(placeId == null) {
         partitionId = 0;
      } else {
         partitionId = (int) (Math.floorMod(placeId.getLeastSignificantBits(), partitionCount));
      }

      logger.debug("Adding [{}] to partition [{}]", protocolAddress, partitionId);
      BoundStatement bs = update.bind(partitionId, protocolAddress);
      session.execute(bs);

      count++;
      devsPerPartition[partitionId]++;
   }
   long duration = System.nanoTime() - startTimeNs;
   logger.info("Partitioned {} ipcd devices in {} secs", count, duration / (float) TimeUnit.NANOSECONDS.toSeconds(1));
   for(int i=0; i<partitionCount; i++) {
      logger.info(String.format("%03d: %3d devs", i, devsPerPartition[i]));
   }
}
 
Example 13
Source File: PlacePurgeRecordingTable.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public PlacePurgeRecord buildEntity(Row row) {
	PurgeMode mode = PurgeMode.ALL;
	if(!row.isNull(COL_MODE)) {
		mode = PurgeMode.valueOf(row.getString(COL_MODE));
	}
	return new PlacePurgeRecord(row.getUUID(COL_PLACEID), row.getTimestamp(COL_DELETE_TIME), mode);
	
}
 
Example 14
Source File: RemoveAlarmSubsystem.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected void doExecute(ExecutionContext context) throws CommandExecutionException {
   PreparedStatement stmt = context.getSession().prepare(SUSPEND_ALARMSUBSYSTEM);

   for(Row row: context.getSession().execute(SELECT_PLACE)) {
		UUID placeId = row.getUUID("id");
   	logger.debug("Disabling for place [{}]", placeId);
		context.getSession().execute( stmt.bind(placeId) );
   }
}
 
Example 15
Source File: AbstractPurgeRecordingTable.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public UUID getPlaceId(Row row) {
	return row.getUUID(COL_PLACEID);
}
 
Example 16
Source File: PlaceDAOImpl.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
protected UUID getIdFromRow(Row row) {
   return row.getUUID(BaseEntityColumns.ID);
}
 
Example 17
Source File: CqlDeltaIterator.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Override
protected UUID getChangeId(Row row) {
    return row.getUUID(_changeIdIndex);
}
 
Example 18
Source File: AbstractPlaceRecordingIndexV2Table.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public UUID getRecordingId(Row row) {
	return row.getUUID(COL_RECORDINGID);
}
 
Example 19
Source File: GenerateHubPartitionId.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public void execute(ExecutionContext context, boolean autoRollback) throws CommandExecutionException {
   Session session = context.getSession();
   PreparedStatement update = session.prepare(UPSERT_PARTITIONID);
   
   BoundStatement select = session.prepare(SELECT).bind();
   select.setConsistencyLevel(ConsistencyLevel.ALL);
   ResultSet rs = context.getSession().execute(select);
   int count = 0;
   int [] hubsPerPartition = new int[partitionCount];
   logger.info("Preparing to partition hub ids");
   long startTimeNs = System.nanoTime();
   for(Row row: rs) {
      String hubId = row.getString("id");
      UUID placeId = row.getUUID("placeid");
      int partitionId;
      if(placeId == null) {
         Matcher m = PATTERN_HUBID.matcher(hubId);
         if(!m.matches()) {
            logger.warn("Invalid hub id: [{}]", hubId);
            return;
         }
         String hubNum = m.group(1);
         partitionId = Integer.parseInt(hubNum) % partitionCount;  
      }
      else {
         partitionId = (int) (Math.floorMod(placeId.getLeastSignificantBits(), partitionCount));
      }

      logger.debug("Adding [{}] to partition [{}]", hubId, partitionId);
      BoundStatement bs = update.bind(partitionId, hubId);
      session.execute(bs);
      
      count++;
      hubsPerPartition[partitionId]++;
   }
   long duration = System.nanoTime() - startTimeNs;
   logger.info("Partitioned {} hubs in {} secs", count, duration / (float) TimeUnit.NANOSECONDS.toSeconds(1));
   for(int i=0; i<partitionCount; i++) {
      logger.info(String.format("%03d: %3d hubs", i, hubsPerPartition[i]));
   }
}
 
Example 20
Source File: AbstractPlaceRecordingIndexV2Table.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public VideoRecordingSize materializeVideoRecordingSize(Row row) {
	return new VideoRecordingSize(row.getUUID(COL_RECORDINGID), row.getLong(COL_SIZE), isFavoriteTable());
}