Java 类com.datastax.driver.core.PreparedStatement 实例源码

项目:sunbird-utils    文件:CassandraOperationImpl.java   
@Override
public Response getPropertiesValueById(String keyspaceName, String tableName, String id,
    String... properties) {
  long startTime = System.currentTimeMillis();
  ProjectLogger.log("Cassandra Service getPropertiesValueById method started at ==" + startTime,
      LoggerEnum.PERF_LOG);
  Response response = new Response();
  try {
    String selectQuery = CassandraUtil.getSelectStatement(keyspaceName, tableName, properties);
    PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(selectQuery);
    BoundStatement boundStatement = new BoundStatement(statement);
    ResultSet results =
        connectionManager.getSession(keyspaceName).execute(boundStatement.bind(id));
    response = CassandraUtil.createResponse(results);
  } catch (Exception e) {
    ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e);
    throw new ProjectCommonException(ResponseCode.SERVER_ERROR.getErrorCode(),
        ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode());
  }
  long stopTime = System.currentTimeMillis();
  long elapsedTime = stopTime - startTime;
  ProjectLogger.log("Cassandra Service getPropertiesValueById method end at ==" + stopTime
      + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG);
  return response;
}
项目:Lagerta    文件:CassandraSessionImpl.java   
/**
 * Tunes CQL statement execution options (consistency level, fetch option and etc.).
 *
 * @param statement Statement.
 * @return Modified statement.
 */
private Statement tuneStatementExecutionOptions(Statement statement) {
    String qry = "";
    if (statement instanceof BoundStatement) {
        qry = ((BoundStatement)statement).preparedStatement().getQueryString().trim().toLowerCase();
    }
    else if (statement instanceof PreparedStatement) {
        qry = ((PreparedStatement)statement).getQueryString().trim().toLowerCase();
    }
    boolean readStatement = qry.startsWith("select");
    boolean writeStatement = statement instanceof Batch || statement instanceof BatchStatement ||
        qry.startsWith("insert") || qry.startsWith("delete") || qry.startsWith("update");
    if (readStatement && readConsistency != null) {
        statement.setConsistencyLevel(readConsistency);
    }
    if (writeStatement && writeConsistency != null) {
        statement.setConsistencyLevel(writeConsistency);
    }
    if (fetchSize != null) {
        statement.setFetchSize(fetchSize);
    }
    return statement;
}
项目:Lagerta    文件:PersistenceController.java   
/**
 * Binds Ignite cache key and value object to {@link PreparedStatement}.
 *
 * @param statement statement to which key and value object should be bind.
 * @param key key object.
 * @param val value object.
 * @return statement with bounded key and value.
 */
public BoundStatement bindKeyValue(PreparedStatement statement, Object key, Object val) {
    KeyPersistenceSettings keySettings = persistenceSettings.getKeyPersistenceSettings();
    Object[] keyValues = getBindingValues(keySettings.getStrategy(),
        keySettings.getSerializer(), keySettings.getFields(), key);
    ValuePersistenceSettings valSettings = persistenceSettings.getValuePersistenceSettings();
    Object[] valValues = getBindingValues(valSettings.getStrategy(),
        valSettings.getSerializer(), valSettings.getFields(), val);
    Object[] values = new Object[keyValues.length + valValues.length];
    int i = 0;
    for (Object keyVal : keyValues) {
        values[i] = keyVal;
        i++;
    }
    for (Object valVal : valValues) {
        values[i] = valVal;
        i++;
    }
    return statement.bind(values);
}
项目:cassandra-java-driver-examples    文件:PreparedStatementExample.java   
public static void main(String[] args) {

        Session session = Connection.connect();     
        PreparedStatement preparedStatement = session.prepare("insert into user (id, name, age) values (?, ?, ?)");

        try {
            BoundStatement boundStatement = preparedStatement.bind(UUIDs.timeBased(), "Hector", 34);
            ResultSet rs = session.execute(boundStatement);
            System.out.println(rs);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        Connection.close();

    }
项目:cassandra-java-driver-examples    文件:BatchStatementExample.java   
public static void main(String[] args) {

        Session session = Connection.connect();     
        BatchStatement batchStatement = new BatchStatement();

        PreparedStatement preparedStatement = session.prepare("insert into user (id, name) values (?, ?)");
        int i = 0;
        while(i < 10) {
            batchStatement.add(preparedStatement.bind(UUIDs.timeBased(), "user-" + i));
            ++i;
        }

        try {
            ResultSet rs = session.execute(batchStatement);
            System.out.println(rs);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        Connection.close();

    }
项目:iotplatform    文件:CassandraBaseAttributesDao.java   
private PreparedStatement getSaveStmt() {
    if (saveStmt == null) {
        saveStmt = getSession().prepare("INSERT INTO " + ModelConstants.ATTRIBUTES_KV_CF +
                "(" + ENTITY_TYPE_COLUMN +
                "," + ENTITY_ID_COLUMN +
                "," + ATTRIBUTE_TYPE_COLUMN +
                "," + ATTRIBUTE_KEY_COLUMN +
                "," + LAST_UPDATE_TS_COLUMN +
                "," + ModelConstants.STRING_VALUE_COLUMN +
                "," + ModelConstants.BOOLEAN_VALUE_COLUMN +
                "," + ModelConstants.LONG_VALUE_COLUMN +
                "," + ModelConstants.DOUBLE_VALUE_COLUMN +
                ")" +
                " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");
    }
    return saveStmt;
}
项目:iotplatform    文件:CassandraBaseTimeseriesDao.java   
private AsyncFunction<List<Long>, List<ResultSet>> getFetchChunksAsyncFunction(EntityId entityId, String key, Aggregation aggregation, long startTs, long endTs) {
    return partitions -> {
        try {
            PreparedStatement proto = getFetchStmt(aggregation);
            List<ResultSetFuture> futures = new ArrayList<>(partitions.size());
            for (Long partition : partitions) {
                log.trace("Fetching data for partition [{}] for entityType {} and entityId {}", partition, entityId.getEntityType(), entityId.getId());
                BoundStatement stmt = proto.bind();
                stmt.setString(0, entityId.getEntityType().name());
                stmt.setUUID(1, entityId.getId());
                stmt.setString(2, key);
                stmt.setLong(3, partition);
                stmt.setLong(4, startTs);
                stmt.setLong(5, endTs);
                log.debug("Generated query [{}] for entityType {} and entityId {}", stmt, entityId.getEntityType(), entityId.getId());
                futures.add(executeAsyncRead(stmt));
            }
            return Futures.allAsList(futures);
        } catch (Throwable e) {
            log.error("Failed to fetch data", e);
            throw e;
        }
    };
}
项目:iotplatform    文件:CassandraBaseTimeseriesDao.java   
private PreparedStatement getSaveStmt(DataType dataType) {
    if (saveStmts == null) {
        saveStmts = new PreparedStatement[DataType.values().length];
        for (DataType type : DataType.values()) {
            saveStmts[type.ordinal()] = getSession().prepare("INSERT INTO " + ModelConstants.TS_KV_CF +
                    "(" + ModelConstants.ENTITY_TYPE_COLUMN +
                    "," + ModelConstants.ENTITY_ID_COLUMN +
                    "," + ModelConstants.KEY_COLUMN +
                    "," + ModelConstants.PARTITION_COLUMN +
                    "," + ModelConstants.TS_COLUMN +
                    "," + getColumnName(type) + ")" +
                    " VALUES(?, ?, ?, ?, ?, ?)");
        }
    }
    return saveStmts[dataType.ordinal()];
}
项目:iotplatform    文件:CassandraBaseTimeseriesDao.java   
private PreparedStatement getSaveTtlStmt(DataType dataType) {
    if (saveTtlStmts == null) {
        saveTtlStmts = new PreparedStatement[DataType.values().length];
        for (DataType type : DataType.values()) {
            saveTtlStmts[type.ordinal()] = getSession().prepare("INSERT INTO " + ModelConstants.TS_KV_CF +
                    "(" + ModelConstants.ENTITY_TYPE_COLUMN +
                    "," + ModelConstants.ENTITY_ID_COLUMN +
                    "," + ModelConstants.KEY_COLUMN +
                    "," + ModelConstants.PARTITION_COLUMN +
                    "," + ModelConstants.TS_COLUMN +
                    "," + getColumnName(type) + ")" +
                    " VALUES(?, ?, ?, ?, ?, ?) USING TTL ?");
        }
    }
    return saveTtlStmts[dataType.ordinal()];
}
项目:iotplatform    文件:CassandraBaseTimeseriesDao.java   
private PreparedStatement getFetchStmt(Aggregation aggType) {
    if (fetchStmts == null) {
        fetchStmts = new PreparedStatement[Aggregation.values().length];
        for (Aggregation type : Aggregation.values()) {
            if (type == Aggregation.SUM && fetchStmts[Aggregation.AVG.ordinal()] != null) {
                fetchStmts[type.ordinal()] = fetchStmts[Aggregation.AVG.ordinal()];
            } else if (type == Aggregation.AVG && fetchStmts[Aggregation.SUM.ordinal()] != null) {
                fetchStmts[type.ordinal()] = fetchStmts[Aggregation.SUM.ordinal()];
            } else {
                fetchStmts[type.ordinal()] = getSession().prepare("SELECT " +
                        String.join(", ", ModelConstants.getFetchColumnNames(type)) + " FROM " + ModelConstants.TS_KV_CF
                        + " WHERE " + ModelConstants.ENTITY_TYPE_COLUMN + " = ? "
                        + "AND " + ModelConstants.ENTITY_ID_COLUMN + " = ? "
                        + "AND " + ModelConstants.KEY_COLUMN + " = ? "
                        + "AND " + ModelConstants.PARTITION_COLUMN + " = ? "
                        + "AND " + ModelConstants.TS_COLUMN + " > ? "
                        + "AND " + ModelConstants.TS_COLUMN + " <= ?"
                        + (type == Aggregation.NONE ? " ORDER BY " + ModelConstants.TS_COLUMN + " DESC LIMIT ?" : ""));
            }
        }
    }
    return fetchStmts[aggType.ordinal()];
}
项目:iotplatform    文件:CassandraBaseTimeseriesDao.java   
private PreparedStatement getFindLatestStmt() {
    if (findLatestStmt == null) {
        findLatestStmt = getSession().prepare("SELECT " +
                ModelConstants.KEY_COLUMN + "," +
                ModelConstants.TS_COLUMN + "," +
                ModelConstants.STRING_VALUE_COLUMN + "," +
                ModelConstants.BOOLEAN_VALUE_COLUMN + "," +
                ModelConstants.LONG_VALUE_COLUMN + "," +
                ModelConstants.DOUBLE_VALUE_COLUMN + " " +
                "FROM " + ModelConstants.TS_KV_LATEST_CF + " " +
                "WHERE " + ModelConstants.ENTITY_TYPE_COLUMN + " = ? " +
                "AND " + ModelConstants.ENTITY_ID_COLUMN + " = ? " +
                "AND " + ModelConstants.KEY_COLUMN + " = ? ");
    }
    return findLatestStmt;
}
项目:cassandra-count    文件:CqlCount.java   
private PreparedStatement prepareStatement() {
List<ColumnMetadata> partkeys = cluster.getMetadata().getKeyspace(keyspaceName).getTable(tableName).getPartitionKey();
StringBuilder sb = new StringBuilder();
sb.append("SELECT COUNT(*) FROM ");
sb.append(keyspaceName).append(".").append(tableName);
sb.append(" WHERE Token(");
sb.append(partkeys.get(0).getName());
for (int i = 1; i < partkeys.size(); i++)
    sb.append(", ").append(partkeys.get(i).getName());
sb.append(") > ? AND Token(");
sb.append(partkeys.get(0).getName());
for (int i = 1; i < partkeys.size(); i++)
    sb.append(",").append(partkeys.get(i).getName());
sb.append(") <= ?");

debugPrint("Query: " + sb.toString(), true, 2);

return session.prepare(sb.toString()).setConsistencyLevel(consistencyLevel);
   }
项目:dmaap-framework    文件:CassandraConfigDb.java   
public CassandraConfigDb(List<String> contactPoints, int port) {

    this.contactPoints = new ArrayList<InetAddress> (contactPoints.size());

    for (String contactPoint : contactPoints) {
        try {
            this.contactPoints.add(InetAddress.getByName(contactPoint));
        } catch (UnknownHostException e) {
               throw new IllegalArgumentException(e.getMessage());
        }
    }

    this.port = port;

    cluster = (new Cluster.Builder()).withPort (this.port)
            .addContactPoints(this.contactPoints)
            .withSocketOptions(new SocketOptions().setReadTimeoutMillis(60000).setKeepAlive(true).setReuseAddress(true))
            .withLoadBalancingPolicy(new RoundRobinPolicy())
            .withReconnectionPolicy(new ConstantReconnectionPolicy(500L))
            .withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.ONE))
            .build ();

    session = cluster.newSession();
    preparedStatements = new ConcurrentHashMap<StatementName, PreparedStatement> ();
    prepareStatementCreateLock = new Object();
}
项目:para-dao-cassandra    文件:CassandraDAO.java   
private String createRow(String key, String appid, String row) {
    if (StringUtils.isBlank(key) || StringUtils.isBlank(appid) || row == null || row.isEmpty()) {
        return null;
    }
    try {
        // if there isn't a document with the same id then create a new document
        // else replace the document with the same id with the new one
        PreparedStatement ps = getPreparedStatement("INSERT INTO " +
                CassandraUtils.getTableNameForAppid(appid) + " (id, json) VALUES (?, ?);");
        getClient().execute(ps.bind(key, row));
        logger.debug("Created id: " + key + " row: " + row);
    } catch (Exception e) {
        logger.error(null, e);
    }
    return key;
}
项目:para-dao-cassandra    文件:CassandraDAO.java   
private <P extends ParaObject> void updateRow(P so, String appid) {
    if (so == null || so.getId() == null || StringUtils.isBlank(appid)) {
        return;
    }
    try {
        String oldRow = readRow(so.getId(), appid);
        if (oldRow != null) {
            Map<String, Object> oldData = ParaObjectUtils.getJsonReader(Map.class).readValue(oldRow);
            Map<String, Object> newData = ParaObjectUtils.getAnnotatedFields(so, Locked.class);
            oldData.putAll(newData);
            PreparedStatement ps = getPreparedStatement("UPDATE " +
                    CassandraUtils.getTableNameForAppid(appid) + " SET json = ? WHERE id = ?;");
            getClient().execute(ps.bind(ParaObjectUtils.getJsonWriterNoIdent().
                    writeValueAsString(oldData), so.getId()));
            logger.debug("Updated id: " + so.getId());
        }
    } catch (Exception e) {
        logger.error(null, e);
    }
}
项目:para-dao-cassandra    文件:CassandraDAO.java   
private String readRow(String key, String appid) {
    if (StringUtils.isBlank(key) || StringUtils.isBlank(appid)) {
        return null;
    }
    String row = null;
    try {
        PreparedStatement ps = getPreparedStatement("SELECT json FROM " +
                CassandraUtils.getTableNameForAppid(appid) + " WHERE id = ?;");
        Row r = getClient().execute(ps.bind(key)).one();
        if (r != null) {
            row = r.getString("json");
        }
        logger.debug("Read id: " + key + " row: " + row);
    } catch (Exception e) {
        logger.error(null, e);
    }
    return (row == null || row.isEmpty()) ? null : row;
}
项目:music    文件:CassandraMixin.java   
/**
 * Remove the entries from the dirty row (for this replica) that correspond to a set of primary keys
 * @param tableName the table we are removing dirty entries from
 * @param keys the primary key values to use in the DELETE.  Note: this is *only* the primary keys, not a full table row.
 */
@Override
public void cleanDirtyRow(String tableName, Object[] keys) {
    TableInfo ti = dbi.getTableInfo(tableName);
    StringBuilder cols = new StringBuilder("REPLICA__=?");
    List<Object> vallist = new ArrayList<Object>();
    vallist.add(myId);
    int n = 0;
    for (int i = 0; i < ti.columns.size(); i++) {
        if (ti.iskey.get(i)) {
            cols.append(" AND ").append(ti.columns.get(i)).append("=?");
            vallist.add(keys[n++]);
        }
    }
    String cql = String.format("DELETE FROM %s.DIRTY_%s WHERE %s;", music_ns, tableName, cols.toString());
    logger.debug("Executing MUSIC write:"+ cql);
    Session sess = getMusicSession();
    PreparedStatement ps = getPreparedStatementFromCache(cql);
    BoundStatement bound = ps.bind(vallist.toArray());
    bound.setReadTimeoutMillis(60000);
    synchronized (sess) {
        sess.execute(bound);
    }
}
项目:music    文件:Cassandra2Mixin.java   
/**
 * Mark rows as "dirty" in the dirty rows table for <i>tableName</i>.  Rows are marked for all replicas but
 * this one (this replica already has the up to date data).
 * @param tableName the table we are marking dirty
 * @param keys an ordered list of the values being put into the table.  The values that correspond to the tables'
 * primary key are copied into the dirty row table.
 */
@Override
public void markDirtyRow(String tableName, Object[] keys) {
    String cql = String.format("INSERT INTO %s.%s (tablename, replica, keyset) VALUES (?, ?, ?);", music_ns, DIRTY_TABLE);
    Session sess = getMusicSession();
    PreparedStatement ps = getPreparedStatementFromCache(cql);
    Object[] values = new Object[] { tableName, "", buildJSON(tableName, keys) };
    for (String repl : allReplicaIds) {
        if (!repl.equals(myId)) {
            values[1] = repl;
            logger.debug("Executing MUSIC write:"+ cql + " with values " + values[0] + " " + values[1] + " " + values[2]);
            BoundStatement bound = ps.bind(values);
            bound.setReadTimeoutMillis(60000);
            synchronized (sess) {
                sess.execute(bound);
            }
        }
    }
}
项目:ibm-performance-monitor    文件:ProfilingUtilities.java   
/**
 * Get the name of a statement.
 * 
 * @param arg0 The statement.
 * @return The name used for logging.
 */
public static String getStatementName( Statement arg0 ) {
    String returnValue = "unknown";
    if ( arg0 instanceof RegularStatement ) {
        returnValue = ( (RegularStatement) arg0 ).getQueryString();
    } else if ( arg0 instanceof BoundStatement ) {
        PreparedStatement preparedStatement = ( (BoundStatement) arg0 ).preparedStatement();
        returnValue = preparedStatement.getQueryString();
    } else if ( arg0 instanceof BatchStatement ) {
        StringBuilder value = new StringBuilder( "Batch : " );
        Collection<Statement> statements = ( (BatchStatement) arg0 ).getStatements();
        boolean first = true;
        for ( Statement statement : statements ) {
            if ( first ) {
                first = false;
            } else {
                value.append( ", " );
            }
            String statementName = getStatementName( statement );
            value.append( statementName );
        }
        returnValue = value.toString();
    }
    return returnValue;
}
项目:vos_backend    文件:WorkerExecutor.java   
/**
 * prepare
 * prepares param workerQuery if it's not already prepared
 * @param workerQuery
 * @throws Exception
 */
private void prepare (
  WorkerQuery workerQuery) throws Exception {

  if (this.preparedStatements.containsKey(
        workerQuery.getPreparedStatementString() ) == true) {

    return;
  }

  PreparedStatement preparedStatement =
    Cassandra.i().makePreparedStatementSync(
      workerQuery.getPreparedStatementString() );

  preparedStatement.setConsistencyLevel(workerQuery.getConsistencyLevel() );

  this.preparedStatements.put(
    workerQuery.getPreparedStatementString(),
    preparedStatement);
}
项目:AbacusUtil    文件:CassandraExecutor.java   
private PreparedStatement prepare(final String query) {
    PreparedStatement preStat = session.prepare(query);

    if (settings != null) {
        if (settings.getConsistency() != null) {
            preStat.setConsistencyLevel(settings.getConsistency());
        }

        if (settings.getSerialConsistency() != null) {
            preStat.setSerialConsistencyLevel(settings.getSerialConsistency());
        }

        if (settings.getRetryPolicy() != null) {
            preStat.setRetryPolicy(settings.getRetryPolicy());
        }

        if (settings.isTraceQuery()) {
            preStat.enableTracing();
        } else {
            preStat.disableTracing();
        }
    }

    return preStat;
}
项目:Docussandra    文件:DocumentRepositoryImpl.java   
@Override
public Document read(Identifier identifier)
{
    Table table = identifier.getTable();
    PreparedStatement readStmt = PreparedStatementFactory.getPreparedStatement(String.format(READ_CQL, table.toDbTable(), Columns.ID), getSession());

    BoundStatement bs = new BoundStatement(readStmt);
    bindIdentifier(bs, identifier);
    Document item = DocumentPersistanceUtils.marshalRow(getSession().execute(bs).one());

    if (item == null)
    {
        throw new ItemNotFoundException("ID not found: " + identifier.toString());
    }
    //item.setId(identifier);
    item.setTable(table);
    return item;
}
项目:Docussandra    文件:DocumentRepositoryImpl.java   
@Override
public Document update(Document entity)
{
    Document old = read(entity.getId()); //will throw exception of doc is not found
    entity.setCreatedAt(old.getCreatedAt());//copy over the original create date
    Table table = entity.getTable();
    PreparedStatement updateStmt = PreparedStatementFactory.getPreparedStatement(String.format(CREATE_CQL, table.toDbTable(), Columns.ID), getSession());

    BoundStatement bs = new BoundStatement(updateStmt);
    bindCreate(bs, entity);
    BatchStatement batch = new BatchStatement(BatchStatement.Type.LOGGED);
    batch.add(bs);//the actual update
    try
    {
        List<BoundStatement> indexStatements = IndexMaintainerHelper.generateDocumentUpdateIndexEntriesStatements(getSession(), entity, bucketLocator);
        for (BoundStatement boundIndexStatement : indexStatements)
        {
            batch.add(boundIndexStatement);//the index updates
        }
        getSession().execute(batch);
        return entity;
    } catch (IndexParseException e)
    {
        throw new RuntimeException(e);
    }
}
项目:Camel    文件:CassandraProducer.java   
/**
 * Execute CQL as PreparedStatement
 */
private ResultSet executePreparedStatement(Session session, Object messageCql, Object[] cqlParams) {
    ResultSet resultSet;
    PreparedStatement lPreparedStatement;
    if (messageCql == null) {
        // URI CQL
        lPreparedStatement = this.preparedStatement;
    } else if (messageCql instanceof String) {
        // Message CQL
        lPreparedStatement = getEndpoint().prepareStatement((String) messageCql);
    } else if (messageCql instanceof RegularStatement) {
        // Message Statement
        lPreparedStatement = getEndpoint().getSession().prepare((RegularStatement) messageCql);
    } else {
        throw new IllegalArgumentException("Invalid " + CassandraConstants.CQL_QUERY + " header");
    }
    if (isEmpty(cqlParams)) {
        resultSet = session.execute(lPreparedStatement.bind());
    } else {
        resultSet = session.execute(lPreparedStatement.bind(cqlParams));
    }
    return resultSet;
}
项目:apex-malhar    文件:CassandraPOJOOutputOperator.java   
private PreparedStatement prepareStatementFromFieldsAndTableName()
{
  if (tablename == null || tablename.length() == 0) {
    throw new RuntimeException("Please sepcify query or table name.");
  }
  StringBuilder queryfields = new StringBuilder();
  StringBuilder values = new StringBuilder();
  for (FieldInfo fieldInfo: fieldInfos) {
    if (queryfields.length() == 0) {
      queryfields.append(fieldInfo.getColumnName());
      values.append("?");
    } else {
      queryfields.append(",").append(fieldInfo.getColumnName());
      values.append(",").append("?");
    }
  }
  String statement
      = "INSERT INTO " + store.keyspace + "."
      + tablename
      + " (" + queryfields.toString() + ") "
      + "VALUES (" + values.toString() + ");";
  LOG.debug("statement is {}", statement);
  return store.getSession().prepare(statement);
}
项目:apex-malhar    文件:CassandraOperatorTest.java   
public void insertEventsInTable(int numEvents)
{
  try {
    Cluster cluster = Cluster.builder().addContactPoint(NODE).build();
    Session session = cluster.connect(KEYSPACE);

    String insert = "INSERT INTO " + TABLE_NAME_INPUT + " (ID,lastname,age)" + " VALUES (?,?,?);";
    PreparedStatement stmt = session.prepare(insert);
    BoundStatement boundStatement = new BoundStatement(stmt);
    for (int i = 0; i < numEvents; i++) {
      ids.add(i);
      mapNames.put(i, "test" + i);
      mapAge.put(i, i + 10);
      session.execute(boundStatement.bind(i, "test" + i, i + 10));
    }
  } catch (DriverException e) {
    throw new RuntimeException(e);
  }
}
项目:cassandra-kmean    文件:SchemaStatement.java   
public SchemaStatement(Timer timer, StressSettings settings, DataSpec spec,
                       PreparedStatement statement, Integer thriftId, ConsistencyLevel cl, ValidationType validationType)
{
    super(timer, settings, spec);
    this.statement = statement;
    this.thriftId = thriftId;
    this.cl = cl;
    this.validationType = validationType;
    argumentIndex = new int[statement.getVariables().size()];
    bindBuffer = new Object[argumentIndex.length];
    int i = 0;
    for (ColumnDefinitions.Definition definition : statement.getVariables())
        argumentIndex[i++] = spec.partitionGenerator.indexOf(definition.getName());

    statement.setConsistencyLevel(JavaDriverClient.from(cl));
}
项目:tempto    文件:CassandraBatchLoader.java   
public void load(Iterator<List<Object>> rows)
{
    PreparedStatement statement = session.prepare(insertQuery);

    BatchStatement batch = createBatchStatement();
    while (rows.hasNext()) {
        if (batch.size() >= batchRowsCount) {
            session.execute(batch);
            batch = createBatchStatement();
        }
        List<Object> row = rows.next();
        checkState(row.size() == columnsCount, "values count in a row is expected to be %d, but found: %d", columnsCount, row.size());
        batch.add(statement.bind(row.toArray()));
    }

    if (batch.size() > 0) {
        session.execute(batch);
    }
}
项目:heroic    文件:LegacySchema.java   
@Override
public AsyncFuture<SchemaInstance> instance(final Session s) {
    final Map<String, String> values = ImmutableMap.of("keyspace", keyspace);

    final AsyncFuture<PreparedStatement> write = prepareAsync(values, s, WRITE_METRICS_CQL);
    final AsyncFuture<PreparedStatement> fetch = prepareAsync(values, s, FETCH_METRICS_CQL);
    final AsyncFuture<PreparedStatement> delete = prepareAsync(values, s, DELETE_METRICS_CQL);
    final AsyncFuture<PreparedStatement> count = prepareAsync(values, s, COUNT_METRICS_CQL);

    return async
        .collectAndDiscard(ImmutableList.of(write, fetch, delete, count))
        .directTransform(r -> {
            return new LegacySchemaInstance(keyspace, POINTS_TABLE, write.getNow(),
                fetch.getNow(), delete.getNow(), count.getNow());
        });
}
项目:heroic    文件:NextGenSchema.java   
@Override
public AsyncFuture<SchemaInstance> instance(final Session s) {
    final Map<String, String> values = ImmutableMap.of("keyspace", keyspace);

    final AsyncFuture<PreparedStatement> write = prepareAsync(values, s, WRITE_METRICS_CQL);
    final AsyncFuture<PreparedStatement> fetch = prepareAsync(values, s, FETCH_METRICS_CQL);
    final AsyncFuture<PreparedStatement> delete = prepareAsync(values, s, DELETE_METRICS_CQL);
    final AsyncFuture<PreparedStatement> count = prepareAsync(values, s, COUNT_METRICS_CQL);

    return async
        .collectAndDiscard(ImmutableList.of(write, fetch, delete, count))
        .directTransform(r -> {
            return new NextGenSchemaInstance(keyspace, POINTS_TABLE, write.getNow(),
                fetch.getNow(), delete.getNow(), count.get());
        });
}
项目:ignite    文件:CassandraSessionImpl.java   
/**
 * Tunes CQL statement execution options (consistency level, fetch option and etc.).
 *
 * @param statement Statement.
 * @return Modified statement.
 */
private Statement tuneStatementExecutionOptions(Statement statement) {
    String qry = "";

    if (statement instanceof BoundStatement)
        qry = ((BoundStatement)statement).preparedStatement().getQueryString().trim().toLowerCase();
    else if (statement instanceof PreparedStatement)
        qry = ((PreparedStatement)statement).getQueryString().trim().toLowerCase();

    boolean readStatement = qry.startsWith("select");
    boolean writeStatement = statement instanceof Batch || statement instanceof BatchStatement ||
        qry.startsWith("insert") || qry.startsWith("delete") || qry.startsWith("update");

    if (readStatement && readConsistency != null)
        statement.setConsistencyLevel(readConsistency);

    if (writeStatement && writeConsistency != null)
        statement.setConsistencyLevel(writeConsistency);

    if (fetchSize != null)
        statement.setFetchSize(fetchSize);

    return statement;
}
项目:java-driver-demos    文件:SynchronousInsert.java   
public void run() {
    logger.info("Preparing to insert metric data points");

    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect("demo");
    PreparedStatement insert = session.prepare(
        "insert into metric_data (metric_id, time, value) values (?, ?, ?)");
    Random random = new Random();
    DateTime time = DateTime.now().minusYears(1);

    Stopwatch stopwatch = new Stopwatch().start();
    for (int i = 0; i < NUM_INSERTS; ++i) {
        String metricId = "metric-" + Math.abs(random.nextInt() % NUM_METRICS);
        double value = random.nextDouble();
        session.execute(insert.bind(metricId, time.toDate(), value));
        time = time.plusSeconds(10);
    }
    stopwatch.stop();

    logger.info("Finished inserting {} data points in {} ms", NUM_INSERTS, stopwatch.elapsed(
        TimeUnit.MILLISECONDS));
}
项目:java-driver-demos    文件:SynchronousRead.java   
public void run() {
    logger.info("Preparing to read data points");

    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect("demo");
    PreparedStatement query = session.prepare(
        "SELECT metric_id, time, value FROM metric_data WHERE metric_id = ? AND time >= ? AND time <= ?");
    DateTime end = DateTime.now();
    DateTime start = end.minusYears(1);
    List<DataPoint> dataPoints = new ArrayList<>();

    Stopwatch stopwatch = new Stopwatch().start();
    for (int i = 0; i < NUM_METRICS; ++i) {
        ResultSet resultSet = session.execute(query.bind("metric-" + i, start.toDate(), end.toDate()));
        resultSet.forEach(row -> dataPoints.add(new DataPoint(row.getString(0), row.getDate(1), row.getDouble(2))));
    }
    stopwatch.stop();

    logger.info("Retrieved {} data points in {} ms", dataPoints.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
项目:hummingbird-framework    文件:CassandraEventSourceRepository.java   
@Override
protected void saveEvents(final Queue<Event> eventStream) {
    String cql = "insert into events (aid, tid, ctime, version, body, meta) values (?, ?, ?, ?, ?, ?)";
    final int eventSize = eventStream.size();
    final Iterator<Event> it = eventStream.iterator();

    template.batchExec(cql, new BatchPreparedStatementSetter() {
        @Override
        public BoundStatement setValues(PreparedStatement ps, int i) {
            Event e = it.next();
            if (e != null) {
                return ps.bind(e.getAggregateID().toString(), e.getCommandID(), e.getTimestamp(), e.getVersion(),
                        new String(serializer.serialize(e)), e.getMetaData());
            } else {
                return null;
            }
        }
        @Override
        public int getBatchSize() {
            return eventSize;
        }
    });
}
项目:testclient    文件:GeneratorBindingList.java   
/**
 * Like {@link #bindGenerator(PreparedStatement, String...)} except that it can only bind one
 * parameter, and that it can accept an offset for addressing generated data from a later
 * continuation point instead of 0
 * @param preparedStmt The statement which the binding is for
 * @param varname - the name of the field which is 'referencing' this binding
 * @param genname - the generator name
 * @param startOffset - the offset which the generator should be initialized with
 */
public void bindGenerator(PreparedStatement preparedStmt, String varname, String genname, long startOffset) {

    Generator generator = instanceSource.getGenerator(genname);

    if (generator == null ) {
        throw new RuntimeException("No generator found for varname:" + varname +", generatorName:" + genname);
    }

    set(varname, generator);

    if (generator instanceof FastForwardableGenerator) {
        ((FastForwardableGenerator) generator).fastForward(startOffset);
        logger.debug("generator " + genname + " fast-forwarded to " + startOffset);
    }
    else {
        logger.debug("generator " + genname + " NOT fast-forwarded");
    }
}
项目:realtime-analytics    文件:MetricCassandraCollector.java   
private void prepareStatements(String columnFamilyName,
        Map<String, String> demensions) {
    StringBuilder stmtStr = new StringBuilder();
    stmtStr.append("INSERT INTO ");
    stmtStr.append(columnFamilyName);
    stmtStr.append(" (metricname, groupid, metrictime");

    int demensionSize = 0;
    if (demensions != null) {
        for (Map.Entry<String, String> entry : demensions.entrySet()) {
            stmtStr.append(",");
            stmtStr.append(entry.getKey());
            demensionSize++;
        }
    }
    stmtStr.append(", value) VALUES (?, ?, ?");
    for (int i = 0; i < demensionSize; i++) {
        stmtStr.append(", ?");
    }

    stmtStr.append(", ?) USING TTL ");
    stmtStr.append(TTL);

    PreparedStatement stmt = cassandraSession.prepare(stmtStr.toString());
    stmtMap.put(columnFamilyName, stmt);
}
项目:realtime-analytics    文件:MetricCassandraCollector.java   
private void prepareStatementsForUpdate(String columnFamilyName,
        Map<String, String> demensions) {
    StringBuilder stmtStr = new StringBuilder();
    stmtStr.append("update ");
    stmtStr.append(columnFamilyName);
    stmtStr.append(" set value = value + ? ");
    stmtStr.append(" where metricname = ? and groupid = ? and metrictime = ? ");

    if (demensions != null) {
        for (String demensionName : demensions.keySet()) {
            stmtStr.append(" and ");
            stmtStr.append(demensionName.toLowerCase());
            stmtStr.append(" = ? ");
        }
    }
    PreparedStatement stmt = cassandraSession.prepare(stmtStr.toString());
    updatestmtMap.put(columnFamilyName, stmt);
}
项目:playorm    文件:CqlSession.java   
private void persist(Persist action, MetaLookup ormSession) {
    String colFamily = action.getColFamily().getColumnFamily();
    String table = lookupOrCreate(colFamily, ormSession);
    List<Column> s = action.getColumns();
    byte[] rowkey = action.getRowKey();

    for (Column c : s) {
        try {
            PreparedStatement statement = session.prepare("INSERT INTO " + keys + "." + table + "(id, colname, colvalue) VALUES (?, ?, ?)");
            BoundStatement boundStatement = new BoundStatement(statement);
            String colName = StandardConverters.convertToString(c.getName());
            checkIfRowExsits(table, rowkey, colName);
            if (c.getValue() != null && c.getValue().length != 0) {
                session.execute(boundStatement.bind(ByteBuffer.wrap(rowkey), colName, ByteBuffer.wrap(c.getValue())));
            } else {
                session.execute(boundStatement.bind(ByteBuffer.wrap(rowkey), colName, ByteBuffer.wrap(new byte[0])));
            }

        } catch (Exception e) {
            System.out.println(c.getValue() + "Exception:" + e.getMessage());
        }
    }

}
项目:scylla-tools-java    文件:BulkLoader.java   
private void sendPrepared(final Object callback, final DecoratedKey key, final long timestamp, String what,
        final List<Object> objects) {
    ListenableFuture<PreparedStatement> f = preparedStatements.get(what);
    if (f == null) {
        if (verbose) {
            System.out.println("Preparing: " + what);
        }
        f = session.prepareAsync(what);
        preparedStatements.put(what, f);
    }

    Futures.addCallback(f, new FutureCallback<PreparedStatement>() {
        @Override
        public void onSuccess(PreparedStatement p) {
            BoundStatement s = p.bind(objects.toArray(new Object[objects.size()]));
            s.setRoutingKey(key.getKey());
            s.setDefaultTimestamp(timestamp);
            send(callback, key, s);
        }

        @Override
        public void onFailure(Throwable t) {
            System.err.println(t);
        }
    }, MoreExecutors.directExecutor());
}
项目:scylla-tools-java    文件:SchemaStatement.java   
public SchemaStatement(Timer timer, StressSettings settings, DataSpec spec,
                       PreparedStatement statement, Integer thriftId, ConsistencyLevel cl)
{
    super(timer, settings, spec);
    this.statement = statement;
    this.thriftId = thriftId;
    this.cl = cl;
    argumentIndex = new int[statement.getVariables().size()];
    bindBuffer = new Object[argumentIndex.length];
    definitions = statement.getVariables();
    int i = 0;
    for (ColumnDefinitions.Definition definition : definitions)
        argumentIndex[i++] = spec.partitionGenerator.indexOf(definition.getName());

    statement.setConsistencyLevel(JavaDriverClient.from(cl));
}