Search in sources :

Example 21 with MongoCollection

use of com.mongodb.client.MongoCollection in project MyPet by xXKeyleXx.

the class MongoDbRepository method getAllMyPets.

@Override
@SuppressWarnings("unchecked")
public List<StoredMyPet> getAllMyPets() {
    List<MyPetPlayer> playerList = getAllMyPetPlayers();
    final Map<UUID, MyPetPlayer> owners = new HashMap<>();
    for (MyPetPlayer player : playerList) {
        owners.put(player.getInternalUUID(), player);
    }
    MongoCollection petCollection = this.db.getCollection(Configuration.Repository.MongoDB.PREFIX + "pets");
    final List<StoredMyPet> myPetList = new ArrayList<>();
    petCollection.find().forEach((Block<Document>) document -> {
        UUID ownerUUID = UUID.fromString(document.getString("owner_uuid"));
        if (owners.containsKey(ownerUUID)) {
            StoredMyPet storedMyPet = documentToMyPet(owners.get(ownerUUID), document);
            if (storedMyPet != null) {
                myPetList.add(storedMyPet);
            }
        }
    });
    return myPetList;
}
Also used : Document(org.bson.Document) java.util(java.util) MongoCollection(com.mongodb.client.MongoCollection) Repository(de.Keyle.MyPet.api.repository.Repository) RepositoryCallback(de.Keyle.MyPet.api.repository.RepositoryCallback) MongoDatabase(com.mongodb.client.MongoDatabase) Player(org.bukkit.entity.Player) TagStream(de.keyle.knbt.TagStream) Lists(com.google.common.collect.Lists) Configuration(de.Keyle.MyPet.api.Configuration) com.mongodb(com.mongodb) MyPetPlayerImpl(de.Keyle.MyPet.util.player.MyPetPlayerImpl) RepositoryInitException(de.Keyle.MyPet.api.repository.RepositoryInitException) Binary(org.bson.types.Binary) ZipException(java.util.zip.ZipException) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) MyPetApi(de.Keyle.MyPet.MyPetApi) IOException(java.io.IOException) InactiveMyPet(de.Keyle.MyPet.entity.InactiveMyPet) Skilltree(de.Keyle.MyPet.api.skill.skilltree.Skilltree) StoredMyPet(de.Keyle.MyPet.api.entity.StoredMyPet) FindIterable(com.mongodb.client.FindIterable) RepositoryMyPetConverterService(de.Keyle.MyPet.api.util.service.types.RepositoryMyPetConverterService) MyPetType(de.Keyle.MyPet.api.entity.MyPetType) MyPetPlayer(de.Keyle.MyPet.api.player.MyPetPlayer) MyPetVersion(de.Keyle.MyPet.api.MyPetVersion) MongoCollection(com.mongodb.client.MongoCollection) MyPetPlayer(de.Keyle.MyPet.api.player.MyPetPlayer) Document(org.bson.Document) StoredMyPet(de.Keyle.MyPet.api.entity.StoredMyPet)

Example 22 with MongoCollection

use of com.mongodb.client.MongoCollection in project MyPet by xXKeyleXx.

the class MongoDbRepository method updatePlayer.

@SuppressWarnings("unchecked")
public boolean updatePlayer(final MyPetPlayer player) {
    MongoCollection playerCollection = db.getCollection(Configuration.Repository.MongoDB.PREFIX + "players");
    Document filter = new Document("internal_uuid", player.getInternalUUID().toString());
    Document playerDocument = (Document) playerCollection.find(filter).first();
    if (playerDocument != null) {
        setPlayerData(player, playerDocument);
        return playerCollection.replaceOne(filter, playerDocument).getModifiedCount() > 0;
    }
    return false;
}
Also used : MongoCollection(com.mongodb.client.MongoCollection) Document(org.bson.Document)

Example 23 with MongoCollection

use of com.mongodb.client.MongoCollection in project MyPet by xXKeyleXx.

the class MongoDbRepository method addMyPet.

@SuppressWarnings("unchecked")
public void addMyPet(StoredMyPet storedMyPet) {
    MongoCollection petCollection = db.getCollection(Configuration.Repository.MongoDB.PREFIX + "pets");
    Document petDocument = new Document();
    petDocument.append("uuid", storedMyPet.getUUID().toString());
    petDocument.append("owner_uuid", storedMyPet.getOwner().getInternalUUID().toString());
    petDocument.append("exp", storedMyPet.getExp());
    petDocument.append("health", storedMyPet.getHealth());
    petDocument.append("respawn_time", storedMyPet.getRespawnTime());
    petDocument.append("name", storedMyPet.getPetName());
    petDocument.append("type", storedMyPet.getPetType().name());
    petDocument.append("last_used", storedMyPet.getLastUsed());
    petDocument.append("hunger", storedMyPet.getSaturation());
    petDocument.append("world_group", storedMyPet.getWorldGroup());
    petDocument.append("wants_to_spawn", storedMyPet.wantsToRespawn());
    petDocument.append("skilltree", storedMyPet.getSkilltree() != null ? storedMyPet.getSkilltree().getName() : null);
    try {
        petDocument.append("skills", TagStream.writeTag(storedMyPet.getSkillInfo(), true));
        petDocument.append("info", TagStream.writeTag(storedMyPet.getInfo(), true));
    } catch (IOException e) {
        e.printStackTrace();
    }
    petCollection.insertOne(petDocument);
}
Also used : MongoCollection(com.mongodb.client.MongoCollection) IOException(java.io.IOException) Document(org.bson.Document)

Example 24 with MongoCollection

use of com.mongodb.client.MongoCollection in project MyPet by xXKeyleXx.

the class MongoDbRepository method updateInfo.

@SuppressWarnings("unchecked")
private void updateInfo() {
    MongoCollection infoCollection = db.getCollection(Configuration.Repository.MongoDB.PREFIX + "info");
    Document info = (Document) infoCollection.find().first();
    updateInfoDocument(info);
    updateInfoDocument(info);
    infoCollection.replaceOne(new Document("_id", info.getObjectId("_id")), info);
}
Also used : MongoCollection(com.mongodb.client.MongoCollection) Document(org.bson.Document)

Example 25 with MongoCollection

use of com.mongodb.client.MongoCollection 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)

Aggregations

MongoCollection (com.mongodb.client.MongoCollection)53 Document (org.bson.Document)39 MongoDatabase (com.mongodb.client.MongoDatabase)21 List (java.util.List)16 FindIterable (com.mongodb.client.FindIterable)14 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)11 BasicDBObject (com.mongodb.BasicDBObject)10 Set (java.util.Set)9 ObjectId (org.bson.types.ObjectId)9 MongoCursor (com.mongodb.client.MongoCursor)7 IOException (java.io.IOException)7 HashMap (java.util.HashMap)7 HashSet (java.util.HashSet)7 Bson (org.bson.conversions.Bson)7 Map (java.util.Map)6 Collectors (java.util.stream.Collectors)6 BsonDocument (org.bson.BsonDocument)6 Block (com.mongodb.Block)5 UpdateOptions (com.mongodb.client.model.UpdateOptions)5