com.datastax.driver.core.PreparedStatement Java Examples

The following examples show how to use com.datastax.driver.core.PreparedStatement. 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: TestBaselineApproach.java    From bboxdb with Apache License 2.0 6 votes vote down vote up
/**
 * Import data into cassandra
 * @param sourceFile
 * @param format
 * @param destTable
 */
public void executeImport(final String sourceFile, final String destTable) {
	session.execute("CREATE TABLE " + destTable + "(id long, data text, PRIMARY KEY(id)");

	final PreparedStatement prepared = session.prepare("INSERT INTO " + destTable
			+ " (id, text) values (?, ?)");

	long lineNumber = 0;
	String line = null;

	try(
			final BufferedReader br = new BufferedReader(new FileReader(new File(sourceFile)));
	) {

		while((line = br.readLine()) != null) {
			session.execute(prepared.bind(lineNumber, line));
		}

	} catch (Exception e) {
		e.printStackTrace();
		System.exit(-1);
	}
}
 
Example #2
Source File: CassandraStorage.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
@Override
public WorkflowInstance readWorkflowInstance(final String wfId) throws Exception {
    logger.debug("readCassandraWorkflow({})", wfId);
    return new CassandraOperation<WorkflowInstance>(logger) {
        @Override
        protected WorkflowInstance execute() throws Exception {
            final PreparedStatement pstmt = preparedStatements.get(CQL_SEL_WORKFLOW_INSTANCE);
            final long startTS = System.nanoTime();
            ResultSet rs = session.execute(pstmt.bind(wfId));
            Row row = rs.one();
            if (row == null) {
                return null;
            }
            final WorkflowInstance cw = row2WorkflowInstance(row);
            runtimeStatisticsCollector.submit("wfi.read", 1, System.nanoTime() - startTS, TimeUnit.NANOSECONDS);
            return cw;
        }
    }.run();
}
 
Example #3
Source File: EnrichedCustomerServiceCassandraOutputOperator.java    From examples with Apache License 2.0 6 votes vote down vote up
@Override
protected Statement setStatementParameters(PreparedStatement updateCommand, EnrichedCustomerService tuple)
    throws DriverException
{
  final BoundStatement boundStmnt = new BoundStatement(updateCommand);
  boundStmnt.setLong(0, ++id);
  boundStmnt.setString(1, tuple.imsi);
  boundStmnt.setInt(2, tuple.totalDuration);
  boundStmnt.setInt(3, tuple.wait);
  boundStmnt.setString(4, tuple.zipCode);
  boundStmnt.setString(5, tuple.issueType.name());
  boundStmnt.setBool(6, tuple.satisfied);
  boundStmnt.setString(7, tuple.operatorCode);
  boundStmnt.setString(8, tuple.deviceBrand);
  boundStmnt.setString(9, tuple.deviceModel);

  //or boundStatement.bind();
  return boundStmnt;

}
 
Example #4
Source File: CassandraBaseTimeseriesDao.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void addSyntheticMonitorAndAlertPermissions() throws Exception {
    PreparedStatement insertPS =
            session.prepare("insert into role (name, permissions) values (?, ?)");
    ResultSet results = session.read("select name, permissions from role");
    for (Row row : results) {
        String name = row.getString(0);
        Set<String> permissions = row.getSet(1, String.class);
        Set<String> permissionsToBeAdded = upgradePermissions2(permissions);
        if (permissionsToBeAdded.isEmpty()) {
            continue;
        }
        permissions.addAll(permissionsToBeAdded);
        BoundStatement boundStatement = insertPS.bind();
        boundStatement.setString(0, name);
        boundStatement.setSet(1, permissions, String.class);
        session.write(boundStatement);
    }
}
 
Example #6
Source File: CassandraOperatorTest.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #7
Source File: CaseController.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/healthCheck")
@ResponseBody
public String healthCheck() {
    Cluster cluster = null;
    Session session = null;
    try {
        cluster = Cluster.builder().addContactPoint(host).withPort(port).withoutJMXReporting().build();
        session = cluster.connect();
        logger.info("cassandra connection open");

        PreparedStatement testPreparedStatement = session.prepare(TEST_EXIST_SQL);
        logger.info("Test result:" + testPreparedStatement.toString());
    } finally {
        if (session != null) {
            session.close();
        }
        if (cluster != null) {
            cluster.close();
        }
        logger.info("cassandra connection close");
    }
    return SUCCESS;
}
 
Example #8
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getSyntheticMonitorDisplays(PreparedStatement readAgentConfig,
        String agentRollupId) throws Exception {
    BoundStatement boundStatement = readAgentConfig.bind();
    boundStatement.setString(0, agentRollupId);
    ResultSet results = session.read(boundStatement);
    if (results.isExhausted()) {
        return ImmutableMap.of();
    }
    AgentConfig agentConfig;
    try {
        Row row = checkNotNull(results.one());
        agentConfig = AgentConfig.parseFrom(checkNotNull(row.getBytes(0)));
    } catch (InvalidProtocolBufferException e) {
        logger.error(e.getMessage(), e);
        return ImmutableMap.of();
    }
    Map<String, String> syntheticMonitorDisplays = new HashMap<>();
    for (SyntheticMonitorConfig config : agentConfig.getSyntheticMonitorConfigList()) {
        syntheticMonitorDisplays.put(config.getId(),
                MoreConfigDefaults.getDisplayOrDefault(config));
    }
    return syntheticMonitorDisplays;
}
 
Example #9
Source File: Tools.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void executeDeletesTt(int rollupLevel, String partialName, String thresholdComparator,
        Date threshold, Set<TtPartitionKey> partitionKeys) throws Exception {
    String tableName = "aggregate_tt_" + partialName + "_rollup_" + rollupLevel;
    PreparedStatement deletePS = session.prepare("delete from " + tableName
            + " where agent_rollup = ? and transaction_type = ? and capture_time "
            + thresholdComparator + " ?");
    int count = 0;
    List<Future<?>> futures = new ArrayList<>();
    for (TtPartitionKey partitionKey : partitionKeys) {
        BoundStatement boundStatement = deletePS.bind();
        int i = 0;
        boundStatement.setString(i++, partitionKey.agentRollupId());
        boundStatement.setString(i++, partitionKey.transactionType());
        boundStatement.setTimestamp(i++, threshold);
        futures.add(session.writeAsync(boundStatement));
        count++;
    }
    MoreFutures.waitForAll(futures);
    startupLogger.info("{} range deletes executed against {}", count, tableName);
}
 
Example #10
Source File: CassandraUtils.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public static long writeIntoTwoColumnTable(Session targetSession, String table, Observable<Pair<Object, Object>> sourceData) {
    Pair<String, String> columnNames = resolveColumnNamesInTwoColumnTable(targetSession, table);
    String primaryKey = columnNames.getLeft();
    String valueColumn = columnNames.getRight();

    PreparedStatement insertStatement = targetSession.prepare(
            String.format("INSERT INTO %s (%s, %s) VALUES (?, ?)", table, primaryKey, valueColumn)
    );

    AsyncCassandraExecutor executor = new AsyncCassandraExecutor(targetSession, PAGE_SIZE, SPLIT);

    long recordCount = sourceData
            .flatMap(pair -> {
                BoundStatement boundStatement = insertStatement.bind(pair.getLeft(), pair.getRight());
                return executor
                        .executeUpdate(boundStatement)
                        .cast(Long.class)
                        .concatWith(Observable.just(1L));
            }, MAX_CONCURRENCY)
            .reduce(0L, (acc, v) -> acc + v)
            .toBlocking().firstOrDefault(null);

    return recordCount;
}
 
Example #11
Source File: EventRepositoryCassandraEtlImpl.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
public void saveEvent(Tenant tenant, Application application, Event event, String table) {
    PreparedStatement ps = getInsertIncomingPreparedStatement(table);

    BoundStatement statement = ps.bind(tenant.getDomainName(),
            application.getName(),
            event.getEpochTime(),
            event.getIncoming().getChannel(),
            event.getIncoming().getDeviceGuid(),
            event.getIncoming().getDeviceId(),
            event.getIncoming().getLocationGuid(),
            Optional.ofNullable(event.getGeolocation()).isPresent() ? event.getGeolocation().getElev() : null,
            Optional.ofNullable(event.getGeolocation()).isPresent() ? event.getGeolocation().getHdop() : null,
            Optional.ofNullable(event.getGeolocation()).isPresent() ? event.getGeolocation().getLat() : null,
            Optional.ofNullable(event.getGeolocation()).isPresent() ? event.getGeolocation().getLon() : null,
            event.getIngestedTimestamp().toEpochMilli() * 1000000, // nanoseconds
            event.getPayload());

    session.execute(statement);
}
 
Example #12
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void rewriteAgentConfigTablePart1() throws Exception {
    dropTableIfExists("agent_config_temp");
    session.updateSchemaWithRetry("create table if not exists agent_config_temp"
            + " (agent_rollup_id varchar, config blob, config_update boolean,"
            + " config_update_token uuid, primary key (agent_rollup_id))");
    PreparedStatement insertTempPS = session.prepare("insert into agent_config_temp"
            + " (agent_rollup_id, config, config_update, config_update_token) values"
            + " (?, ?, ?, ?)");
    ResultSet results = session.read("select agent_rollup_id, config, config_update,"
            + " config_update_token from agent_config");
    for (Row row : results) {
        BoundStatement boundStatement = insertTempPS.bind();
        boundStatement.setString(0, row.getString(0));
        boundStatement.setBytes(1, row.getBytes(1));
        boundStatement.setBool(2, row.getBool(2));
        boundStatement.setUUID(3, row.getUUID(3));
        session.write(boundStatement);
    }
}
 
Example #13
Source File: CassandraMailboxPathV2DAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
private PreparedStatement prepareDelete(Session session) {
    return session.prepare(QueryBuilder.delete()
        .from(TABLE_NAME)
        .where(eq(NAMESPACE, bindMarker(NAMESPACE)))
        .and(eq(USER, bindMarker(USER)))
        .and(eq(MAILBOX_NAME, bindMarker(MAILBOX_NAME)))
        .ifExists());
}
 
Example #14
Source File: CassandraUsersDAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
private PreparedStatement prepareUpdateUserStatement(Session session) {
    return session.prepare(update(TABLE_NAME)
        .with(set(REALNAME, bindMarker(REALNAME)))
        .and(set(PASSWORD, bindMarker(PASSWORD)))
        .and(set(ALGORITHM, bindMarker(ALGORITHM)))
        .where(eq(NAME, bindMarker(NAME)))
        .ifExists());
}
 
Example #15
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void updateEncryptedPasswordAttributeName(String key, PreparedStatement readPS,
        PreparedStatement insertPS) throws Exception {
    BoundStatement boundStatement = readPS.bind();
    boundStatement.setString(0, key);
    ResultSet results = session.read(boundStatement);
    Row row = results.one();
    if (row == null) {
        return;
    }
    String configText = row.getString(0);
    if (configText == null) {
        return;
    }
    JsonNode jsonNode = mapper.readTree(configText);
    if (jsonNode == null || !jsonNode.isObject()) {
        return;
    }
    ObjectNode objectNode = (ObjectNode) jsonNode;
    JsonNode passwordNode = objectNode.remove("password");
    if (passwordNode != null) {
        objectNode.set("encryptedPassword", passwordNode);
    }
    String updatedConfigText = mapper.writeValueAsString(objectNode);
    boundStatement = insertPS.bind();
    boundStatement.setString(0, key);
    boundStatement.setString(1, updatedConfigText);
    session.write(boundStatement);
}
 
Example #16
Source File: ImportLocalizationKeysCommand.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private BoundStatement bindLocalizationKey(PreparedStatement stmt, String bundle, String locale, String key, String value) {
   return new BoundStatement(stmt)
      .setString("bundle", bundle)
      .setString("locale", locale)
      .setString("key", key)
      .setString("value", value);
}
 
Example #17
Source File: SyntheticResultDaoImpl.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void rollup(String agentRollupId, int rollupLevel, int ttl) throws Exception {
    List<RollupConfig> rollupConfigs = configRepository.getRollupConfigs();
    long rollupIntervalMillis = rollupConfigs.get(rollupLevel).intervalMillis();
    Collection<NeedsRollup> needsRollupList = Common.getNeedsRollupList(agentRollupId,
            rollupLevel, rollupIntervalMillis, readNeedsRollup, session, clock);
    Long nextRollupIntervalMillis = null;
    if (rollupLevel + 1 < rollupConfigs.size()) {
        nextRollupIntervalMillis = rollupConfigs.get(rollupLevel + 1).intervalMillis();
    }
    for (NeedsRollup needsRollup : needsRollupList) {
        long captureTime = needsRollup.getCaptureTime();
        long from = captureTime - rollupIntervalMillis;
        int adjustedTTL = Common.getAdjustedTTL(ttl, captureTime, clock);
        Set<String> syntheticMonitorIds = needsRollup.getKeys();
        List<ListenableFuture<?>> futures = new ArrayList<>();
        for (String syntheticMonitorId : syntheticMonitorIds) {
            futures.add(rollupOne(rollupLevel, agentRollupId, syntheticMonitorId, from,
                    captureTime, adjustedTTL));
        }
        // wait for above async work to ensure rollup complete before proceeding
        MoreFutures.waitForAll(futures);

        int needsRollupAdjustedTTL =
                Common.getNeedsRollupAdjustedTTL(adjustedTTL, rollupConfigs);
        PreparedStatement insertNeedsRollup = nextRollupIntervalMillis == null ? null
                : this.insertNeedsRollup.get(rollupLevel);
        PreparedStatement deleteNeedsRollup = this.deleteNeedsRollup.get(rollupLevel - 1);
        Common.postRollup(agentRollupId, needsRollup.getCaptureTime(), syntheticMonitorIds,
                needsRollup.getUniquenessKeysForDeletion(), nextRollupIntervalMillis,
                insertNeedsRollup, deleteNeedsRollup, needsRollupAdjustedTTL, session);
    }
}
 
Example #18
Source File: LowercaseLoginIndex.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 insert = session.prepare(INSERT_LOGIN);
   PreparedStatement delete = session.prepare(DELETE_LOGIN);
   
   ResultSet rs = context.getSession().execute(SELECT);
   for(Row row: rs) {
      String domain = row.getString("domain");
      String user_0_3 = row.getString("user_0_3");
      String user = row.getString("user");
      if(
            !domain.equals(domain.toLowerCase()) ||
            !user_0_3.equals(user_0_3.toLowerCase()) ||
            !user.equals(user.toLowerCase())
      ) {
         // TODO async this?
         logger.debug("Converting [{}] to lower case", user);
         BoundStatement bs = insert.bind(
               domain.toLowerCase(), 
               user_0_3.toLowerCase(), 
               user.toLowerCase(),
               row.getString("password"),
               row.getString("password_salt"),
               row.getUUID("personid")
         );
         if(session.execute(bs).wasApplied()) {
            session.execute( delete.bind(domain, user_0_3, user) );
         }
         else {
            logger.warn("Unable to convert [{}] to lower case", user);
         }
      }
   }
}
 
Example #19
Source File: StorageInformationDAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
private PreparedStatement prepareAdd(Session session) {
    return session.prepare(insertInto(TABLE)
        .value(OWNER, bindMarker(OWNER))
        .value(MESSAGE_ID, bindMarker(MESSAGE_ID))
        .value(BUCKET_NAME, bindMarker(BUCKET_NAME))
        .value(BLOB_ID, bindMarker(BLOB_ID)));
}
 
Example #20
Source File: DataAccessImpl.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
PreparedStatement getTempStatement(MetricType type, TempStatement ts, long timestamp) {
    Map.Entry<Long, Map<Integer, PreparedStatement>> floorEntry = prepMap
            .floorEntry(timestamp);

    if(floorEntry != null) {
            return floorEntry.getValue()
                .get(getMapKey(type, ts));
    }
    return null;
}
 
Example #21
Source File: CassandraMailboxPathV2DAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
private PreparedStatement prepareInsert(Session session) {
    return session.prepare(insertInto(TABLE_NAME)
        .value(NAMESPACE, bindMarker(NAMESPACE))
        .value(USER, bindMarker(USER))
        .value(MAILBOX_NAME, bindMarker(MAILBOX_NAME))
        .value(MAILBOX_ID, bindMarker(MAILBOX_ID))
        .ifNotExists());
}
 
Example #22
Source File: CassandraMappingsSourcesDAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
private PreparedStatement prepareDelete(Session session) {
    return session.prepare(delete()
        .from(TABLE_NAME)
        .where(eq(MAPPING_TYPE, bindMarker(MAPPING_TYPE)))
        .and(eq(MAPPING_VALUE, bindMarker(MAPPING_VALUE)))
        .and(eq(SOURCE, bindMarker(SOURCE))));
}
 
Example #23
Source File: Cassandra2xQuadIndexDAO.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
@Override
protected void prepareStatements() {
	super.prepareStatements();

	final int ttl = _factory.getTtl();
	// Inserting
	if (ttl != -1) {
		_insertOCPSStatement = _session.prepare("INSERT INTO " + TABLE_OC_PS + "(o, c, p, s, c_index) VALUES (?, ?, ?, ?, ?) USING TTL " + ttl);
		_insertSCOPStatement = _session.prepare("INSERT INTO " + TABLE_SC_OP + "(s, c, o, p) VALUES (?, ?, ?, ?) USING TTL " + ttl);
		_insertSPCOStatement = _session.prepare("INSERT INTO " + TABLE_SPC_O + "(s, p, c, o, pc_index) VALUES (?, ?, ?, ?, ?) USING TTL " + ttl);
	} else {
		_insertOCPSStatement = _session.prepare("INSERT INTO " + TABLE_OC_PS + "(o, c, p, s, c_index) VALUES (?, ?, ?, ?, ?)");
		_insertSCOPStatement = _session.prepare("INSERT INTO " + TABLE_SC_OP + "(s, c, o, p) VALUES (?, ?, ?, ?)");
		_insertSPCOStatement = _session.prepare("INSERT INTO " + TABLE_SPC_O + "(s, p, c, o, pc_index) VALUES (?, ?, ?, ?, ?)");
	}

	// Deleting
	_deleteOCPSStatement = _session.prepare("DELETE FROM " + TABLE_OC_PS + " WHERE o = ? AND c = ? AND p = ? and s = ?");
	_deleteSCOPStatement = _session.prepare("DELETE FROM " + TABLE_SC_OP + " WHERE s = ? AND c = ? AND o = ? and p = ?");
	_deleteSPCOStatement = _session.prepare("DELETE FROM " + TABLE_SPC_O + " WHERE s = ? AND p = ? AND c = ? and o = ?");

	// Clearing
	_clearOCPSStatement = _session.prepare("TRUNCATE " + TABLE_OC_PS);
	_clearSCOPStatement = _session.prepare("TRUNCATE " + TABLE_SC_OP);
	_clearSPCOStatement = _session.prepare("TRUNCATE " + TABLE_SPC_O);

	// Querying
	_queries = new PreparedStatement[8];
	_queries[0] = _session.prepare("SELECT s, p, o, c FROM " + TABLE_SC_OP + " WHERE s = ? AND p = ? AND o = ? AND c = ? LIMIT ?"); // (s, p, o, c)
	_queries[1] = _session.prepare("SELECT s, p, o, c FROM " + TABLE_SPC_O + " WHERE s = ? AND p = ?           AND c = ? LIMIT ?"); // (s, p, ?, c)
	_queries[2] = _session.prepare("SELECT s, p, o, c FROM " + TABLE_SC_OP + " WHERE s = ?           AND o = ? AND c = ? LIMIT ?"); // (s, ?, o, c)
	_queries[3] = _session.prepare("SELECT s, p, o, c FROM " + TABLE_SC_OP + " WHERE s = ?                     AND c = ? LIMIT ?"); // (s, ?, ?, c)
	_queries[4] = _session.prepare("SELECT s, p, o, c FROM " + TABLE_OC_PS + " WHERE           p = ? AND o = ? AND c = ? LIMIT ?"); // (?, p, o, c)
	_queries[5] = _session.prepare("SELECT s, p, o, c FROM " + TABLE_SPC_O + " WHERE           pc_index = ?              LIMIT ?"); // (?, p, ?, c)
	_queries[6] = _session.prepare("SELECT s, p, o, c FROM " + TABLE_OC_PS + " WHERE                     o = ? AND c = ? LIMIT ?"); // (?, ?, o, c)
	_queries[7] = _session.prepare("SELECT s, p, o, c FROM " + TABLE_OC_PS + " WHERE                         c_index = ? LIMIT ?"); // (?, ?, ?, c)
}
 
Example #24
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void rewriteTraceAttributeNameTablePart2() throws Exception {
    if (!tableExists("trace_attribute_name_temp")) {
        // previously failed mid-upgrade prior to updating schema version
        return;
    }
    dropTableIfExists("trace_attribute_name");
    Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
    session.createTableWithLCS("create table if not exists trace_attribute_name (agent_rollup"
            + " varchar, transaction_type varchar, trace_attribute_name varchar, primary key"
            + " ((agent_rollup, transaction_type), trace_attribute_name))");
    PreparedStatement insertPS = session.prepare("insert into trace_attribute_name"
            + " (agent_rollup, transaction_type, trace_attribute_name) values (?, ?, ?) using"
            + " ttl ?");
    int ttl = getCentralStorageConfig(session).getTraceTTL();
    ResultSet results = session.read("select agent_rollup, transaction_type,"
            + " trace_attribute_name from trace_attribute_name_temp");
    for (Row row : results) {
        String v09AgentRollupId = row.getString(0);
        V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
        if (v09AgentRollup == null) {
            // v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
            // table in which case its parent is no longer known and best to ignore
            continue;
        }
        BoundStatement boundStatement = insertPS.bind();
        boundStatement.setString(0, v09AgentRollup.agentRollupId());
        boundStatement.setString(1, row.getString(1));
        boundStatement.setString(2, row.getString(2));
        boundStatement.setInt(3, ttl);
        session.write(boundStatement);
    }
    dropTableIfExists("trace_attribute_name_temp");
}
 
Example #25
Source File: PutCassandraRecordTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Cluster createCluster(List<InetSocketAddress> contactPoints, SSLContext sslContext,
                                String username, String password, String compressionType) {
    Cluster mockCluster = mock(Cluster.class);
    try {
        Metadata mockMetadata = mock(Metadata.class);
        when(mockMetadata.getClusterName()).thenReturn("cluster1");
        when(mockCluster.getMetadata()).thenReturn(mockMetadata);
        when(mockCluster.connect()).thenReturn(mockSession);
        when(mockCluster.connect(anyString())).thenReturn(mockSession);
        Configuration config = Configuration.builder().build();
        when(mockCluster.getConfiguration()).thenReturn(config);
        ResultSetFuture future = mock(ResultSetFuture.class);
        ResultSet rs = CassandraQueryTestUtil.createMockResultSet();
        PreparedStatement ps = mock(PreparedStatement.class);
        when(mockSession.prepare(anyString())).thenReturn(ps);
        BoundStatement bs = mock(BoundStatement.class);
        when(ps.bind()).thenReturn(bs);
        when(future.getUninterruptibly()).thenReturn(rs);
        try {
            doReturn(rs).when(future).getUninterruptibly(anyLong(), any(TimeUnit.class));
        } catch (TimeoutException te) {
            throw new IllegalArgumentException("Mocked cluster doesn't time out");
        }
        if (exceptionToThrow != null) {
            doThrow(exceptionToThrow).when(mockSession).executeAsync(anyString());
            doThrow(exceptionToThrow).when(mockSession).executeAsync(any(Statement.class));

        } else {
            when(mockSession.executeAsync(anyString())).thenReturn(future);
            when(mockSession.executeAsync(any(Statement.class))).thenReturn(future);
        }
        when(mockSession.getCluster()).thenReturn(mockCluster);
    } catch (Exception e) {
        fail(e.getMessage());
    }
    return mockCluster;
}
 
Example #26
Source File: CassandraRecipientRewriteTableDAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
private PreparedStatement prepareDelete(Session session) {
    return session.prepare(delete()
        .from(TABLE_NAME)
        .where(eq(USER, bindMarker(USER)))
        .and(eq(DOMAIN, bindMarker(DOMAIN)))
        .and(eq(MAPPING, bindMarker(MAPPING))));
}
 
Example #27
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void updateRolePermissionName() throws Exception {
    PreparedStatement insertPS =
            session.prepare("insert into role (name, permissions) values (?, ?)");
    ResultSet results = session.read("select name, permissions from role");
    for (Row row : results) {
        String name = row.getString(0);
        Set<String> permissions = row.getSet(1, String.class);
        boolean updated = false;
        Set<String> upgradedPermissions = new HashSet<>();
        for (String permission : permissions) {
            PermissionParser parser = new PermissionParser(permission);
            parser.parse();
            if (parser.getPermission().equals("agent:alert")) {
                upgradedPermissions.add("agent:"
                        + PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
                        + ":incident");
                updated = true;
            } else {
                upgradedPermissions.add(permission);
            }
        }
        if (updated) {
            BoundStatement boundStatement = insertPS.bind();
            boundStatement.setString(0, name);
            boundStatement.setSet(1, upgradedPermissions, String.class);
            session.write(boundStatement);
        }
    }
}
 
Example #28
Source File: NextGenSchemaInstance.java    From heroic with Apache License 2.0 5 votes vote down vote up
NextGenSchemaInstance(
    final String keyspace,
    final String pointsTable,
    final PreparedStatement write,
    final PreparedStatement fetch,
    final PreparedStatement delete,
    final PreparedStatement count
) {
    super(KEY);
    this.write = write;
    this.fetch = fetch;
    this.delete = delete;
    this.count = count;
    this.keyUtils = new BackendKeyUtils(KEY, keyspace, pointsTable, this);
}
 
Example #29
Source File: BatchHandlerTest.java    From scalardb with Apache License 2.0 5 votes vote down vote up
private void configureBehavior() {
  when(insert.prepare(any(Mutation.class))).thenReturn(prepared);
  when(insert.bind(any(PreparedStatement.class), any(Mutation.class))).thenReturn(bound);
  when(update.prepare(any(Mutation.class))).thenReturn(prepared);
  when(update.bind(any(PreparedStatement.class), any(Mutation.class))).thenReturn(bound);
  when(delete.prepare(any(Mutation.class))).thenReturn(prepared);
  when(delete.bind(any(PreparedStatement.class), any(Mutation.class))).thenReturn(bound);
}
 
Example #30
Source File: PersonDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private PreparedStatement prepareUpdatePassword() {
   return CassandraQueryBuilder.update(Tables.LOGIN)
      .addColumn(LoginColumns.PASSWORD)
      .addColumn(LoginColumns.PASSWORD_SALT)
      .addColumn(LoginColumns.LAST_PASS_CHANGE)
      .addWhereColumnEquals(LoginColumns.DOMAIN)
      .addWhereColumnEquals(LoginColumns.USER_0_3)
      .addWhereColumnEquals(LoginColumns.USER)
      .prepare(session);
}