Java tutorial
/* * Statistician, a custom mongo backed statistic collector for Bukkit * Copyright (C) meggawatts <http://mcme.co> * * This file is part of Statistician. * * Statistician is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Statistician is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Statistician. If not, see <http://www.gnu.org/licenses/>. */ package co.mcme.statistician.database; import co.mcme.statistician.Statistician; import co.mcme.statistician.utilities.StatisticianLogger; import com.mongodb.*; import lombok.Getter; import java.net.UnknownHostException; import java.util.Arrays; public class MongoDBUtil { @Getter private final MongoClient client; @Getter private final DB database; @Getter private DBCollection statsCollection; public MongoDBUtil(String hostname, int port, String username, char[] password, String database, boolean tryAuth, String collection) throws UnknownHostException { if (tryAuth) { this.client = new MongoClient(Arrays.asList(new ServerAddress(hostname, port)), Arrays.asList(MongoCredential.createPlainCredential(username, database, password))); } else { this.client = new MongoClient(Arrays.asList(new ServerAddress(hostname, port))); } this.database = client.getDB(database); if (client != null) { if (!this.database.collectionExists(collection)) { statsCollection = this.database.createCollection(collection, new BasicDBObject()); } else { statsCollection = this.database.getCollection(collection); } } else { StatisticianLogger.severe( "Could not authenticate to '" + hostname + ":" + port + "/" + database + "' disabling plugin."); Statistician.getServerInstance().getPluginManager().disablePlugin(Statistician.getPluginInstance()); } } public void storeReport(StatsReport report) { StatisticianLogger.info("Storing new report"); statsCollection.insert(report.toDBObject()); Statistician.getEventListener().resetStats(); } }