private boolean lockTransactionInMongoDB(TransactionXid transactionXid, String identifier) { 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); Document document = new Document(); document.append(CONSTANTS_FD_GLOBAL, instanceId); document.append("identifier", identifier); collection.insertOne(document); return true; } catch (com.mongodb.MongoWriteException error) { com.mongodb.WriteError writeError = error.getError(); if (MONGODB_ERROR_DUPLICATE_KEY != writeError.getCode()) { logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, error); } return false; } catch (RuntimeException rex) { logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, rex); return false; } }
private BulkWriteResult executeSingleWriteRequest(@Nullable final ClientSession clientSession, final WriteOperation<BulkWriteResult> writeOperation, final WriteRequest.Type type) { try { return executor.execute(writeOperation, readConcern, clientSession); } catch (MongoBulkWriteException e) { if (e.getWriteErrors().isEmpty()) { throw new MongoWriteConcernException(e.getWriteConcernError(), translateBulkWriteResult(type, e.getWriteResult()), e.getServerAddress()); } else { throw new MongoWriteException(new WriteError(e.getWriteErrors().get(0)), e.getServerAddress()); } } }
@Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BulkWriteError that = (BulkWriteError) o; if (index != that.index) { return false; } return super.equals(that); }
/** * Construct an instance * @param error the error * @param serverAddress the server address */ public MongoWriteException(final WriteError error, final ServerAddress serverAddress) { super(error.getCode(), error.getMessage(), serverAddress); this.error = error; }
public boolean acquireLock(MongoDatabase db) { Document insertObj = new Document(KEY_PROP_NAME, LOCK_ENTRY_KEY_VAL).append("status", "LOCK_HELD"); // acquire lock by attempting to insert the same value in the collection - if it already exists (i.e. lock held) // there will be an exception try { db.getCollection(lockCollectionName).insertOne(insertObj); } catch (MongoWriteException ex) { if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) { logger.warn("Duplicate key exception while acquireLock. Probably the lock has been already acquired."); } return false; } return true; }
@Override public int hashCode() { int result = super.hashCode(); result = 31 * result + index; return result; }
/** * Construct an instance * @param error the error * @param serverAddress the server address */ public MongoWriteException(final WriteError error, final ServerAddress serverAddress) { super(error.getCode(), error.getMessage(), serverAddress); this.error = error; }
public boolean acquireLock(MongoDatabase db) { Document insertObj = new Document(KEY_PROP_NAME, LOCK_ENTRY_KEY_VAL).append("status", "LOCK_HELD"); // acquire lock by attempting to insert the same value in the collection - if it already exists (i.e. lock held) // there will be an exception try { db.getCollection(lockCollectionName).insertOne(insertObj); } catch (MongoWriteException ex) { if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) { logger.warn("Duplicate key exception while acquireLock. Probably the lock has been already acquired."); } return false; } return true; }
@Override public int hashCode() { int result = super.hashCode(); result = 31 * result + index; return result; }
private static boolean hasErrorCode(final WriteError error, final int expectedErrorCode) { return expectedErrorCode == error.getCode(); }
@ManagedOperation(description = "Adds the key to the store") @Override public boolean add(E key) { Document document = new Document("_id", key); try { collection.insertOne(document); } catch (com.mongodb.MongoWriteException ex) { if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) { return false; } throw ex; } return true; }
private BulkWriteResult executeSingleWriteRequest(@Nullable final ClientSession clientSession, final WriteOperation<BulkWriteResult> writeOperation, final WriteRequest.Type type) { try { return executor.execute(writeOperation, readConcern, clientSession); } catch (MongoBulkWriteException e) { if (e.getWriteErrors().isEmpty()) { throw new MongoWriteConcernException(e.getWriteConcernError(), translateBulkWriteResult(type, e.getWriteResult()), e.getServerAddress()); } else { throw new MongoWriteException(new WriteError(e.getWriteErrors().get(0)), e.getServerAddress()); } } }
@Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BulkWriteError that = (BulkWriteError) o; if (index != that.index) { return false; } return super.equals(that); }
private static boolean hasErrorCode(final WriteError error, final int expectedErrorCode) { return expectedErrorCode == error.getCode(); }
/** * Common handler for creating new objects. Assures that errors are handled in a * consistent way. * * @param collection * @param object * @throws SiteWhereException */ public static void insert(MongoCollection<Document> collection, Document object, ErrorCode ifDuplicate) throws SiteWhereException { try { long start = System.currentTimeMillis(); collection.insertOne(object); LOGGER.trace("Insert took " + (System.currentTimeMillis() - start) + " ms."); } catch (MongoWriteException e) { ErrorCategory category = e.getError().getCategory(); if (ErrorCategory.DUPLICATE_KEY == category) { throw new ResourceExistsException(ifDuplicate); } throw new SiteWhereException("Error during MongoDB insert.", e); } catch (MongoClientException e) { throw handleClientException(e); } }
private BulkWriteResult executeSingleWriteRequest(@Nullable final ClientSession clientSession, final WriteOperation<BulkWriteResult> writeOperation, final WriteRequest.Type type) { try { return executor.execute(writeOperation, readConcern, clientSession); } catch (MongoBulkWriteException e) { if (e.getWriteErrors().isEmpty()) { throw new MongoWriteConcernException(e.getWriteConcernError(), translateBulkWriteResult(type, e.getWriteResult()), e.getServerAddress()); } else { throw new MongoWriteException(new WriteError(e.getWriteErrors().get(0)), e.getServerAddress()); } } }
private static void assertMongoWriteException(Callable callable, int expectedErrorCode, String expectedMessage) { try { callable.call(); fail("MongoWriteException expected"); } catch (MongoWriteException e) { assertThat(e).hasMessage(expectedMessage); assertThat(e.getError().getCode()).isEqualTo(expectedErrorCode); } }
private void insertUpdate(LockEntry newLock, boolean onlyIfSameOwner) { boolean lockHeld; try { final Bson acquireLockQuery = getAcquireLockQuery(newLock.getKey(), newLock.getOwner(), onlyIfSameOwner); final UpdateResult result = collection.updateMany( acquireLockQuery, new Document().append("$set", newLock.buildFullDBObject()), new UpdateOptions().upsert(!onlyIfSameOwner)); lockHeld = result.getModifiedCount() <= 0 && result.getUpsertedId() == null; } catch (MongoWriteException ex) { lockHeld = ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY; if (!lockHeld) { throw ex; } } catch (DuplicateKeyException ex) { lockHeld = true; } if (lockHeld) { throw new LockPersistenceException("Lock is held"); } }
} catch (MongoWriteException e) { if (e.getError().getCode() != 11000) { throw e;
private void updateOrInsertTokenEntry(TrackingToken token, String processorName, int segment) { AbstractTokenEntry<?> tokenEntry = new GenericTokenEntry<>(token, serializer, contentType, processorName, segment); tokenEntry.claim(nodeId, claimTimeout); Bson update = combine(set("owner", nodeId), set("timestamp", tokenEntry.timestamp().toEpochMilli()), set("token", tokenEntry.getSerializedToken().getData()), set("tokenType", tokenEntry.getSerializedToken().getType().getName())); UpdateResult updateResult = mongoTemplate.trackingTokensCollection() .updateOne(claimableTokenEntryFilter(processorName, segment), update); if (updateResult.getModifiedCount() == 0) { try { mongoTemplate.trackingTokensCollection() .insertOne(tokenEntryToDocument(tokenEntry)); } catch (MongoWriteException exception) { if (ErrorCategory.fromErrorCode(exception.getError().getCode()) == ErrorCategory.DUPLICATE_KEY) { throw new UnableToClaimTokenException(format("Unable to claim token '%s[%s]'", processorName, segment)); } } } }