List of usage examples for com.mongodb Mongo Mongo
Mongo(final MongoClientURI mongoURI, @Nullable final MongoDriverInformation mongoDriverInformation)
From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java
License:Apache License
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {/*from w w w . j a v a2 s . co m*/ getLog().info("Skipping mongodb: mongodb.skip==true"); return; } if (installation == null) { getLog().info("Using mongod from PATH"); } else { getLog().info("Using mongod installed in " + installation); } getLog().info("Using database root of " + databaseRoot); final Logger mongoLogger = Logger.getLogger("com.mongodb"); Level mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 50; opts.socketTimeout = 50; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance with the following databases " + databaseNames); } catch (MongoException.Network e) { // fine... no instance running } catch (MongoException e) { throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance"); } catch (UnknownHostException e) { // ignore... localhost is always known! } } finally { mongoLogger.setLevel(mongoLevel); } CommandLine commandLine = null; if (installation != null && installation.isDirectory()) { File bin = new File(installation, "bin"); File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); if (exe.isFile()) { commandLine = new CommandLine(exe); } else { throw new MojoExecutionException("Could not find mongo executables in specified installation: " + installation + " expected to find " + exe + " but it does not exist."); } } if (commandLine == null) { commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); } if (databaseRoot.isFile()) { throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory"); } if (databaseRoot.isDirectory() && cleanDatabaseRoot) { getLog().info("Cleaning database root directory: " + databaseRoot); try { FileUtils.deleteDirectory(databaseRoot); } catch (IOException e) { throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e); } } if (!databaseRoot.isDirectory()) { getLog().debug("Creating database root directory: " + databaseRoot); if (!databaseRoot.mkdirs()) { throw new MojoExecutionException("Could not create database root directory " + databaseRoot); } } if (!verbose) { commandLine.addArgument("--quiet"); } commandLine.addArgument("--logpath"); commandLine.addArgument(logPath.getAbsolutePath()); if (logAppend) { commandLine.addArgument("--logappend"); } commandLine.addArgument(auth ? "--auth" : "--noauth"); commandLine.addArgument("--port"); try { // this is a hack to force mongo to use a project property // that we are randomly setting at run-time (reserve-network-port) port = Integer.parseInt(project.getProperties().getProperty("mongodb.port")); } catch (NumberFormatException e) { // no or bad project property } commandLine.addArgument(Integer.toString(port)); commandLine.addArgument("--dbpath"); commandLine.addArgument(databaseRoot.getAbsolutePath()); if (additionalArguments != null) { for (String aa : additionalArguments) { commandLine.addArgument(aa); } } Executor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(databaseRoot); ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer()); exec.setProcessDestroyer(processObserver); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); getLog().info("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr)); try { exec.execute(commandLine, execHandler); getLog().info("Waiting for MongoDB to start..."); long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120); mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) { MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 250; opts.socketTimeout = 250; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); getLog().info("MongoDb started."); getLog().info("Databases: " + databaseNames); } catch (MongoException.Network e) { // ignore, wait and try again try { Thread.sleep(50); } catch (InterruptedException e1) { // ignore } continue; } catch (MongoException e) { getLog().info("MongoDb started."); getLog().info("Unable to list databases due to " + e.getMessage()); } break; } } finally { mongoLogger.setLevel(mongoLevel); } if (execHandler.hasResult()) { ExecuteException exception = execHandler.getException(); if (exception != null) { throw new MojoFailureException(exception.getMessage(), exception); } throw new MojoFailureException( "Command " + commandLine + " exited with exit code " + execHandler.getExitValue()); } Map pluginContext = session.getPluginContext(getPluginDescriptor(), project); pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:com.hangum.tadpole.mongodb.core.connection.MongoConnectionManager.java
License:Open Source License
/** * /*w ww .j av a 2s .c o m*/ * @param userDB * @return * @throws Exception */ public static DB getInstance(UserDBDAO userDB) throws MongoDBNotFoundException, Exception { DB db = null; synchronized (dbManager) { try { String searchKey = getKey(userDB); Mongo mongoDB = dbManager.get(searchKey); if (mongoDB == null) { final MongoOptions options = new MongoOptions(); options.connectionsPerHost = 20; options.threadsAllowedToBlockForConnectionMultiplier = 5; options.maxWaitTime = 120000; options.autoConnectRetry = false; options.safe = true; String strReplcaSet = userDB.getExt1(); if (strReplcaSet == null | "".equals(strReplcaSet)) { mongoDB = new Mongo(new DBAddress(userDB.getUrl()), options); } else { List<ServerAddress> listServerList = new ArrayList<ServerAddress>(); listServerList.add(new ServerAddress(userDB.getHost(), Integer.parseInt(userDB.getPort()))); String[] urls = StringUtils.split(strReplcaSet, ","); for (String ipPort : urls) { String[] strIpPort = StringUtils.split(ipPort, ":"); listServerList.add(new ServerAddress(strIpPort[0], Integer.parseInt(strIpPort[1]))); } // options.setReadPreference(ReadPreference.primary()); mongoDB = new Mongo(listServerList, options); } // password ?. db = mongoDB.getDB(userDB.getDb()); if (!"".equals(userDB.getUsers())) { //$NON-NLS-1$ // pass change String passwdDecrypt = ""; try { passwdDecrypt = CipherManager.getInstance().decryption(userDB.getPasswd()); } catch (Exception e) { passwdDecrypt = userDB.getPasswd(); } boolean auth = db.authenticate(userDB.getUsers(), passwdDecrypt.toCharArray()); if (!auth) { throw new Exception(Messages.MongoDBConnection_3); } } // // ? ? ? . // // // db . // List<String> listDB = mongoDB.getDatabaseNames(); // boolean isDB = false; // for (String dbName : listDB) if(userDB.getDb().equals(dbName)) isDB = true; // if(!isDB) { // throw new MongoDBNotFoundException(userDB.getDb() + Messages.MongoDBConnection_0); // } try { // ? ? ? ? . db.getCollectionNames(); } catch (Exception e) { logger.error("error", e); throw new MongoDBNotFoundException(userDB.getDb() + " " + e.getMessage());//Messages.MongoDBConnection_0); } // db map? . dbManager.put(searchKey, mongoDB); } else { db = mongoDB.getDB(userDB.getDb()); } } catch (Exception e) { logger.error("mongodb connection error", e); throw e; } } return db; }
From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java
License:Open Source License
/** * create database//from w w w.j a v a2 s . c o m * * @param userDB * @throws Exception */ public static void createDB(UserDBDAO userDB) throws Exception { MongoOptions options = new MongoOptions(); options.connectionsPerHost = 20; Mongo mongo = new Mongo(userDB.getHost(), Integer.parseInt(userDB.getPort())); DB db = mongo.getDB(userDB.getDb()); db.authenticate(userDB.getUsers(), userDB.getPasswd().toCharArray()); // // ? ? ? ?? . // Set<String> listColNames = db.getCollectionNames(); for (String stringColName : listColNames) { } // }
From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java
License:Open Source License
/** * get admin mongodb//from w w w . j a v a 2s . co m * * @param userDB * @return * @throws Exception */ public static DB getAdminMongoDB(UserDBDAO userDB) throws Exception { Mongo mongo = new Mongo(userDB.getHost(), Integer.parseInt(userDB.getPort())); return mongo.getDB("admin"); }
From source file:com.hangum.tadpole.mongodb.core.test.ConAndAuthentication.java
License:Open Source License
/** * mongo db .//from ww w .j av a 2 s .c o m * * @return */ public Mongo connection(String uri, int port) { Mongo m = null; try { m = new Mongo(uri, port); List<String> listDB = m.getDatabaseNames(); for (String dbName : listDB) { System.out.println(dbName); } // authentication(optional) // boolean auth = db.authenticate(myUserName, myPassword); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } return m; }
From source file:com.happy_coding.viralo.mongodb.MongoConnection.java
License:Apache License
/** * the constructor./*from w w w.j a v a 2 s .c om*/ */ private MongoConnection() { logger = LoggerFactory.getLogger(getClass()); String mongoServer = System.getProperty("mongoserver"); String mongoPort = System.getProperty("mongoport"); String mongoDatabase = System.getProperty("mongodatabase"); try { /* * load addresses from properties file */ mongo = new Mongo(mongoServer, new Integer(mongoPort)); database = mongo.getDB(mongoDatabase); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.howbuy.appframework.homo.configure.commons.jdbc.datasource.DriverManagerDataSource.java
License:Apache License
/** * ?MongoDB/*from ww w . java 2 s .c om*/ * @param conn * @return * @throws Exception */ protected DB getConnectionFromDriverManagerMongoDB(Connection conn) throws Exception { String[] dataArray = getConnectionFromStringArr(conn); String[] mongoDBConn = dataArray[1].split(","); Mongo m = new Mongo(mongoDBConn[0], (new Integer(mongoDBConn[1])).intValue()); DB db = m.getDB(mongoDBConn[2]); if (dataArray[2] != null && !dataArray[2].equals("") && dataArray[3] != null && !dataArray[3].equals("")) { char[] pwd = dataArray[3].toCharArray(); db.authenticate(dataArray[2], pwd); } if (mongoDBConn.length > 3 && mongoDBConn[3] != null && !mongoDBConn[3].equals("")) { db = m.getDB(mongoDBConn[3]); } return db; }
From source file:com.ikanow.infinit.e.data_model.store.MongoDbConnection.java
License:Apache License
/** * Class Constructor used to establish the mongo object * //w w w . j av a 2s .c o m * @param server the server location ( example localhost ) * @param port the port number ( example 27017 * @throws MongoException * @throws UnknownHostException */ public MongoDbConnection(String server, int port) throws UnknownHostException, MongoException { this.server = server; this.port = port; mongo = new Mongo(this.server, this.port); }
From source file:com.ikanow.infinit.e.data_model.store.MongoDbConnection.java
License:Apache License
/** * Class Constructor used to establish the mongo object * //from w w w. jav a 2 s . c om * @param server the server location ( example localhost ) * @param port the port number ( example 27017 * @throws MongoException * @throws UnknownHostException */ public MongoDbConnection(PropertiesManager properties) throws UnknownHostException, MongoException { if (null != properties) { this.server = properties.getDatabaseServer(); this.port = properties.getDatabasePort(); } mongo = new Mongo(this.server, this.port); if (null != properties) { if (properties.getDistributeAllDbReadsAcrossSlaves()) { mongo.setReadPreference(ReadPreference.secondaryPreferred()); } } }
From source file:com.ikanow.infinit.e.utility.MongoEntityFeatureTxfer.java
License:Apache License
@SuppressWarnings("unused") private void doUnitTestCode(String sMongoDbHost, String sMongoDbPort, String sElasticHost, String sElasticPort, BasicDBObject query, int nLimit) { Mongo mongoDB = null;//from ww w . j a v a2s . c om ElasticSearchManager elasticManager = null; try { // Initialize the DB: mongoDB = new Mongo(sMongoDbHost, Integer.parseInt(sMongoDbPort)); DBCollection gazDB = mongoDB.getDB("feature").getCollection("entity"); // Initialize the ES (create the index if it doesn't already): // 1. Set-up the entity feature index String indexName = "entity_index"; //TEST: delete the index: // elasticManager = ElasticSearchManager.getIndex(indexName, sElasticHost + ":" + sElasticPort); // elasticManager.deleteMe(); //TEST: create the index // String sMapping = new Gson().toJson(new GazateerPojo.Mapping(), GazateerPojo.Mapping.class); // Builder localSettings = ImmutableSettings.settingsBuilder(); // localSettings.put("number_of_shards", 1).put("number_of_replicas", 0); q // elasticManager = ElasticSearchManager.createIndex // (indexName, false, // sElasticHost + ":" + sElasticPort, // sMapping, localSettings); //TEST: delete the index: // elasticManager.deleteMe(); //TEST: get the index: // elasticManager = ElasticSearchManager.getIndex(indexName, sElasticHost + ":" + sElasticPort); // Now query the DB: DBCursor dbc = null; if (nLimit > 0) { dbc = gazDB.find(query).limit(nLimit); } else { // Everything! dbc = gazDB.find(query); } Type listType = new TypeToken<ArrayList<EntityFeaturePojo>>() { }.getType(); List<EntityFeaturePojo> entities = new Gson().fromJson(dbc.toArray().toString(), listType); //Debug: List<String> entIds = new LinkedList<String>(); // Loop over array and invoke the cleansing function for each one for (EntityFeaturePojo ent : entities) { if (null != ent.getAlias()) { // (some corrupt gazateer entry) //Debug: //System.out.println("entity=" + ent.getGazateerIndex()); //System.out.println("aliases=" + Arrays.toString(ent.getAlias().toArray())); // Insert into the elasticsearch index //Debug: //System.out.println(new Gson().toJson(ent, GazateerPojo.class)); // Handle groups (system group is: "4c927585d591d31d7b37097a") if (null == ent.getCommunityId()) { ent.setCommunityId(new ObjectId("4c927585d591d31d7b37097a")); } //TEST: index documemt // ent.synchronizeWithIndex(); // boolean b = elasticManager.addDocument(ent, ent.getGazateerIndex(), true); //TEST: remove document //b = elasticManager.removeDocument(ent.getGazateerIndex()); //TEST: (part of get, bulk add/delete) entIds.add(ent.getIndex()); // Debug: // if (!b) { // System.out.println("Didn't add " + ent.getGazateerIndex()); // } } } // End loop over entities //TEST: bulk delete //elasticManager.bulkAddDocuments(entities, "index", null); //elasticManager.bulkDeleteDocuments(entIds); //TEST: get document // elasticManager.getRawClient().admin().indices().refresh(Requests.refreshRequest(indexName)).actionGet(); // for (String id: entIds) { // Map<String, GetField> results = elasticManager.getDocument(id,"doccount", "disambiguated_name"); // System.out.println(id + ": " + results.get("doccount").values().get(0) + " , " + results.get("disambiguated_name").values().get(0)); // } //TEST: search // elasticManager.getRawClient().admin().indices().refresh(Requests.refreshRequest(indexName)).actionGet(); // SearchRequestBuilder searchOptions = elasticManager.getSearchOptions(); // XContentQueryBuilder queryObj = QueryBuilders.matchAllQuery(); // searchOptions.addSort("doccount", SortOrder.DESC); // searchOptions.addFields("doccount", "type"); // SearchResponse rsp = elasticManager.doQuery(queryObj, searchOptions); // SearchHit[] docs = rsp.getHits().getHits(); // for (SearchHit hit: docs) { // String id = hit.getId(); // Long doccount = (Long) hit.field("doccount").value(); // String type = (String) hit.field("type").value(); // System.out.println(id + ": " + doccount + ", " + type); // } } catch (NumberFormatException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } finally { if (null != mongoDB) { mongoDB.close(); } if (null != elasticManager) { //NB not sure when exactly to call this - probably can just not bother? //elasticManager.getRawClient().close(); } } }