|
| 1 | +package net.sinender.bungeemsg.pubsub; |
| 2 | + |
| 3 | +import com.mongodb.ConnectionString; |
| 4 | +import com.mongodb.MongoClientSettings; |
| 5 | +import com.mongodb.client.MongoClient; |
| 6 | +import com.mongodb.client.MongoClients; |
| 7 | +import com.mongodb.client.MongoCollection; |
| 8 | +import com.mongodb.client.MongoDatabase; |
| 9 | +import net.sinender.bungeemsg.BungeeMsg; |
| 10 | +import org.bson.Document; |
| 11 | + |
| 12 | +import java.util.ArrayList; |
| 13 | +import java.util.List; |
| 14 | + |
| 15 | +public class MongoDBPS { |
| 16 | + private final MongoCollection<Document> collection; |
| 17 | + private static MongoClient client; |
| 18 | + private static MongoDatabase database; |
| 19 | + |
| 20 | + public MongoDBPS(String collection) { |
| 21 | + this.collection = database.getCollection(collection); |
| 22 | + } |
| 23 | + |
| 24 | + public static void connect() { |
| 25 | + // connect to mongoDB |
| 26 | + BungeeMsg.getInstance().getLogger().info("Connecting to MongoDB..."); |
| 27 | + MongoClientSettings settings = MongoClientSettings.builder() |
| 28 | + .applyConnectionString(new ConnectionString(BungeeMsg.config.getString("mongo.uri"))) |
| 29 | + .applyToSslSettings(x -> x.enabled(BungeeMsg.config.getBoolean("mongo.useSSL"))) |
| 30 | + .build(); |
| 31 | + client = MongoClients.create(settings); |
| 32 | + database = client.getDatabase(BungeeMsg.config.getString("mongo.database")); |
| 33 | + BungeeMsg.getInstance().getLogger().info("Successfully connected to MongoDB!"); |
| 34 | + } |
| 35 | + |
| 36 | + public Document getDocument(String uuid) { |
| 37 | + // get document from mongoDB |
| 38 | + Document query = new Document("key", uuid); |
| 39 | + return collection.find(query).first(); |
| 40 | + } |
| 41 | + |
| 42 | + public List<Document> getDocuments() { |
| 43 | + return collection.find().into(new ArrayList<>()); |
| 44 | + } |
| 45 | + |
| 46 | + public Document getLatestDocument() { |
| 47 | + return collection.find().sort(new Document("_id", -1)).first(); |
| 48 | + } |
| 49 | + |
| 50 | + public void setDocument(String uuid, Document document) { |
| 51 | + // set document in mongoDB |
| 52 | + collection.insertOne(document); |
| 53 | + } |
| 54 | + |
| 55 | + public Document updateDocument(Document document) { |
| 56 | + Document query = new Document("key", document.getString("key")); |
| 57 | + if (collection.find(query).first() == null) { |
| 58 | + collection.insertOne(document); |
| 59 | + } else { |
| 60 | + collection.replaceOne(query, document); |
| 61 | + } |
| 62 | + return document; |
| 63 | + } |
| 64 | +} |
0 commit comments