Java Code Examples for com.datastax.driver.core.ResultSet#wasApplied()
The following examples show how to use
com.datastax.driver.core.ResultSet#wasApplied() .
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: CassandraAlarmIncidentDAO.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public boolean updateMonitoringState(UUID placeId, UUID incidentId, AlarmIncident.MonitoringState state) { AlarmIncident.MonitoringState required = AlarmIncident.MonitoringState.NONE; switch(state) { case NONE: case PENDING: break; case DISPATCHING: case CANCELLED: required = AlarmIncident.MonitoringState.PENDING; break; case DISPATCHED: required = AlarmIncident.MonitoringState.DISPATCHING; break; } BoundStatement bound = new BoundStatement(updateMonitoringState); bound.bind(state.name(), placeId, incidentId, required.name()); ResultSet rs = session.execute(bound); return rs.wasApplied(); }
Example 2
Source File: CassandraExecutionDAO.java From conductor with Apache License 2.0 | 6 votes |
@Override public boolean removeWorkflow(String workflowId) { Workflow workflow = getWorkflow(workflowId, true); boolean removed = false; // TODO: calculate number of shards and iterate if (workflow != null) { try { recordCassandraDaoRequests("removeWorkflow", "n/a", workflow.getWorkflowName()); ResultSet resultSet = session.execute(deleteWorkflowStatement.bind(UUID.fromString(workflowId), DEFAULT_SHARD_ID)); removed = resultSet.wasApplied(); } catch (Exception e) { Monitors.error(CLASS_NAME, "removeWorkflow"); String errorMsg = String.format("Failed to remove workflow: %s", workflowId); LOGGER.error(errorMsg, e); throw new ApplicationException(Code.BACKEND_ERROR, errorMsg); } workflow.getTasks().forEach(this::removeTaskLookup); } return removed; }
Example 3
Source File: HubDAOImpl.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public Map<String, Object> connected(String hubId) { Date ts = new Date(); BoundStatement bs = connected.bind(HubCapability.STATE_NORMAL, JSON.toJson(HubConnectionCapability.STATE_ONLINE), JSON.toJson(ts), ts, hubId); Address hubAddress = Address.hubService(hubId, HubCapability.NAMESPACE); try(Context ctx = connectedTimer.time()) { ResultSet rs = session.execute(bs); if(rs.wasApplied()) { return ImmutableMap.of( HubCapability.ATTR_STATE, HubCapability.STATE_NORMAL, HubConnectionCapability.ATTR_STATE, HubConnectionCapability.STATE_ONLINE, HubConnectionCapability.ATTR_LASTCHANGE, ts ); } else { Row row = rs.one(); if(row.getColumnDefinitions().contains(HubEntityColumns.STATE)) { return ImmutableMap.of(); } else { throw new NotFoundException(hubAddress); } } } }
Example 4
Source File: CassandraBaseComponentDescriptorDao.java From iotplatform with Apache License 2.0 | 6 votes |
private Optional<ComponentDescriptor> saveIfNotExist(ComponentDescriptorEntity entity) { if (entity.getId() == null) { entity.setId(UUIDs.timeBased()); } ResultSet rs = executeRead(QueryBuilder.insertInto(getColumnFamilyName()) .value(ModelConstants.ID_PROPERTY, entity.getId()) .value(ModelConstants.COMPONENT_DESCRIPTOR_NAME_PROPERTY, entity.getName()) .value(ModelConstants.COMPONENT_DESCRIPTOR_CLASS_PROPERTY, entity.getClazz()) .value(ModelConstants.COMPONENT_DESCRIPTOR_TYPE_PROPERTY, entity.getType()) .value(ModelConstants.COMPONENT_DESCRIPTOR_SCOPE_PROPERTY, entity.getScope()) .value(ModelConstants.COMPONENT_DESCRIPTOR_CONFIGURATION_DESCRIPTOR_PROPERTY, entity.getConfigurationDescriptor()) .value(ModelConstants.COMPONENT_DESCRIPTOR_ACTIONS_PROPERTY, entity.getActions()) .value(ModelConstants.SEARCH_TEXT_PROPERTY, entity.getSearchText()) .ifNotExists() ); if (rs.wasApplied()) { return Optional.of(DaoUtil.getData(entity)); } else { return Optional.empty(); } }
Example 5
Source File: CassandraSchedulerModelDao.java From arcusplatform with Apache License 2.0 | 6 votes |
protected boolean insertModel( ModelEntity model, UUID placeId, UUID modelId ) { ResultSet rs = session().execute( insert.bind( model.getCreated(), model.getModified(), encode( model.toMap() ), placeId, SchedulerModel.getTarget(model), modelId ) ); return rs.wasApplied(); }
Example 6
Source File: CassandraClusterServiceDao.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public ClusterServiceRecord heartbeat(ClusterServiceRecord record) throws ClusterServiceDaoException { try(Timer.Context timer = ClusterServiceMetrics.heartbeatTimer.time()) { Instant instant = clock.instant(); Date now = new Date(instant.toEpochMilli()); BoundStatement bs = heartbeat.bind(now, record.getService(), record.getMemberId(), record.getHost(), new Date(record.getRegistered().toEpochMilli())); ResultSet rs = session.execute( bs ); if(!rs.wasApplied()) { ClusterServiceMetrics.clusterIdLostCounter.inc(); throw new ClusterIdLostException("Another service has taken the member id"); } ClusterServiceRecord copy = record.copy(); copy.setLastHeartbeat(instant); return copy; } }
Example 7
Source File: CassandraDataHandler.java From micro-integrator with Apache License 2.0 | 6 votes |
private boolean deleteEntityTableNonTransactional(String tableName, ODataEntry entity) throws ODataServiceFault { List<ColumnMetadata> cassandraTableMetaData = this.session.getCluster().getMetadata().getKeyspace(this.keyspace) .getTable(tableName).getColumns(); List<String> pKeys = this.primaryKeys.get(tableName); String query = createDeleteCQL(tableName); List<Object> values = new ArrayList<>(); for (String column : pKeys) { if (entity.getNames().contains(column)) { bindParams(column, entity.getValue(column), values, cassandraTableMetaData); } } PreparedStatement statement = this.preparedStatementMap.get(query); if (statement == null) { statement = this.session.prepare(query); this.preparedStatementMap.put(query, statement); } ResultSet result = this.session.execute(statement.bind(values.toArray())); return result.wasApplied(); }
Example 8
Source File: CassandraStorage.java From cassandra-reaper with Apache License 2.0 | 5 votes |
@Override public boolean takeLead(UUID leaderId, int ttl) { LOG.debug("Trying to take lead on segment {}", leaderId); ResultSet lwtResult = session.execute( takeLeadPrepStmt.bind(leaderId, reaperInstanceId, AppContext.REAPER_INSTANCE_ADDRESS, ttl)); if (lwtResult.wasApplied()) { LOG.debug("Took lead on segment {}", leaderId); return true; } // Another instance took the lead on the segment LOG.debug("Could not take lead on segment {}", leaderId); return false; }
Example 9
Source File: CassandraDatabaseDelegate.java From testcontainers-java with MIT License | 5 votes |
@Override public void execute(String statement, String scriptPath, int lineNumber, boolean continueOnError, boolean ignoreFailedDrops) { try { ResultSet result = getConnection().execute(statement); if (result.wasApplied()) { log.debug("Statement {} was applied", statement); } else { throw new ScriptStatementFailedException(statement, lineNumber, scriptPath); } } catch (DriverException e) { throw new ScriptStatementFailedException(statement, lineNumber, scriptPath, e); } }
Example 10
Source File: MobileDeviceDAOImpl.java From arcusplatform with Apache License 2.0 | 5 votes |
private int incCount(UUID personId) { int currentId = session.execute(new BoundStatement(personCurrentMobileQuery).bind(personId)).one().getInt("mobileDeviceSequence"); int nextId = currentId + 1; ResultSet rs = currentId == 0 ? session.execute(new BoundStatement(initialPersonUpdateCurrentMobile).bind(nextId, personId)) : session.execute(new BoundStatement(personUpdateCurrentMobile).bind(nextId, personId, currentId)); // TODO: should we try multiple times? if (!rs.wasApplied()){ throw new IllegalStateException("Failed to retrieve new identifier for mobile device."); } return nextId; }
Example 11
Source File: MobileDeviceDAOImpl.java From arcusplatform with Apache License 2.0 | 5 votes |
private boolean tryTokenIndexUpdateForDevice(MobileDevice device) { if (!StringUtils.isBlank(device.getNotificationToken())){ ResultSet rs = session.execute(new BoundStatement(optimisticUpdateTokenIndex).bind(device.getPersonId(), device.getDeviceIndex(), device.getNotificationToken())); return rs.wasApplied(); } return false; // isblank or failure }
Example 12
Source File: CassandraExecutionDAO.java From conductor with Apache License 2.0 | 5 votes |
private boolean removeTask(Task task) { // TODO: calculate shard number based on seq and maxTasksPerShard try { // get total tasks for this workflow WorkflowMetadata workflowMetadata = getWorkflowMetadata(task.getWorkflowInstanceId()); int totalTasks = workflowMetadata.getTotalTasks(); // remove from task_lookup table removeTaskLookup(task); recordCassandraDaoRequests("removeTask", task.getTaskType(), task.getWorkflowType()); // delete task from workflows table and decrement total tasks by 1 BatchStatement batchStatement = new BatchStatement(); batchStatement.add(deleteTaskStatement.bind(UUID.fromString(task.getWorkflowInstanceId()), DEFAULT_SHARD_ID, task.getTaskId())); batchStatement.add(updateTotalTasksStatement.bind(totalTasks - 1, UUID.fromString(task.getWorkflowInstanceId()), DEFAULT_SHARD_ID)); ResultSet resultSet = session.execute(batchStatement); if (task.getTaskDefinition().isPresent() && task.getTaskDefinition().get().concurrencyLimit() > 0) { updateTaskDefLimit(task, true); } return resultSet.wasApplied(); } catch (Exception e) { Monitors.error(CLASS_NAME, "removeTask"); String errorMsg = String.format("Failed to remove task: %s", task.getTaskId()); LOGGER.error(errorMsg, e); throw new ApplicationException(Code.BACKEND_ERROR, errorMsg); } }
Example 13
Source File: AbstractUpsertOutputOperator.java From attic-apex-malhar with Apache License 2.0 | 5 votes |
private void updatePerRowMetric(ResultSet result) { uniqueHostsWrittenToInCurrentWindow.add(result.getExecutionInfo().getQueriedHost()); updateConsistencyLevelMetrics(result.getExecutionInfo().getAchievedConsistencyLevel()); successfullWrites += 1; if (!result.wasApplied()) { ignoredRequestsDuetoIfExistsCheck += 1; } }
Example 14
Source File: CassandraSchedulerModelDao.java From arcusplatform with Apache License 2.0 | 5 votes |
protected UUID insertIndices(UUID modelId, String targetAddress, String placeAddress) { ResultSet rs = session().execute( insertTargetIndex.bind(targetAddress, ImmutableSet.of(modelId), Relationship.TARGET.name()) ); if(!rs.wasApplied()) { Set<UUID> ids = rs.one().getSet(SchedulerAddressIndex.Columns.SCHEDULER_IDS, UUID.class); if(ids.isEmpty()) { // TODO repair this index throw new DaoException("Corrupt scheduler index for target: " + targetAddress); } return ids.iterator().next(); } session().execute( addToPlaceIndex.bind(ImmutableSet.of(modelId), placeAddress) ); return null; }
Example 15
Source File: CassandraSchedulerModelDao.java From arcusplatform with Apache License 2.0 | 5 votes |
protected void updateAttributes( Address address, Date timestamp, Set<String> attributes, Function<String, Object> provider ) { List<Object> values = new ArrayList<>(2 * attributes.size() + 3); CassandraUpdateBuilder builder = CassandraQueryBuilder .update(SchedulerTable.NAME) .addColumn(Columns.MODIFIED) ; values.add(timestamp); attributes.forEach((attribute) -> { builder.addColumn(Columns.ATTRIBUTES + "[?]"); values.add(attribute); Object value = provider.apply(attribute); if(value == null) { values.add(null); } else { values.add( encode(attribute, value) ); } }); builder .addWhereColumnEquals(Columns.ID) .ifClause(Columns.CREATED + " != null"); values.add((UUID) address.getId()); ResultSet rs = session().execute(builder.toQuery().toString(), values.toArray()); if(!rs.wasApplied()) { throw new NotFoundException(address); } }
Example 16
Source File: CassandraMemoryDAO.java From modernmt with Apache License 2.0 | 5 votes |
/** * This method receives a Memory object * and stores it in the DB overwriting an existing row with same ID. * If in the DB there is no row with that ID nothing happens. * * @param memory the Memory object to store in the DB * in place of an already existing one * @return the same memory object passed as a parameter, * if the overwrite is successful * (if an object with that ID was already in the DB) * or null if the overwrite was not successful. * @throws PersistenceException */ @Override public Memory update(Memory memory) throws PersistenceException { BuiltStatement built = QueryBuilder.update(CassandraDatabase.MEMORIES_TABLE) .with(QueryBuilder.set("name", memory.getName())) .where(QueryBuilder.eq("id", memory.getId())) .ifExists(); ResultSet result = CassandraUtils.checkedExecute(connection, built); if (result.wasApplied()) return memory; else return null; }
Example 17
Source File: RuleDaoImpl.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public void updateVariables(CompositeId<UUID, Integer> id, Map<String, Object> variables, Date modified) { BoundStatement bs = updateVariables.bind(); bs.setUUID(Column.PLACE_ID.columnName(), id.getPrimaryId()); bs.setInt(Column.ID.columnName(), id.getSecondaryId()); bs.setString(RuleColumn.VARIABLES.columnName(), JSON.toJson(variables)); bs.setTimestamp(Column.MODIFIED.columnName(),modified); ResultSet rs = session.execute(bs); if(!rs.wasApplied()) { throw new IllegalStateException(String.format("Unable to update rule variables. Rule [%s] has been modified since read",id)); } }
Example 18
Source File: BaseRuleEnvironmentDaoImpl.java From arcusplatform with Apache License 2.0 | 5 votes |
public void save(T bean) { Preconditions.checkNotNull(bean, "definition may not be null"); Preconditions.checkArgument(bean.getPlaceId() != null, "object must be associated with a place"); boolean insert = !bean.isPersisted(); Context c; Statement stmt; if(insert) { c = metrics.startDaoCreateTimer(); } else { c = metrics.startDaoUpdateTimer(); } try { Date ts = new Date(); if(insert) { stmt = prepareInsert(bean, ts); } else { stmt = prepareUpdate(bean, ts); } ResultSet rs = session.execute( stmt ); if(!rs.wasApplied()) { throw new IllegalStateException("Failed to persist object"); } } finally { c.close(); } }
Example 19
Source File: CassandraClusterServiceDao.java From arcusplatform with Apache License 2.0 | 4 votes |
private boolean tryRegister(int memberId, Instant heartbeat, BoundStatement statement) { ResultSet rs = session.execute( statement ); return rs.wasApplied(); }
Example 20
Source File: InvitationDAOImpl.java From arcusplatform with Apache License 2.0 | 4 votes |
@Override public Invitation insert(Invitation invitation) { Preconditions.checkNotNull(invitation, "invitation is required"); try(Context timer = insertTimer.time()) { for(int i = 0; i < tokenRetries; i++) { String token = generateToken(); Date created = new Date(); BoundStatement stmt = new BoundStatement(insert); stmt.setString(Column.code.name(), token); stmt.setUUID(Column.placeId.name(), UUID.fromString(invitation.getPlaceId())); stmt.setString(Column.placeName.name(), invitation.getPlaceName()); stmt.setString(Column.streetAddress1.name(), invitation.getStreetAddress1()); stmt.setString(Column.streetAddress2.name(), invitation.getStreetAddress2()); stmt.setString(Column.city.name(), invitation.getCity()); stmt.setString(Column.stateProv.name(), invitation.getStateProv()); stmt.setString(Column.zipCode.name(), invitation.getZipCode()); stmt.setUUID(Column.inviteeId.name(), invitation.getInviteeId() == null ? null : UUID.fromString(invitation.getInviteeId())); stmt.setString(Column.inviteeEmail.name(), invitation.getInviteeEmail().toLowerCase()); stmt.setString(Column.inviteeFirstName.name(), invitation.getInviteeFirstName()); stmt.setString(Column.inviteeLastName.name(), invitation.getInviteeLastName()); stmt.setUUID(Column.invitorId.name(), UUID.fromString(invitation.getInvitorId())); stmt.setString(Column.invitorFirstName.name(), invitation.getInvitorFirstName()); stmt.setString(Column.invitorLastName.name(), invitation.getInvitorLastName()); stmt.setUUID(Column.placeOwnerId.name(), UUID.fromString(invitation.getPlaceOwnerId())); stmt.setString(Column.placeOwnerFirstName.name(), invitation.getPlaceOwnerFirstName()); stmt.setString(Column.placeOwnerLastName.name(), invitation.getPlaceOwnerLastName()); stmt.setTimestamp(Column.created.name(), created); stmt.setTimestamp(Column.accepted.name(), null); stmt.setTimestamp(Column.rejected.name(), null); stmt.setString(Column.rejectReason.name(), invitation.getRejectReason()); stmt.setString(Column.relationship.name(), invitation.getRelationship()); stmt.setString(Column.invitationText.name(), invitation.getInvitationText()); stmt.setString(Column.personalizedGreeting.name(), invitation.getPersonalizedGreeting()); ResultSet rs = session.execute(stmt); if(rs.wasApplied()) { insertIndexes(invitation.getPlaceId(), invitation.getInviteeId(), token); invitation.setCode(token); invitation.setCreated(created); return invitation; } } invitationCodeConflictCounter.inc(); throw new ErrorEventException(Errors.CODE_GENERIC, "unique token could not be found after " + tokenRetries + " attempts"); } }