@Override public Bson createFilter(ITuple tuple) { return Filters.eq(field, tuple.getValueByField(field)); }
@Override public Bson createFilterByKeys(List<Object> keys) { return Filters.eq("_id", MongoUtils.getId(keys)); }
public Bson getIdFilter() { return Filters.eq(ID_FIELD, document.get(ID_FIELD)); }
/** * Creates a filter that matches all documents where the value of _id field equals the specified value. Note that this doesn't * actually generate a $eq operator, as the query language doesn't require it. * * @param value the value, which may be null * @param <TItem> the value type * @return the filter * @mongodb.driver.manual reference/operator/query/eq $eq * * @since 3.4 */ public static <TItem> Bson eq(@Nullable final TItem value) { return eq("_id", value); }
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; } }
private void markTransactionRollback(TransactionXid transactionXid) { try { byte[] global = transactionXid.getGlobalTransactionId(); String identifier = ByteUtils.byteArrayToString(global); 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 document = new Document(); document.append("$set", new Document("status", Status.STATUS_MARKED_ROLLBACK)); Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, identifier); Bson statusFilter = Filters.eq("status", Status.STATUS_ACTIVE); collection.updateOne(Filters.and(globalFilter, statusFilter), document); } catch (RuntimeException error) { logger.error("Error occurred while setting the error flag.", error); } }
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public Session get(final Builder builder) { return Optional.ofNullable(sessions.find(Filters.eq("_id", builder.sessionId())).first()) .map(doc -> { Map session = new LinkedHashMap<>(doc); Date accessedAt = (Date) session.remove("_accessedAt"); Date createdAt = (Date) session.remove("_createdAt"); Date savedAt = (Date) session.remove("_savedAt"); session.remove("_id"); builder .accessedAt(accessedAt.getTime()) .createdAt(createdAt.getTime()) .savedAt(savedAt.getTime()); session.forEach((k, v) -> builder.set(decode(k.toString()), v.toString())); return builder.build(); }).orElse(null); }
public void unlockTransactionInMongoDB(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); Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, instanceId); Bson instIdFilter = Filters.eq("identifier", identifier); DeleteResult result = collection.deleteOne(Filters.and(globalFilter, instIdFilter)); if (result.getDeletedCount() == 0) { logger.warn("Error occurred while unlocking transaction(gxid= {}).", instanceId); } } catch (RuntimeException rex) { logger.error("Error occurred while unlocking transaction(gxid= {})!", instanceId, rex); } }
/** * Add field use_raw_configuration_schema to endpointProfile that used to support devices using * SDK version 0.9.0 */ public void transform() { //mongo MongoClient client = new MongoClient(host); MongoDatabase database = client.getDatabase(dbName); MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile"); endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false))); //cassandra Cluster cluster = Cluster.builder().addContactPoint(host).build(); Session session = cluster.connect(dbName); session.execute("ALTER TABLE ep_profile ADD use_raw_schema boolean"); session.close(); cluster.close(); } }
private void removeConfigPath() { final FindIterable<Document> documentsWithConfigPath = collection.find(exists("configuration_path")); for (Document document : documentsWithConfigPath) { final ObjectId objectId = document.getObjectId("_id"); document.remove("configuration_path"); final UpdateResult updateResult = collection.replaceOne(eq("_id", objectId), document); if (updateResult.wasAcknowledged()) { LOG.debug("Successfully updated document with ID <{}>", objectId); } else { LOG.error("Failed to update document with ID <{}>", objectId); } } }
@Override public Document fetch(DBRef dbRef) { StringUtils.hasText(dbRef.getDatabaseName()); return getCollection(dbRef).find(Filters.eq("_id", dbRef.getId())).first(); }
collection.deleteOne(eq("_id", id));
public void deleteTransaction(TransactionArchive archive) { try { TransactionXid transactionXid = (TransactionXid) archive.getXid(); byte[] global = transactionXid.getGlobalTransactionId(); String identifier = ByteUtils.byteArrayToString(global); String application = CommonUtils.getApplication(this.endpoint); String databaseName = application.replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> transactions = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS); DeleteResult result = transactions.deleteOne(Filters.eq(CONSTANTS_FD_GLOBAL, identifier)); if (result.getDeletedCount() != 1) { logger.error("Error occurred while deleting transaction(deleted= {}).", result.getDeletedCount()); } } catch (RuntimeException error) { logger.error("Error occurred while deleting transaction!", error); } }
private void initializeClusterInstanceVersion() { String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_"); MongoDatabase database = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> instances = database.getCollection(CONSTANTS_TB_INSTS); Bson condition = Filters.eq("_id", this.endpoint); Document increases = new Document(); increases.append("version", 1L); Document document = new Document(); document.append("$inc", increases); FindOneAndUpdateOptions options = new FindOneAndUpdateOptions(); options.upsert(true); Document target = instances.findOneAndUpdate(condition, document, new FindOneAndUpdateOptions().upsert(true)); this.instanceVersion = (target == null) ? 1 : (target.getLong("version") + 1); }
@Override public void save(final Session session) { syncTtl(); String id = session.id(); Bson filter = Filters.eq("_id", id); Document doc = new Document() .append("_id", id) .append("_accessedAt", new Date(session.accessedAt())) .append("_createdAt", new Date(session.createdAt())) .append("_savedAt", new Date(session.savedAt())); // dump attributes Map<String, String> attributes = session.attributes(); attributes.forEach((k, v) -> doc.append(encode(k), v)); sessions.updateOne(filter, new Document("$set", doc), new UpdateOptions().upsert(true)); }
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(); } }
private String getTransactionOwnerInMongoDB(TransactionXid transactionXid) { 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); FindIterable<Document> findIterable = collection.find(Filters.eq(CONSTANTS_FD_GLOBAL, instanceId)); MongoCursor<Document> cursor = findIterable.iterator(); if (cursor.hasNext()) { Document document = cursor.next(); return document.getString("identifier"); } else { return null; } } catch (RuntimeException rex) { logger.error("Error occurred while querying the lock-owner of transaction(gxid= {}).", instanceId, rex); return null; } }
@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())); }
@Override public void upgrade() { final FindIterable<Document> documentsWithMissingFields = collection.find(or(not(exists(ContentPack.FIELD_META_ID)), not(exists(ContentPack.FIELD_META_REVISION)))); for (Document document : documentsWithMissingFields) { final ObjectId objectId = document.getObjectId("_id"); LOG.debug("Found document with missing \"id\" or \"rev\" field with ID <{}>", objectId); final String id = document.get("id", objectId.toHexString()); final int rev = document.get("rev", 0); document.put("id", id); document.put("rev", rev); final UpdateResult updateResult = collection.replaceOne(eq("_id", objectId), document); if (updateResult.wasAcknowledged()) { LOG.debug("Successfully updated document with ID <{}>", objectId); } else { LOG.error("Failed to update document with ID <{}>", objectId); } } } }
public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { if (dbId != null) { collection.replaceOne(Filters.eq("_id", dbId.get("_id")), dbDoc); } else { if (dbDoc.containsKey("_id") && dbDoc.get("_id") == null) { dbDoc.remove("_id"); } collection.insertOne(dbDoc); } return null; } });