Search in sources :

Example 6 with MongoCursor

use of com.mongodb.client.MongoCursor in project nifi by apache.

the class GetMongo method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile input = null;
    if (context.hasIncomingConnection()) {
        input = session.get();
        if (input == null && context.hasNonLoopConnection()) {
            return;
        }
    }
    final ComponentLog logger = getLogger();
    Map attributes = new HashMap();
    attributes.put(CoreAttributes.MIME_TYPE.key(), "application/json");
    final Document query;
    String queryStr;
    if (context.getProperty(QUERY).isSet()) {
        queryStr = context.getProperty(QUERY).evaluateAttributeExpressions(input).getValue();
        query = Document.parse(queryStr);
    } else if (!context.getProperty(QUERY).isSet() && input == null) {
        queryStr = "{}";
        query = Document.parse("{}");
    } else {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            session.exportTo(input, out);
            out.close();
            queryStr = new String(out.toByteArray());
            query = Document.parse(queryStr);
        } catch (Exception ex) {
            getLogger().error("Error reading flowfile", ex);
            if (input != null) {
                // Likely culprit is a bad query
                session.transfer(input, REL_FAILURE);
                return;
            } else {
                throw new ProcessException(ex);
            }
        }
    }
    if (context.getProperty(QUERY_ATTRIBUTE).isSet()) {
        final String queryAttr = context.getProperty(QUERY_ATTRIBUTE).evaluateAttributeExpressions(input).getValue();
        attributes.put(queryAttr, queryStr);
    }
    final Document projection = context.getProperty(PROJECTION).isSet() ? Document.parse(context.getProperty(PROJECTION).evaluateAttributeExpressions(input).getValue()) : null;
    final Document sort = context.getProperty(SORT).isSet() ? Document.parse(context.getProperty(SORT).evaluateAttributeExpressions(input).getValue()) : null;
    final String jsonTypeSetting = context.getProperty(JSON_TYPE).getValue();
    final String usePrettyPrint = context.getProperty(USE_PRETTY_PRINTING).getValue();
    configureMapper(jsonTypeSetting);
    final MongoCollection<Document> collection = getCollection(context);
    try {
        final FindIterable<Document> it = query != null ? collection.find(query) : collection.find();
        if (projection != null) {
            it.projection(projection);
        }
        if (sort != null) {
            it.sort(sort);
        }
        if (context.getProperty(LIMIT).isSet()) {
            it.limit(context.getProperty(LIMIT).evaluateAttributeExpressions(input).asInteger());
        }
        if (context.getProperty(BATCH_SIZE).isSet()) {
            it.batchSize(context.getProperty(BATCH_SIZE).evaluateAttributeExpressions(input).asInteger());
        }
        final MongoCursor<Document> cursor = it.iterator();
        ComponentLog log = getLogger();
        try {
            FlowFile flowFile = null;
            if (context.getProperty(RESULTS_PER_FLOWFILE).isSet()) {
                int ceiling = context.getProperty(RESULTS_PER_FLOWFILE).evaluateAttributeExpressions(input).asInteger();
                List<Document> batch = new ArrayList<>();
                while (cursor.hasNext()) {
                    batch.add(cursor.next());
                    if (batch.size() == ceiling) {
                        try {
                            if (log.isDebugEnabled()) {
                                log.debug("Writing batch...");
                            }
                            String payload = buildBatch(batch, jsonTypeSetting, usePrettyPrint);
                            writeBatch(payload, null, context, session, attributes, REL_SUCCESS);
                            batch = new ArrayList<>();
                        } catch (Exception ex) {
                            getLogger().error("Error building batch", ex);
                        }
                    }
                }
                if (batch.size() > 0) {
                    try {
                        writeBatch(buildBatch(batch, jsonTypeSetting, usePrettyPrint), null, context, session, attributes, REL_SUCCESS);
                    } catch (Exception ex) {
                        getLogger().error("Error sending remainder of batch", ex);
                    }
                }
            } else {
                while (cursor.hasNext()) {
                    flowFile = session.create();
                    flowFile = session.write(flowFile, out -> {
                        String json;
                        if (jsonTypeSetting.equals(JSON_TYPE_STANDARD)) {
                            json = getObjectWriter(mapper, usePrettyPrint).writeValueAsString(cursor.next());
                        } else {
                            json = cursor.next().toJson();
                        }
                        out.write(json.getBytes(context.getProperty(CHARSET).evaluateAttributeExpressions().getValue()));
                    });
                    flowFile = session.putAllAttributes(flowFile, attributes);
                    session.getProvenanceReporter().receive(flowFile, getURI(context));
                    session.transfer(flowFile, REL_SUCCESS);
                }
            }
            if (input != null) {
                session.transfer(input, REL_ORIGINAL);
            }
        } finally {
            cursor.close();
        }
    } catch (final RuntimeException e) {
        if (input != null) {
            session.transfer(input, REL_FAILURE);
        }
        context.yield();
        logger.error("Failed to execute query {} due to {}", new Object[] { query, e }, e);
    }
}
Also used : StandardValidators(org.apache.nifi.processor.util.StandardValidators) Document(org.bson.Document) MongoCollection(com.mongodb.client.MongoCollection) CapabilityDescription(org.apache.nifi.annotation.documentation.CapabilityDescription) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonWriterSettings(org.bson.json.JsonWriterSettings) SimpleDateFormat(java.text.SimpleDateFormat) HashMap(java.util.HashMap) ComponentLog(org.apache.nifi.logging.ComponentLog) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ProcessException(org.apache.nifi.processor.exception.ProcessException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) MongoCursor(com.mongodb.client.MongoCursor) Relationship(org.apache.nifi.processor.Relationship) Map(java.util.Map) Requirement(org.apache.nifi.annotation.behavior.InputRequirement.Requirement) ValidationResult(org.apache.nifi.components.ValidationResult) DateFormat(java.text.DateFormat) Validator(org.apache.nifi.components.Validator) FlowFile(org.apache.nifi.flowfile.FlowFile) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ProcessContext(org.apache.nifi.processor.ProcessContext) Set(java.util.Set) ProcessSession(org.apache.nifi.processor.ProcessSession) IOException(java.io.IOException) AllowableValue(org.apache.nifi.components.AllowableValue) InputRequirement(org.apache.nifi.annotation.behavior.InputRequirement) List(java.util.List) FindIterable(com.mongodb.client.FindIterable) Tags(org.apache.nifi.annotation.documentation.Tags) CoreAttributes(org.apache.nifi.flowfile.attributes.CoreAttributes) Collections(java.util.Collections) FlowFile(org.apache.nifi.flowfile.FlowFile) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.bson.Document) ComponentLog(org.apache.nifi.logging.ComponentLog) ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException) ProcessException(org.apache.nifi.processor.exception.ProcessException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with MongoCursor

use of com.mongodb.client.MongoCursor in project nifi by apache.

the class RunMongoAggregation method onTrigger.

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = null;
    if (context.hasIncomingConnection()) {
        flowFile = session.get();
        if (flowFile == null && context.hasNonLoopConnection()) {
            return;
        }
    }
    String query = context.getProperty(QUERY).evaluateAttributeExpressions(flowFile).getValue();
    String queryAttr = context.getProperty(QUERY_ATTRIBUTE).evaluateAttributeExpressions(flowFile).getValue();
    Integer batchSize = context.getProperty(BATCH_SIZE).asInteger();
    Integer resultsPerFlowfile = context.getProperty(RESULTS_PER_FLOWFILE).asInteger();
    Map attrs = new HashMap();
    if (queryAttr != null && queryAttr.trim().length() > 0) {
        attrs.put(queryAttr, query);
    }
    MongoCollection collection = getCollection(context);
    MongoCursor iter = null;
    try {
        List<Bson> aggQuery = buildAggregationQuery(query);
        AggregateIterable it = collection.aggregate(aggQuery);
        it.batchSize(batchSize != null ? batchSize : 1);
        iter = it.iterator();
        List batch = new ArrayList();
        while (iter.hasNext()) {
            batch.add(iter.next());
            if (batch.size() == resultsPerFlowfile) {
                writeBatch(buildBatch(batch), flowFile, context, session, attrs, REL_RESULTS);
                batch = new ArrayList();
            }
        }
        if (batch.size() > 0) {
            writeBatch(buildBatch(batch), flowFile, context, session, attrs, REL_RESULTS);
        }
        if (flowFile != null) {
            session.transfer(flowFile, REL_ORIGINAL);
        }
    } catch (Exception e) {
        getLogger().error("Error running MongoDB aggregation query.", e);
        if (flowFile != null) {
            session.transfer(flowFile, REL_FAILURE);
        }
    } finally {
        if (iter != null) {
            iter.close();
        }
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException) Bson(org.bson.conversions.Bson) MongoCollection(com.mongodb.client.MongoCollection) ArrayList(java.util.ArrayList) List(java.util.List) MongoCursor(com.mongodb.client.MongoCursor) AggregateIterable(com.mongodb.client.AggregateIterable) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with MongoCursor

use of com.mongodb.client.MongoCursor in project LuckPerms by lucko.

the class MongoDao method savePlayerData.

@Override
public PlayerSaveResult savePlayerData(UUID uuid, String username) {
    username = username.toLowerCase();
    MongoCollection<Document> c = this.database.getCollection(this.prefix + "uuid");
    // find any existing mapping
    String oldUsername = getPlayerName(uuid);
    // do the insert
    if (!username.equalsIgnoreCase(oldUsername)) {
        c.replaceOne(new Document("_id", uuid), new Document("_id", uuid).append("name", username), new UpdateOptions().upsert(true));
    }
    PlayerSaveResult result = PlayerSaveResult.determineBaseResult(username, oldUsername);
    Set<UUID> conflicting = new HashSet<>();
    try (MongoCursor<Document> cursor = c.find(new Document("name", username)).iterator()) {
        if (cursor.hasNext()) {
            conflicting.add(cursor.next().get("_id", UUID.class));
        }
    }
    conflicting.remove(uuid);
    if (!conflicting.isEmpty()) {
        // remove the mappings for conflicting uuids
        c.deleteMany(Filters.and(conflicting.stream().map(u -> Filters.eq("_id", u)).collect(Collectors.toList())));
        result = result.withOtherUuidsPresent(conflicting);
    }
    return result;
}
Also used : PlayerSaveResult(me.lucko.luckperms.common.storage.PlayerSaveResult) LogEntry(me.lucko.luckperms.api.LogEntry) Document(org.bson.Document) MongoClientURI(com.mongodb.MongoClientURI) AbstractDao(me.lucko.luckperms.common.storage.dao.AbstractDao) MongoCredential(com.mongodb.MongoCredential) MongoCollection(com.mongodb.client.MongoCollection) UserIdentifier(me.lucko.luckperms.common.references.UserIdentifier) MongoDatabase(com.mongodb.client.MongoDatabase) MutableContextSet(me.lucko.luckperms.api.context.MutableContextSet) BulkUpdate(me.lucko.luckperms.common.bulkupdate.BulkUpdate) ArrayList(java.util.ArrayList) Filters(com.mongodb.client.model.Filters) LegacyNodeFactory(me.lucko.luckperms.common.node.LegacyNodeFactory) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Strings(com.google.common.base.Strings) PlayerSaveResult(me.lucko.luckperms.common.storage.PlayerSaveResult) NodeModel(me.lucko.luckperms.common.node.NodeModel) MongoCursor(com.mongodb.client.MongoCursor) MongoClientOptions(com.mongodb.MongoClientOptions) Map(java.util.Map) LuckPermsPlugin(me.lucko.luckperms.common.plugin.LuckPermsPlugin) HeldPermission(me.lucko.luckperms.api.HeldPermission) UpdateOptions(com.mongodb.client.model.UpdateOptions) ServerAddress(com.mongodb.ServerAddress) ExtendedLogEntry(me.lucko.luckperms.common.actionlog.ExtendedLogEntry) GroupManager(me.lucko.luckperms.common.managers.group.GroupManager) StorageCredentials(me.lucko.luckperms.common.storage.StorageCredentials) NodeHeldPermission(me.lucko.luckperms.common.node.NodeHeldPermission) Set(java.util.Set) ImmutableContextSet(me.lucko.luckperms.api.context.ImmutableContextSet) Log(me.lucko.luckperms.common.actionlog.Log) NodeFactory(me.lucko.luckperms.common.node.NodeFactory) UUID(java.util.UUID) ContextSet(me.lucko.luckperms.api.context.ContextSet) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Track(me.lucko.luckperms.common.model.Track) List(java.util.List) TrackManager(me.lucko.luckperms.common.managers.track.TrackManager) MongoClient(com.mongodb.MongoClient) Group(me.lucko.luckperms.common.model.Group) Optional(java.util.Optional) Node(me.lucko.luckperms.api.Node) User(me.lucko.luckperms.common.model.User) Document(org.bson.Document) UUID(java.util.UUID) UpdateOptions(com.mongodb.client.model.UpdateOptions) HashSet(java.util.HashSet)

Example 9 with MongoCursor

use of com.mongodb.client.MongoCursor in project jackrabbit-oak by apache.

the class MongoBlobReferenceIterator method getIteratorOverDocsWithBinaries.

@Override
public Iterator<NodeDocument> getIteratorOverDocsWithBinaries() {
    Bson query = Filters.eq(NodeDocument.HAS_BINARY_FLAG, NodeDocument.HAS_BINARY_VAL);
    // TODO It currently prefers secondary. Would that be Ok?
    MongoCursor<BasicDBObject> cursor = documentStore.getDBCollection(NODES).withReadPreference(documentStore.getConfiguredReadPreference(NODES)).find(query).iterator();
    return CloseableIterator.wrap(transform(cursor, input -> documentStore.convertFromDBObject(NODES, input)), cursor);
}
Also used : Bson(org.bson.conversions.Bson) Filters(com.mongodb.client.model.Filters) Iterator(java.util.Iterator) MongoCursor(com.mongodb.client.MongoCursor) DocumentNodeStore(org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore) BasicDBObject(com.mongodb.BasicDBObject) NodeDocument(org.apache.jackrabbit.oak.plugins.document.NodeDocument) Iterators.transform(com.google.common.collect.Iterators.transform) BlobReferenceIterator(org.apache.jackrabbit.oak.plugins.document.BlobReferenceIterator) NODES(org.apache.jackrabbit.oak.plugins.document.Collection.NODES) CloseableIterator(org.apache.jackrabbit.oak.plugins.document.util.CloseableIterator) BasicDBObject(com.mongodb.BasicDBObject) Bson(org.bson.conversions.Bson)

Example 10 with MongoCursor

use of com.mongodb.client.MongoCursor in project jackrabbit-oak by apache.

the class MongoStatus method isMajorityReadConcernEnabled.

/**
 * Check if the majority read concern is enabled and can be used for queries.
 *
 * @return true if the majority read concern is enabled
 */
public boolean isMajorityReadConcernEnabled() {
    if (majorityReadConcernEnabled == null) {
        // Mongo API doesn't seem to provide an option to check whether the
        // majority read concern has been enabled, so we have to try to use
        // it and optionally catch the exception.
        MongoCollection<?> emptyCollection = client.getDatabase(dbName).getCollection("emptyCollection-" + System.currentTimeMillis());
        try (MongoCursor cursor = emptyCollection.withReadConcern(ReadConcern.MAJORITY).find(new BasicDBObject()).iterator()) {
            cursor.hasNext();
            majorityReadConcernEnabled = true;
        } catch (MongoQueryException | IllegalArgumentException e) {
            majorityReadConcernEnabled = false;
        }
    }
    return majorityReadConcernEnabled;
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) MongoCursor(com.mongodb.client.MongoCursor) MongoQueryException(com.mongodb.MongoQueryException)

Aggregations

MongoCursor (com.mongodb.client.MongoCursor)13 Document (org.bson.Document)10 MapReduceIterable (com.mongodb.client.MapReduceIterable)5 MongoCollection (com.mongodb.client.MongoCollection)5 List (java.util.List)5 Test (org.junit.jupiter.api.Test)5 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 Set (java.util.Set)4 Bson (org.bson.conversions.Bson)4 BasicQuery (org.springframework.data.mongodb.core.query.BasicQuery)4 NearQuery (org.springframework.data.mongodb.core.query.NearQuery)4 Query (org.springframework.data.mongodb.core.query.Query)4 FindIterable (com.mongodb.client.FindIterable)3 MongoDatabase (com.mongodb.client.MongoDatabase)3 Filters (com.mongodb.client.model.Filters)3 HashSet (java.util.HashSet)3 BasicDBObject (com.mongodb.BasicDBObject)2 ServerAddress (com.mongodb.ServerAddress)2 IOException (java.io.IOException)2