List of usage examples for com.mongodb MongoClient getDB
@Deprecated public DB getDB(final String dbName)
From source file:mypackage.DownloadDoc.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String getDBName = request.getParameter("db"); String getCollName = request.getParameter("coll"); String getDocName = request.getParameter("doc"); // out.print(getCollName+getDBName+getDocName); MongoClient mongoClient = new MongoClient("localhost", 27017); DB mongoDatabase = mongoClient.getDB(getDBName); DBCollection coll = mongoDatabase.getCollection(getCollName); BasicDBObject basicDBObject = new BasicDBObject(); basicDBObject.put("name", getDocName); DBCursor cursor = coll.find(basicDBObject); JSONObject jSONObject = new JSONObject(); JSONArray jSONArray = new JSONArray(); while (cursor.hasNext()) { jSONArray.put(cursor.next()); }/*from www .ja v a 2s. c o m*/ String filename = getDBName + "_" + getCollName + "_" + getDocName + ".json"; jSONObject.put(getCollName, jSONArray); File file = checkExist("mongodoc.json"); FileWriter fileWriter = new FileWriter(file); fileWriter.write(jSONObject.toString()); fileWriter.flush(); fileWriter.close(); response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\""); FileInputStream fis = new FileInputStream(dir + "\\" + "mongodoc.json"); int i; while ((i = fis.read()) != -1) { out.write(i); } fis.close(); out.close(); } catch (JSONException ex) { Logger.getLogger(DownloadDoc.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:mypackage.GetDatabase.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try {/* www . ja va2s. co m*/ MongoClient mongoClient = new MongoClient("localhost", 27017); HttpSession httpSession = request.getSession(false); DB db = mongoClient.getDB("mydb"); DBCollection coll = db.getCollection(httpSession.getAttribute("uname") + "DB"); JSONObject jSONObject = new JSONObject(); JSONObject jSONObject1 = new JSONObject(); JSONArray jSONArray = new JSONArray(); DBCursor cursor = coll.find(); int i = 0; while (cursor.hasNext()) { jSONArray.put(cursor.next()); i++; } jSONObject.put("db", jSONArray); jSONObject.put("counter", i); out.println(jSONObject); } catch (Exception e) { } }
From source file:mypackage.Login.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String getUname = request.getParameter("uname"); String getPass = request.getParameter("upass"); MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("mydb"); DBCollection coll = db.getCollection("ulogin"); DBObject bObject = new BasicDBObject(); bObject.put(getUname, getPass);/*from ww w . ja va2s . com*/ DBCursor bCursor = coll.find(bObject); int count = bCursor.count(); if (count == 1) { HttpSession httpSession = request.getSession(true); httpSession.setAttribute("uname", getUname); if (!collectionExists(getUname + "DB", db)) { db.createCollection(getUname + "DB", bObject); } out.print("true"); } else { out.print("false"); } } }
From source file:mypackage.ManupulateData.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String ukey = request.getParameter("ukey"); String docname = request.getParameter("doc"); String db = request.getParameter("db"); String coll = request.getParameter("coll"); MongoClient mongoClient = new MongoClient("localhost", 27017); DB mongoDatabase = mongoClient.getDB(db); DBCollection dbcoll = mongoDatabase.getCollection(coll); if (ukey.equals("Update Document")) { String key = request.getParameter("dockey"); String value = request.getParameter("docval"); BasicDBObject basicDBObject = new BasicDBObject(); basicDBObject.append("$set", new BasicDBObject().append(key, value)); BasicDBObject serchQuery = new BasicDBObject("name", docname); dbcoll.update(serchQuery, basicDBObject); out.print("true"); }/*from w ww . j a v a 2 s. com*/ if (ukey.equals("New Document")) { BasicDBObject bObject = new BasicDBObject("name", docname); dbcoll.insert(bObject); out.print("true"); } } }
From source file:mypackage.ManupulateMongo.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String respective = request.getParameter("respective"); String db = request.getParameter("dbname"); String coll = request.getParameter("collname"); String sb = respective;//w w w. ja v a 2 s.c o m int index = sb.indexOf(";"); int length = respective.length(); String key = sb.substring(index + 1, length); HttpSession session = request.getSession(false); MongoClient mongoClient = new MongoClient("localhost", 27017); if (key.equals("db")) { String dbname = respective.substring(0, index); String coll_personal = session.getAttribute("uname") + "DB"; DB mongodb = mongoClient.getDB(dbname); DB mongodb_personal = mongoClient.getDB("mydb"); mongodb.dropDatabase(); DBCollection dBCollection = mongodb_personal.getCollection(coll_personal); BasicDBObject query = new BasicDBObject(); query.put("kapil", dbname); dBCollection.remove(query); out.print("true"); } if (key.equals("coll")) { String collname = respective.substring(0, index); DB mongodb = mongoClient.getDB(db); DBCollection dBCollection = mongodb.getCollection(collname); dBCollection.drop(); out.print("true"); } if (key.equals("doc")) { String docname = respective.substring(0, index); DB mongodb = mongoClient.getDB(db); DBCollection dBCollection = mongodb.getCollection(coll); BasicDBObject query = new BasicDBObject(); query.put("name", docname); dBCollection.remove(query); out.print("true"); } } }
From source file:net.bluemix.todo.store.ToDoStoreFactory.java
License:Open Source License
private static DBCollection getCollection(MongoServiceInfo info) throws ToDoStoreException { MongoClient client; try {// w w w.j av a2 s .com client = new MongoClient(info.getHost(), info.getPort()); DB db = client.getDB(info.getDatabase()); boolean auth = db.authenticate(info.getUserName(), info.getPassword().toCharArray()); if (!auth) { throw new ToDoStoreException("Could not authenticate to Mongo DB."); } return db.getCollection("todos"); } catch (Exception e) { throw new ToDoStoreException("Error creating Mongo DB client.", e); } }
From source file:net.hydromatic.optiq.impl.mongodb.MongoSchema.java
License:Apache License
/** * Creates a MongoDB schema.// w w w . ja va 2s .co m * * @param host Mongo host, e.g. "localhost" * @param database Mongo database name, e.g. "foodmart" */ public MongoSchema(String host, String database) { super(); try { MongoClient mongo = new MongoClient(host); this.mongoDb = mongo.getDB(database); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:net.jimj.automaton.Main.java
License:Open Source License
public static void main(String[] args) { try {//from w w w. j a v a 2 s .c om LogManager.getLogManager() .readConfiguration(Bot.getConfigAsStream("bot.logConfig", "/META-INF/logging.properties")); MongoClient client = new MongoClient(); DB db = client.getDB(DATABASE_NAME); Bot bot = new Bot(db); bot.go(); } catch (Exception e) { System.err.println("The bot is dead."); e.printStackTrace(System.err); } }
From source file:net.tbnr.util.player.TPlayerManager.java
License:Open Source License
public TPlayerManager(AuthenticationDetails details) { TPlayerManager.instance = this; Plugin gearz = Bukkit.getPluginManager().getPlugin("Gearz"); Logger logger;//from w w w.j a v a2 s.c om if (gearz != null) { logger = gearz.getLogger(); if (!gearz.getConfig().getBoolean("database.enable", true)) { return; } } else { logger = Bukkit.getLogger(); } MongoClient databaseClient; try { databaseClient = details.getClient(); logger.info("Attempting a connection to the MongoDB!"); } catch (UnknownHostException e) { e.printStackTrace(); logger.severe("Failed to connect!"); return; } if (details.getDatabase() == null || details.getPlayerCollection() == null) { logger.severe("Cannot continue, data is null for connection!"); return; } this.database = databaseClient.getDB(details.getDatabase()); if (this.database == null) { logger.severe("Failed to connect!"); return; } this.collection = this.database.getCollection(details.getPlayerCollection()); logger.info("Connected to MongoDB!"); TCooldownManager.database = database; }
From source file:no.asgari.civilization.server.application.CivilizationApplication.java
License:Apache License
@Override public void run(CivilizationConfiguration configuration, Environment environment) throws Exception { DB db;/*from w w w . j ava 2s . co m*/ MongoClient mongo; if (!Strings.isNullOrEmpty(configuration.mongodbUser) && !Strings.isNullOrEmpty(configuration.mongodbPassword)) { MongoClientURI clientURI = new MongoClientURI("mongodb://" + configuration.mongodbUser + ":" + configuration.mongodbPassword + "@" + configuration.mongohost + ":" + configuration.mongoport + "/" + configuration.mongodb); mongo = new MongoClient(clientURI); db = mongo.getDB(clientURI.getDatabase()); } else { mongo = new MongoClient(configuration.mongohost, configuration.mongoport); db = mongo.getDB(configuration.mongodb); } MongoManaged mongoManaged = new MongoManaged(mongo); environment.lifecycle().manage(mongoManaged); JacksonDBCollection<Player, String> playerCollection = JacksonDBCollection .wrap(db.getCollection(Player.COL_NAME), Player.class, String.class); JacksonDBCollection<PBF, String> pbfCollection = JacksonDBCollection.wrap(db.getCollection(PBF.COL_NAME), PBF.class, String.class); JacksonDBCollection<Chat, String> chatCollection = JacksonDBCollection.wrap(db.getCollection(Chat.COL_NAME), Chat.class, String.class); createUniqueIndexForPlayer(playerCollection); createUsernameCache(playerCollection); //createUniqueIndexForPBF(pbfCollection); createIndexForChat(chatCollection); //createItemCache(); //TODO Have to rewrite the code to make it work, right now everyone gets same number and same draws //healtcheck environment.healthChecks().register("MongoHealthCheck", new MongoHealthCheck(mongo)); //Resources environment.jersey().register(new GameResource(db)); environment.jersey().register(new AuthResource(db)); environment.jersey().register(new PlayerResource(db)); environment.jersey().register(new DrawResource(db)); environment.jersey().register(new AdminResource(db)); //Authenticator CachingAuthenticator<BasicCredentials, Player> cachingAuthenticator = new CachingAuthenticator<>( new MetricRegistry(), new CivAuthenticator(db), CacheBuilderSpec.parse("expireAfterWrite=120m")); //Authentication binder Binder authBinder = AuthFactory .binder(new BasicAuthFactory<>(cachingAuthenticator, "civilization", Player.class)); //Authentication environment.jersey().register(authBinder); // Configure CORS parameters FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORSFilter", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, environment.getApplicationContext().getContextPath() + "api/*"); filter.setInitParameter(ALLOWED_METHODS_PARAM, "GET,PUT,POST,OPTIONS,DELETE"); filter.setInitParameter(ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,authorization"); filter.setInitParameter(ALLOW_CREDENTIALS_PARAM, "true"); filter.setInitParameter(EXPOSED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location,Accept-Content-Encoding"); }