List of usage examples for com.mongodb Mongo Mongo
Mongo(final MongoClientURI mongoURI, @Nullable final MongoDriverInformation mongoDriverInformation)
From source file:mytubermiserver.mongo.GridFileSystem.java
public InputStream receiveVideo(String fileName) throws UnknownHostException, MongoException, IOException { Mongo mongo = new Mongo(hostAddress, portAddress); DB db = mongo.getDB("MyTube"); // create a "video" namespace GridFS gfsPhoto = new GridFS(db, "video"); // get image file by it's filename GridFSDBFile videoForOutput = gfsPhoto.findOne(fileName); return videoForOutput.getInputStream(); }
From source file:mytubermiserver.mongo.GridFileSystem.java
public void RemoveVideo(String fileName) throws UnknownHostException, MongoException, IOException { Mongo mongo = new Mongo(hostAddress, portAddress); DB db = mongo.getDB("MyTube"); // create a "video" namespace GridFS gfsVideo = new GridFS(db, "video"); // remove the image file from mongoDB gfsVideo.remove(fileName);//ww w . j a va 2s . c o m }
From source file:net.autosauler.ballance.server.mongodb.Database.java
License:Apache License
/** * Inits the connection./*from ww w . jav a2s. com*/ * * @throws UnknownHostException * the unknown host exception * @throws MongoException * the mongo exception * @throws InterruptedException * the interrupted exception */ private static synchronized void initConnection(String domain) throws UnknownHostException, MongoException, InterruptedException { try { if (mongo == null) { mongo = new Mongo(host, port); } } catch (com.mongodb.MongoInternalException e) { close(); throw (e); } DB db = mongo.getDB("admin"); boolean auth = db.authenticate(adminuser, adminpassword.toCharArray()); if (auth) { List<String> databases = mongo.getDatabaseNames(); db = mongo.getDB(database); if (!databases.contains(database)) { db.addUser(user, password.toCharArray()); } auth = db.authenticate(user, password.toCharArray()); if (auth) { mongodatabase = db; retain(); // check settings and create new collection if not exists GlobalSettings.createDefaultRecords(db); // check users and if none - create admin UserList.createDefaultRecords(db); // check currency values. If none - load today values from cbr Currency.createDefaultRecords(db); release(); } else { close(); } } else { close(); } loadSettings(domain); }
From source file:net.bunselmeyer.mongo.maven.plugin.MigrateMojo.java
License:Apache License
private void runMigrations(List<MigrationDetails> migrations) { if (migrations.isEmpty()) { return;//from w ww . ja v a2 s .c om } MigrationDetails migrationDetails = migrations.get(0); Mongo mongo; try { mongo = new Mongo(migrationDetails.host, Integer.parseInt(port)); } catch (UnknownHostException e) { getLog().error("Failed to connect to " + migrationDetails.host + ":" + port); return; } catch (NumberFormatException e) { getLog().error("Invalid port: " + port); return; } mongo.setWriteConcern(WriteConcern.SAFE); DB db = mongo.getDB(migrationDetails.db); JacksonDBCollection<MigrationVersionDetails, ObjectId> migrationVersionCollection = createMigrationVersionCollection( db); getLog().info("Running migrations. Host: " + migrationDetails.host + ". DB: " + migrationDetails.db); sortMigrationDetails(migrations); Class<? extends Migration> lastMigration = null; try { for (MigrationDetails details : migrations) { lastMigration = details.migration; Migration m = details.migration.newInstance(); MigrationVersionDetails versionDetails = new MigrationVersionDetails(); versionDetails.setMigrationName(details.migration.getName()); versionDetails.setVersion(details.version); if (migrationVersionCollection.getCount(versionDetails) == 0) { m.up(db); db.getLastError().throwOnError(); getLog().info( " " + details.migration.getName() + ", v" + details.version + " migration complete"); versionDetails.setRun(DateTime.now(DateTimeZone.UTC)); migrationVersionCollection.insert(versionDetails); } else { getLog().info( " " + details.migration.getName() + ", v" + details.version + " was already run"); } } } catch (Exception e) { String name = lastMigration != null ? lastMigration.getName() : ""; getLog().info(" FAIL! " + name + " migration error", e); } finally { mongo.close(); } }
From source file:net.cit.tetrad.dao.management.impl.ManagementDaoImpl.java
License:Open Source License
/** * mongo ping ?/*ww w.j a v a2 s . c o m*/ */ public String mongoExistCheck(String ip, int port, String userStr, String passwdStr, String isExistMongo) { Map<String, Object> resultMap = new HashMap<String, Object>(); try { mongo = new Mongo(ip, port); DB db = mongo.getDB("admin"); if (!userStr.equals("") && !passwdStr.equals("")) { boolean auth = db.authenticate(userStr, passwdStr.toCharArray()); } CommandResult pingResult = db.command("ping"); resultMap = JasonUtil.getEntryValue(pingResult, "", resultMap); Double resultOkVal = (Double) resultMap.get("ok"); if (resultOkVal != 1.0) { isExistMongo = "3"; } else { try { mongo.slaveOk(); } catch (Exception e) { } CommandResult commandResult = db.command("serverStatus"); resultMap = JasonUtil.getEntryValue(commandResult, "", resultMap); resultOkVal = (Double) resultMap.get("ok"); if (resultOkVal != 1.0) isExistMongo = "4"; } } catch (Exception e) { isExistMongo = "3"; } finally { if (mongo != null) mongo.close(); } return isExistMongo; }
From source file:net.cit.tetrad.data.convert.DataConvertThread.java
License:Open Source License
public DataConvertThread(String host, String port, String database, String startDate) { Mongo mongo;// w ww . ja va2 s . c o m try { mongo = new Mongo(host, Integer.parseInt(port)); this.mongodatasource = new DBDataSource(mongo, database); this.START_DATE = DateUtil.dateformat(startDate, "yyyyMMdd"); } catch (Exception e) { logger.error(e, e); } }
From source file:net.cit.tetrad.resource.ManagementResource.java
License:Open Source License
/** * mongos? ? ?? //from w w w . java2 s .co m * @param request * @param response * @throws Exception */ @RequestMapping("/mongosResearch.do") public void mongosResearch(HttpServletRequest request, HttpServletResponse response, CommonDto commDto) throws Exception { String authUser = Utility.isNull(commDto.getAuthUser()); String authPasswd = Utility.isNull(commDto.getAuthPasswd()); String tempIp = Utility.isNull(commDto.getIp()); boolean loopbackCheck = commDto.isLoopbackCheck(); boolean authCheck = false; Mongo mongo = null; List<Map<String, Object>> resultLst = new ArrayList<Map<String, Object>>(); boolean auth = false; DB db; try { PersonJson result = new PersonJson(); if (authUser != "" && authPasswd != "") authCheck = true; List<Object> readMongoShards = new ArrayList<Object>(); List<Object> readMongos = new ArrayList<Object>(); Object readConfigDb = null; mongo = new Mongo(commDto.getIp(), Integer.parseInt(commDto.getPort())); if (authCheck) { db = mongo.getDB("admin"); auth = db.authenticate(authUser, authPasswd.toCharArray()); } readMongos = mongoStatusToMonitor.readMongoShards(mongo, "mongos", "config"); readMongoShards = mongoStatusToMonitor.readMongoShards(mongo, "shards", "config"); readConfigDb = mongoStatusToMonitor.readMongoStatus(mongo, new Device(), "getCmdLineOpts") .get("parsed_configdb"); mongo.close(); //mongos int mongoIdNum = 0; for (Object mongosObj : readMongos) { mongoIdNum++; Map<String, Object> statusMap = (Map<String, Object>) mongosObj; String[] splitName = ((String) statusMap.get("_id")).split(":"); boolean isExistCheck = false; if (isExistDeviceIpPort(splitName[0], splitName[1]) != null) isExistCheck = true; statusMap.put("isExistCheck", isExistCheck); statusMap.put("ipStr", splitName[0]); statusMap.put("portStr", splitName[1]); statusMap.put("groupNameStr", "mongos_grp"); statusMap.put("uidStr", "mongos" + "_" + mongoIdNum + "_" + splitName[1]); statusMap.put("typeStr", "mongos"); resultLst.add(statusMap); } // mongod for (Object shardObj : readMongoShards) { Map<String, Object> shardMap = (Map<String, Object>) shardObj; String[] host = ((String) shardMap.get("host")).split("/"); String[] hostLst = host[1].split(","); String[] ipPortSplit = hostLst[0].split(":"); if (ipPortSplit[0].equals("127.0.0.1") || ipPortSplit[0].equals("localhost")) { ipPortSplit[0] = tempIp; } mongo = new Mongo(ipPortSplit[0], Integer.parseInt(ipPortSplit[1])); if (authCheck) { db = mongo.getDB("admin"); auth = db.authenticate(authUser, authPasswd.toCharArray()); } Map<String, Object> readMongoStatus = mongoStatusToMonitor.readMongoStatus(mongo, new Device(), "replSetGetStatus"); mongoIdNum = 0; for (Object status : (List<Object>) readMongoStatus.get("members")) { mongoIdNum++; Map<String, Object> statusMap = (Map<String, Object>) status; String[] splitName = ((String) statusMap.get("name")).split(":"); if (loopbackCheck == true && (splitName[0].equals("127.0.0.1") || splitName[0].equals("localhost"))) { splitName[0] = tempIp; } boolean isExistCheck = false; if (isExistDeviceIpPort(splitName[0], splitName[1]) != null) isExistCheck = true; statusMap.put("isExistCheck", isExistCheck); statusMap.put("ipStr", splitName[0]); statusMap.put("portStr", splitName[1]); statusMap.put("groupNameStr", readMongoStatus.get("set")); statusMap.put("uidStr", readMongoStatus.get("set") + "_" + mongoIdNum + "_" + statusMap.get("stateStr")); statusMap.put("typeStr", "mongod"); resultLst.add(statusMap); } mongo.close(); } //config mongoIdNum = 0; for (String configStr : ((String) readConfigDb).split(",")) { mongoIdNum++; Map<String, Object> statusMap = new HashMap<String, Object>(); String[] splitName = configStr.split(":"); if (loopbackCheck == true && (splitName[0].equals("127.0.0.1") || splitName[0].equals("localhost"))) { splitName[0] = tempIp; } boolean isExistCheck = false; if (isExistDeviceIpPort(splitName[0], splitName[1]) != null) isExistCheck = true; statusMap.put("isExistCheck", isExistCheck); statusMap.put("ipStr", splitName[0]); statusMap.put("portStr", splitName[1]); statusMap.put("groupNameStr", "config_grp"); statusMap.put("uidStr", "config" + "_" + mongoIdNum + "_" + splitName[1]); statusMap.put("typeStr", "config"); resultLst.add(statusMap); } result.setAaData(resultLst); JSONObject jsonObject = JSONObject.fromObject(result); Writer writer = setResponse(response).getWriter(); writer.write(jsonObject.toString()); writer.flush(); } catch (Exception e) { e.printStackTrace(); mongo.close(); } log.debug("end - mongosResearch()"); }
From source file:net.coreapi.mongo.documents.ManagedMongoDriver.java
License:Apache License
private Mongo createMongo() { try {// w w w . j a v a 2 s. co m mongo = new Mongo("198.101.202.204", 27017); } catch (UnknownHostException e) { // NOP } return mongo; }
From source file:NexT.db.mongo.MongoWrapper.java
License:GNU General Public License
public MongoWrapper(String user, String pass, String database, String host, int port) throws DBException { super(user, pass, database, host, port); try {/*from w ww. j av a2s.c om*/ LOG.log(Level.INFO, "[MongoDB] Connecting."); client = new Mongo(host, port); db = client.getDB(database); if (user != null && pass != null) { if (!db.authenticate(user, pass.toCharArray())) { LOG.log(Level.SEVERE, "[MongoDB] Authentication with user " + user + " failed!"); throw new MongoException("Failed to authenticate"); } else { LOG.log(Level.INFO, "[MongoDB] Authenticaton with user " + user + " successful."); } } MongoWrapper.INSTANCE = this; } catch (UnknownHostException ex) { LOG.log(Level.SEVERE, "[MongoDB] Failed to start connection.", ex); throw new MongoException("Failed to start connection", ex); } }
From source file:nl.knaw.huygens.timbuctoo.storage.mongo.MongoDB.java
License:Open Source License
@Inject public MongoDB(Configuration config) throws UnknownHostException { MongoOptions options = new MongoOptions(); options.safe = true;/*from w ww .j a v a2 s .co m*/ String host = config.getSetting("database.host", "localhost"); int port = config.getIntSetting("database.port", 27017); mongo = new Mongo(new ServerAddress(host, port), options); String dbName = config.getSetting("database.name"); db = mongo.getDB(dbName); String user = config.getSetting("database.user"); if (!user.isEmpty()) { String password = config.getSetting("database.password"); db.authenticate(user, password.toCharArray()); } }