Java Code Examples for com.datastax.driver.core.BoundStatement#setConsistencyLevel()

The following examples show how to use com.datastax.driver.core.BoundStatement#setConsistencyLevel() . 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: 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 2
Source File: VersionHistoryDAO.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void insert(VersionHistory history) {

      // can't prepare these early because they may not exist if the system has not been bootstrapped
      if(insert == null) {
         insert = this.session.prepare(INSERT);
      }

      BoundStatement boundStatement = new BoundStatement(insert);
      boundStatement.setConsistencyLevel(ConsistencyLevel.ALL);
      session.execute(boundStatement.bind(
            IDENTIFIER,
            history.getVersion(),
            history.getTimestamp(),
            history.getStatus().toString(),
            history.getUsername()
      ));
   }
 
Example 3
Source File: GuicedCassandraSessionDAO.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private Session doCassandraReadSession(Serializable sessionId) {
   UUID id = toUuid(sessionId);
   BoundStatement bs = new BoundStatement(this.readPreparedStatement);
   bs.bind(id);
   bs.setConsistencyLevel(consistencyLevel);

   ResultSet results = cassandraSession.execute(bs);

   for(Row row : results) {
      Session session = hydrateSession(id, row);
      if (session != null && !isExpired(session)) {
      	return session;
      }
   }

   throw NO_SESSION_EXCEPTION;
}
 
Example 4
Source File: CassandraSearcher.java    From newts with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the set of resource ids that match the given
 * term query.
 */
private Set<String> searchForIds(Context context, TermQuery query, ConsistencyLevel readConsistency) {
    Set<String> ids = Sets.newTreeSet();

    BoundStatement bindStatement = m_searchStatement.bind();
    bindStatement.setString(Schema.C_TERMS_CONTEXT, context.getId());
    bindStatement.setString(Schema.C_TERMS_FIELD, query.getTerm().getField(Constants.DEFAULT_TERM_FIELD));
    bindStatement.setString(Schema.C_TERMS_VALUE, query.getTerm().getValue());
    bindStatement.setConsistencyLevel(readConsistency);

    for (Row row : m_session.execute(bindStatement)) {
        ids.add(row.getString(Constants.Schema.C_TERMS_RESOURCE));
    }

    return ids;
}
 
Example 5
Source File: CassandraSampleRepository.java    From newts with Apache License 2.0 6 votes vote down vote up
private Iterator<com.datastax.driver.core.Row> cassandraSelect(Context context, Resource resource,
                                                               Timestamp start, Timestamp end) {

    List<Future<ResultSet>> futures = Lists.newArrayList();

    Duration resourceShard = m_contextConfigurations.getResourceShard(context);
    Timestamp lower = start.stepFloor(resourceShard);
    Timestamp upper = end.stepFloor(resourceShard);

    for (Timestamp partition : new IntervalGenerator(lower, upper, resourceShard)) {
        BoundStatement bindStatement = m_selectStatement.bind();
        bindStatement.setString(SchemaConstants.F_CONTEXT, context.getId());
        bindStatement.setInt(SchemaConstants.F_PARTITION, (int) partition.asSeconds());
        bindStatement.setString(SchemaConstants.F_RESOURCE, resource.getId());
        bindStatement.setTimestamp("start", start.asDate());
        bindStatement.setTimestamp("end", end.asDate());
        // Use the context specific consistency level
        bindStatement.setConsistencyLevel(m_contextConfigurations.getReadConsistency(context));

        futures.add(m_session.executeAsync(bindStatement));
    }

    return new ConcurrentResultWrapper(futures);
}
 
Example 6
Source File: GeneratePlacePartitionId.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);
   update.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
   
   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 place ids");
   long startTimeNs = System.nanoTime();
   for(Row row: rs) {
      UUID placeId = row.getUUID("id");
      int partitionId = (int) (Math.floorMod(placeId.getLeastSignificantBits(), partitionCount));

      logger.debug("Adding [{}] to partition [{}]", placeId, partitionId);
      BoundStatement bs = update.bind(partitionId, placeId);
      session.execute(bs);
      
      count++;
      hubsPerPartition[partitionId]++;
   }
   long duration = System.nanoTime() - startTimeNs;
   logger.info("Partitioned {} place in {} secs", count, duration / (float) TimeUnit.NANOSECONDS.toSeconds(1));
   for(int i=0; i<partitionCount; i++) {
      logger.info(String.format("%03d: %3d places", i, hubsPerPartition[i]));
   }
}
 
Example 7
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 8
Source File: CassandraSessionDAO.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected void save(SimpleSession ss) {

      //Cassandra TTL values are in seconds, so we need to convert from Shiro's millis:
      int timeoutInSeconds = (int)(ss.getTimeout() / 1000);

      PreparedStatement ps = prepareSaveStatement();
      BoundStatement bs = new BoundStatement(ps);

      byte[] serialized = serializer.serialize(ss);

      ByteBuffer bytes = ByteBuffer.wrap(serialized);

      bs.bind(
            timeoutInSeconds,
            ss.getStartTimestamp(),
            ss.getStopTimestamp() != null ? ss.getStartTimestamp() : null,
            ss.getLastAccessTime(),
            ss.getTimeout(),
            ss.isExpired(),
            ss.getHost(),
            bytes,
            ss.getId()
      );
      // TODO drop this down when we add session caching
      bs.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);

      cassandraSession.execute(bs);
   }
 
Example 9
Source File: GuicedCassandraSessionDAO.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(Session session) {
   BoundStatement bs = new BoundStatement(this.deletePreparedStatement);
   bs.bind(session.getId());
   bs.setConsistencyLevel(consistencyLevel);
   cassandraSession.execute(bs);
   sessionCache.invalidate(session.getId());
}
 
Example 10
Source File: AbstractUpsertOutputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private BoundStatement setDefaultsAndPrepareBoundStatement(UpsertExecutionContext tuple)
{
  UpsertExecutionContext.NullHandlingMutationStyle nullHandlingMutationStyle = tuple.getNullHandlingMutationStyle();
  if (UpsertExecutionContext.NullHandlingMutationStyle.UNDEFINED == nullHandlingMutationStyle) {
    nullHandlingMutationStyle = UpsertExecutionContext.NullHandlingMutationStyle.SET_NULL_COLUMNS;
  }
  boolean setNulls = true;
  if (nullHandlingMutationStyle != UpsertExecutionContext.NullHandlingMutationStyle.SET_NULL_COLUMNS) {
    setNulls = false;
  }
  UpsertExecutionContext.CollectionMutationStyle collectionMutationStyle = tuple.getCollectionMutationStyle();
  if ((collectionMutationStyle == null) ||
      (collectionMutationStyle == UpsertExecutionContext.CollectionMutationStyle.UNDEFINED) ) {
    tuple.setCollectionMutationStyle(UpsertExecutionContext.CollectionMutationStyle.ADD_TO_EXISTING_COLLECTION);
  }
  UpsertExecutionContext.ListPlacementStyle listPlacementStyle = tuple.getListPlacementStyle();
  if ( (listPlacementStyle == null) || (listPlacementStyle == UpsertExecutionContext.ListPlacementStyle.UNDEFINED) ) {
    tuple.setListPlacementStyle(UpsertExecutionContext.ListPlacementStyle.APPEND_TO_EXISTING_LIST);
  }
  PreparedStatement preparedStatement = resolvePreparedStatementForCurrentExecutionContext(tuple);
  BoundStatement stmnt = processPayloadForExecution(preparedStatement, tuple, setNulls);
  if ((tuple.isTtlOverridden()) || (connectionStateManager.isTTLSet())) {
    int ttlToUse = connectionStateManager.getDefaultTtlInSecs();
    if (tuple.isTtlOverridden()) {
      ttlToUse = tuple.getOverridingTTL();
    }
    stmnt.setInt(CassandraPreparedStatementGenerator.TTL_PARAM_NAME, ttlToUse);
  }
  if (tuple.isOverridingConsistencyLevelSet()) {
    ConsistencyLevel currentConsistencyLevel = tuple.getOverridingConsistencyLevel();
    if (currentConsistencyLevel.isSerial()) {
      stmnt.setSerialConsistencyLevel(tuple.getOverridingConsistencyLevel());
    } else {
      stmnt.setConsistencyLevel(tuple.getOverridingConsistencyLevel());
    }
  }
  LOG.debug("Executing statement " + preparedStatement.getQueryString());
  return stmnt;
}
 
Example 11
Source File: CassandraSearcher.java    From newts with Apache License 2.0 5 votes vote down vote up
private ResultSetFuture fetchResourceAttributes(Context context, String resourceId, ConsistencyLevel readConsistency) {
    BoundStatement bindStatement = m_selectAttributesStatement.bind();
    bindStatement.setString(Schema.C_ATTRS_CONTEXT, context.getId());
    bindStatement.setString(Schema.C_ATTRS_RESOURCE, resourceId);
    bindStatement.setConsistencyLevel(readConsistency);

    return m_session.executeAsync(bindStatement);
}
 
Example 12
Source File: CassandraSearcher.java    From newts with Apache License 2.0 5 votes vote down vote up
private ResultSetFuture fetchMetricNames(Context context, String resourceId, ConsistencyLevel readConsistency) {
    BoundStatement bindStatement = m_selectMetricNamesStatement.bind();
    bindStatement.setString(Schema.C_METRICS_CONTEXT, context.getId());
    bindStatement.setString(Schema.C_METRICS_RESOURCE, resourceId);
    bindStatement.setConsistencyLevel(readConsistency);

    return m_session.executeAsync(bindStatement);
}
 
Example 13
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 14
Source File: GuicedCassandraSessionDAO.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
protected void save(SimpleSession ss) {
	
   //Cassandra TTL values are in seconds, so we need to convert from Shiro's millis:
   int timeoutInSeconds = (int)(ss.getTimeout() / 1000);

   BoundStatement bs = new BoundStatement(this.savePreparedStatement);
   
   Map<String,String> attributes = new HashMap<>();
   for (Object key : ss.getAttributeKeys()) {
   	if (key instanceof String) {
   		Object value = ss.getAttribute(key);
   		if (value instanceof Serializable) {
   			attributes.put((String)key, gson.toJson(value));
   		}
   		else {
   			logger.error("Could not store un-serializable attribute in Session. Session {}: Key{}", ss.getId(), key);
   		}
   	}
   	else {
   		logger.error("Session attributes with non-string keys are not supported. Session {}: Key {}", ss.getId(), key);
   	}
   }
       
   // FIXME if isExpired() == true we should just delete the row...
   bs.bind(
         timeoutInSeconds,
         ss.getStartTimestamp(),
         ss.getStopTimestamp(),
         ss.getLastAccessTime(),
         ss.getTimeout(),
         ss.isExpired(),
         ss.getHost(),
         attributes,
         null,
         ss.getId()
   );
   bs.setConsistencyLevel(consistencyLevel);
   
   cassandraSession.execute(bs);      
   sessionCache.put(ss.getId(), ss);
}
 
Example 15
Source File: StatementHandler.java    From scalardb with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the consistency level for the specified {@link BoundStatement} and {@link Operation}
 *
 * @param bound a {@code BoundStatement}
 * @param operation an {@code Operation}
 */
protected void setConsistency(BoundStatement bound, Operation operation) {
  bound.setConsistencyLevel(StatementHandler.convert(operation, operation.getConsistency()));
  // set preferable consistency for the operation
  overwriteConsistency(bound, operation);
}