/** * Inserts or replaces an object in the database, depending on whether the * passed ID is null or not. * * @param indexName Index name * @param id ID of the object to be updated. If null - a new entry will be created and generated ID will be returned * @param objectContents Object contents, to be associated with a given or newly created ID * @return ID of the updated object. Matches given ID if passed ID is null */ @Nonnull default Key updateObject(@Nonnull String indexName, @Nullable Key id, @Nonnull byte[] objectContents) { return withTransaction(tx -> withIndex(indexName, index -> { Key resultId = id; if (resultId != null) { if (!index.replace(tx, resultId.getBytesNoCopy(), objectContents)) { throw new KeyNotFoundException(id); } } else { boolean inserted; do { resultId = Key.random(); inserted = index.insert(tx, resultId.getBytesNoCopy(), objectContents); } while (!inserted); // repeat until new key is created } return resultId; })); }