if (result.wasAcknowledged() && result.getMatchedCount() == 0) { System.err.println("Nothing updated for key " + key); return Status.NOT_FOUND;
private boolean takeOverTransactionInMongoDB(TransactionXid transactionXid, String source, String target) { byte[] global = transactionXid.getGlobalTransactionId(); String instanceId = ByteUtils.byteArrayToString(global); try { String application = CommonUtils.getApplication(this.endpoint); String databaseName = application.replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_LOCKS); Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, instanceId); Bson instIdFilter = Filters.eq("identifier", source); Document document = new Document("$set", new Document("identifier", target)); UpdateResult result = collection.updateOne(Filters.and(globalFilter, instIdFilter), document); return result.getMatchedCount() == 1; } catch (RuntimeException rex) { logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, rex); return false; } }
public void deleteParticipant(XAResourceArchive archive) { try { TransactionXid transactionXid = (TransactionXid) archive.getXid(); byte[] global = transactionXid.getGlobalTransactionId(); byte[] branch = transactionXid.getBranchQualifier(); String globalKey = ByteUtils.byteArrayToString(global); String branchKey = ByteUtils.byteArrayToString(branch); String application = CommonUtils.getApplication(this.endpoint); String databaseName = application.replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS); Document participants = new Document(); participants.append(String.format("participants.%s", branchKey), null); Document document = new Document(); document.append("$unset", participants); UpdateResult result = collection.updateOne(Filters.eq(CONSTANTS_FD_GLOBAL, globalKey), document); if (result.getMatchedCount() != 1) { throw new IllegalStateException( String.format("Error occurred while deleting participant(matched= %s, modified= %s).", result.getMatchedCount(), result.getModifiedCount())); } } catch (RuntimeException error) { logger.error("Error occurred while deleting participant.", error); this.beanFactory.getCompensableManager().setRollbackOnlyQuietly(); } }
if (result.getMatchedCount() > 0) { modifiedStreams.add(streamId); modifiedAlertConditions.add(alertConditionId);
public void putErrorTransaction(TransactionXid transactionXid, Transaction transaction) { try { TransactionArchive archive = (TransactionArchive) transaction.getTransactionArchive(); byte[] global = transactionXid.getGlobalTransactionId(); String identifier = ByteUtils.byteArrayToString(global); int status = archive.getCompensableStatus(); String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS); Document target = new Document(); target.append("modified", this.endpoint); target.append("status", status); target.append("error", true); target.append("recovered_at", archive.getRecoveredAt() == 0 ? null : new Date(archive.getRecoveredAt())); target.append("recovered_times", archive.getRecoveredTimes()); Document document = new Document(); document.append("$set", target); // document.append("$inc", new BasicDBObject("modified_time", 1)); UpdateResult result = collection.updateOne(Filters.eq(CONSTANTS_FD_GLOBAL, identifier), document); if (result.getMatchedCount() != 1) { throw new IllegalStateException( String.format("Error occurred while updating transaction(matched= %s, modified= %s).", result.getMatchedCount(), result.getModifiedCount())); } } catch (RuntimeException error) { logger.error("Error occurred while setting the error flag.", error); } }
@Override public void upgrade() { if (clusterConfigService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already done."); return; } // Do not overwrite an existing default index config boolean defaultDone = clusterConfigService.get(DefaultIndexSetConfig.class) != null; final ImmutableSet.Builder<String> builder = ImmutableSet.builder(); final FindIterable<Document> documents = collection.find(exists(FIELD_DEFAULT)).sort(ascending(FIELD_CREATION_DATE)); for (final Document document : documents) { final ObjectId id = document.getObjectId(FIELD_ID); final String idString = id.toHexString(); final boolean isDefault = firstNonNull(document.getBoolean(FIELD_DEFAULT), false); if (!defaultDone && isDefault) { defaultDone = true; clusterConfigService.write(DefaultIndexSetConfig.create(idString)); } final long modifiedCount = collection.updateOne(eq(FIELD_ID, id), unset(FIELD_DEFAULT)).getMatchedCount(); if (modifiedCount > 0) { LOG.info("Removed <default> field from index set <{}> ({})", document.getString(FIELD_TITLE), idString); builder.add(idString); } else { LOG.error("Couldn't remove <default> field from index set <{}> ({})", document.getString(FIELD_TITLE), idString); } } clusterConfigService.write(MigrationCompleted.create(builder.build())); }
if (result.getMatchedCount() != 1) { throw new IllegalStateException( String.format("Error occurred while updating transaction(matched= %s, modified= %s).", result.getMatchedCount(), result.getModifiedCount()));
if (result.getMatchedCount() != 1) { throw new IllegalStateException( String.format("Error occurred while creating/updating participant(matched= %s, modified= %s).", result.getMatchedCount(), result.getModifiedCount()));
if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
if (result.getMatchedCount() != 1) { throw new IllegalStateException( String.format("Error occurred while creating/updating compensable(matched= %s, modified= %s).", result.getMatchedCount(), result.getModifiedCount()));
private void executeRename(@Nullable final ClientSession clientSession, final BsonValue id, final String newFilename) { UpdateResult updateResult; if (clientSession != null) { updateResult = filesCollection.updateOne(clientSession, new BsonDocument("_id", id), new BsonDocument("$set", new BsonDocument("filename", new BsonString(newFilename)))); } else { updateResult = filesCollection.updateOne(new BsonDocument("_id", id), new BsonDocument("$set", new BsonDocument("filename", new BsonString(newFilename)))); } if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) { throw new MongoGridFSException(format("No file found with the id: %s", id)); } }
if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
@Test public void testUpdateNothing() throws Exception { Document object = json("_id: 1"); UpdateResult result = collection.replaceOne(object, object); assertThat(result.getModifiedCount()).isEqualTo(0); assertThat(result.getMatchedCount()).isEqualTo(0); assertThat(result.getUpsertedId()).isNull(); }
@Override public void extendClaim(String processorName, int segment) throws UnableToClaimTokenException { UpdateResult updateResult = mongoTemplate.trackingTokensCollection() .updateOne(and(eq("processorName", processorName), eq("segment", segment), eq("owner", nodeId)), set("timestamp", TokenEntry.clock.instant().toEpochMilli())); if (updateResult.getMatchedCount() == 0) { throw new UnableToClaimTokenException(format("Unable to extend claim on token token '%s[%s]'. It is owned " + "by another segment.", processorName, segment)); } }
@Test public void testUpsertWithoutChange() { collection.insertOne(json("_id: 1, a: 2, b: 3")); Document query = json("_id: 1"); Document update = json("$set: {a: 2}"); UpdateResult updateResult = collection.updateOne(query, update, new UpdateOptions().upsert(true)); assertThat(updateResult.getModifiedCount()).isZero(); assertThat(updateResult.getMatchedCount()).isOne(); assertThat(collection.find().first()).isEqualTo(json("_id: 1, a: 2, b: 3")); }
private Source<Boolean, NotUsed> delete(final String thingId, final Bson filter, final Bson document) { return Source.fromPublisher(collection.updateOne(filter, document)) .flatMapConcat(deleteResult -> { if (deleteResult.getMatchedCount() <= 0) { return Source.single(Boolean.FALSE); } final PolicyUpdate deletePolicyEntries = PolicyUpdateFactory.createDeleteThingUpdate(thingId); final Bson policyIndexRemoveFilter = deletePolicyEntries.getPolicyIndexRemoveFilter(); return Source.fromPublisher(policiesCollection.deleteMany(policyIndexRemoveFilter)) .map(r -> true); }); }
private Source<Boolean, NotUsed> delete(final String thingId, final Bson filter, final Bson document) { return Source.fromPublisher(collection.updateOne(filter, document)) .flatMapConcat(deleteResult -> { if (deleteResult.getMatchedCount() <= 0) { return Source.single(Boolean.FALSE); } final PolicyUpdate deletePolicyEntries = PolicyUpdateFactory.createDeleteThingUpdate(thingId); final Bson policyIndexRemoveFilter = deletePolicyEntries.getPolicyIndexRemoveFilter(); return Source.fromPublisher(policiesCollection.deleteMany(policyIndexRemoveFilter)) .map(r -> true); }); }
/** * {@inheritDoc} */ @Override protected final Source<Boolean, NotUsed> save(final Thing thing, final long revision, final long policyRevision) { log.debug("Saving Thing with revision <{}> and policy revision <{}>: <{}>", revision, policyRevision, thing); final Bson filter = filterWithLowerThingRevisionOrLowerPolicyRevision(getThingId(thing), revision, policyRevision); final Document document = toUpdate(ThingDocumentMapper.toDocument(thing), revision, policyRevision); return Source.fromPublisher(collection.updateOne(filter, document, new UpdateOptions().upsert(true))) .map(updateResult -> updateResult.getMatchedCount() > 0 || null != updateResult.getUpsertedId()); }
/** * {@inheritDoc} */ @Override protected final Source<Boolean, NotUsed> save(final Thing thing, final long revision, final long policyRevision) { log.debug("Saving Thing with revision <{}> and policy revision <{}>: <{}>", revision, policyRevision, thing); final Bson filter = filterWithLowerThingRevisionOrLowerPolicyRevision(getThingId(thing), revision, policyRevision); final Document document = toUpdate(ThingDocumentMapper.toDocument(thing), revision, policyRevision); return Source.fromPublisher(collection.updateOne(filter, document, new UpdateOptions().upsert(true))) .map(updateResult -> updateResult.getMatchedCount() > 0 || null != updateResult.getUpsertedId()); }
private void executeRename(@Nullable final ClientSession clientSession, final BsonValue id, final String newFilename) { UpdateResult updateResult; if (clientSession != null) { updateResult = filesCollection.updateOne(clientSession, new BsonDocument("_id", id), new BsonDocument("$set", new BsonDocument("filename", new BsonString(newFilename)))); } else { updateResult = filesCollection.updateOne(new BsonDocument("_id", id), new BsonDocument("$set", new BsonDocument("filename", new BsonString(newFilename)))); } if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) { throw new MongoGridFSException(format("No file found with the id: %s", id)); } }