List of usage examples for com.mongodb DBCollection findOne
@Nullable
public DBObject findOne()
From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java
License:Apache License
/** * Return a list of custom "lastErrorModes" (if any) defined in the replica set configuration object on the server. * These can be used as the "w" setting for the write concern in addition to the standard "w" values of <number> or * "majority".//from w w w . j av a 2 s . c o m * * @return a list of the names of any custom "lastErrorModes" * @throws KettleException * if a problem occurs */ public List<String> getLastErrorModes() throws KettleException { List<String> customLastErrorModes = new ArrayList<String>(); DB local = getDb(LOCAL_DB); if (local != null) { try { DBCollection replset = local.getCollection(REPL_SET_COLLECTION); if (replset != null) { DBObject config = replset.findOne(); extractLastErrorModes(config, customLastErrorModes); } } catch (Exception e) { if (e instanceof KettleException) { throw (KettleException) e; } else { throw new KettleException(e); } } } return customLastErrorModes; }
From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java
License:Apache License
private BasicDBList getRepSetMemberRecords() throws KettleException { BasicDBList setMembers = null;/*from www . j a va 2s . co m*/ try { DB local = getDb(LOCAL_DB); if (local != null) { DBCollection replset = local.getCollection(REPL_SET_COLLECTION); if (replset != null) { DBObject config = replset.findOne(); if (config != null) { Object members = config.get(REPL_SET_MEMBERS); if (members instanceof BasicDBList) { if (((BasicDBList) members).size() == 0) { // log that there are no replica set members defined if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$ } } else { setMembers = (BasicDBList) members; } } else { // log that there are no replica set members defined if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$ } } } else { // log that there are no replica set members defined if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$ } } } else { // log that the replica set collection is not available if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Warning.ReplicaSetCollectionUnavailable")); //$NON-NLS-1$ } } } else { // log that the local database is not available!! if (log != null) { log.logBasic( BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Warning.LocalDBNotAvailable")); //$NON-NLS-1$ } } } catch (Exception ex) { throw new KettleException(ex); } finally { if (getMongo() != null) { getMongo().close(); } } return setMembers; }
From source file:com.hangum.tadpole.erd.core.dnd.TableTransferDropTargetListener.java
License:Open Source License
/** * table? .//w ww . j a v a2 s . co m * * @param strTBName * @return * @throws Exception */ public List<TableColumnDAO> getColumns(String strTBName) throws Exception { if (DBDefine.getDBDefine(userDB.getTypes()) != DBDefine.MONGODB_DEFAULT) { SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB); Map<String, String> param = new HashMap<String, String>(); param.put("db", userDB.getDb()); param.put("table", strTBName); return sqlClient.queryForList("tableColumnList", param); } else if (DBDefine.getDBDefine(userDB.getTypes()) == DBDefine.MONGODB_DEFAULT) { Mongo mongo = new Mongo(new DBAddress(userDB.getUrl())); com.mongodb.DB mongoDB = mongo.getDB(userDB.getDb()); DBCollection coll = mongoDB.getCollection(strTBName); return MongoDBTableColumn.tableColumnInfo(coll.getIndexInfo(), coll.findOne()); } return null; }
From source file:com.hangum.tadpole.erd.core.utils.TadpoleModelUtils.java
License:Open Source License
/** * table? ./*from w ww. j av a 2 s.c o m*/ * * @param strTBName * @return * @throws Exception */ public List<TableColumnDAO> getColumns(String db, String strTBName) throws Exception { if (DBDefine.getDBDefine(userDB.getTypes()) != DBDefine.MONGODB_DEFAULT) { SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB); Map<String, String> param = new HashMap<String, String>(); param.put("db", db); param.put("table", strTBName); return sqlClient.queryForList("tableColumnList", param); } else if (DBDefine.getDBDefine(userDB.getTypes()) == DBDefine.MONGODB_DEFAULT) { Mongo mongo = new Mongo(new DBAddress(userDB.getUrl())); com.mongodb.DB mongoDB = mongo.getDB(userDB.getDb()); DBCollection coll = mongoDB.getCollection(strTBName); return MongoDBTableColumn.tableColumnInfo(coll.getIndexInfo(), coll.findOne()); } return null; }
From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java
License:Open Source License
/** * collection column list// w ww . j av a2s .co m * * @param userDB * @param colName * @return * @throws Exception */ public static List<CollectionFieldDAO> collectionColumn(UserDBDAO userDB, String colName) throws Exception { DB mongoDB = MongoConnectionManager.getInstance(userDB); DBCollection coll = mongoDB.getCollection(colName); return MongoDBTableColumn.tableColumnInfo(coll.getIndexInfo(), coll.findOne()); }
From source file:com.hangum.tadpole.mongodb.core.test.MongoTestReferenceCollection.java
License:Open Source License
/** * @param args// w w w . j a va 2 s .c o m */ public static void main(String[] args) throws Exception { ConAndAuthentication testMongoCls = new ConAndAuthentication(); Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port); DB db = mongo.getDB("test"); DBObject colInformation = (DBObject) JSON.parse("{capped:true, size:100000}"); DBCollection ref1Coll = db.getCollection(REF_1); if (ref1Coll != null) ref1Coll.drop(); ref1Coll = db.createCollection(REF_1, colInformation); DBObject dbObjRef1 = (DBObject) JSON.parse("{ 'name' : 'cho'}");//"{'names': {'First': 'Gonza', 'Last': 'Vieira'}}"); WriteResult wr = ref1Coll.insert(dbObjRef1); DBObject retDBObj = ref1Coll.findOne(); createRef1Collection(db, retDBObj.get("_id")); mongo.close(); }
From source file:com.hangum.tadpole.mongodb.erd.core.dnd.TableTransferDropTargetListener.java
License:Open Source License
/** * table? ./*from w w w. j a v a 2 s .c o m*/ * * @param strTBName * @return * @throws Exception */ public List<CollectionFieldDAO> getColumns(String strTBName) throws Exception { Mongo mongo = new Mongo(new DBAddress(userDB.getUrl())); com.mongodb.DB mongoDB = mongo.getDB(userDB.getDb()); DBCollection coll = mongoDB.getCollection(strTBName); return MongoDBTableColumn.tableColumnInfo(coll.getIndexInfo(), coll.findOne()); }
From source file:com.ikanow.infinit.e.api.knowledge.QueryHandler.java
License:Open Source License
private ResponsePojo getSavedQueryInstead(String storedQueryNameOrId, String[] communityIdStrs, AdvancedQueryPojo query) {/*w w w . j a va 2 s.c o m*/ ResponsePojo rp = null; ObjectId oid = null; BasicDBObject jobQuery = null; try { oid = new ObjectId(storedQueryNameOrId); jobQuery = new BasicDBObject(CustomMapReduceJobPojo._id_, oid); } catch (Exception e) { jobQuery = new BasicDBObject(CustomMapReduceJobPojo.jobtitle_, storedQueryNameOrId); } CustomMapReduceJobPojo savedJob = CustomMapReduceJobPojo .fromDb(DbManager.getCustom().getLookup().findOne(jobQuery), CustomMapReduceJobPojo.class); if (null != savedJob) { // Is this even a saved job? if (null != savedJob.jarURL) { savedJob = null; } } if (null != savedJob) { // Authorization boolean auth = false; String communityIdStrList = Arrays.toString(communityIdStrs); for (ObjectId commId : savedJob.communityIds) { if (communityIdStrList.contains(commId.toString())) { auth = true; break; } } if (!auth) { savedJob = null; } if (null == savedJob) { throw new RuntimeException( "Can't find saved query, or is a custom job not a query, or authorization error"); } // OK go get the results of the job DBCollection coll = DbManager.getCollection(savedJob.getOutputDatabase(), savedJob.outputCollection); BasicDBObject result = (BasicDBObject) coll.findOne(); // (at some point support multiple saved queries) if (null == result) { throw new RuntimeException("Saved query is empty"); } BasicDBObject apiResultToConvert = (BasicDBObject) result.get("value"); if (null == apiResultToConvert) { throw new RuntimeException("Saved query has invalid format"); } rp = ResponsePojo.fromDb(apiResultToConvert); } else if (null != oid) { // Support new user/doc queues SharePojo share = SharePojo.fromDb(DbManager.getSocial().getShare().findOne(jobQuery), SharePojo.class); if ((null == share) || (null == share.getShare()) || (!share.getType().equals(DocumentQueueControlPojo.UserQueue) && !share.getType().equals(DocumentQueueControlPojo.SavedQueryQueue))) { throw new RuntimeException( "Can't find saved query, or is a custom job not a query, or authorization error"); } else { // share.share is a DocumentQueueControlPojo DocumentQueueControlPojo queue = DocumentQueueControlPojo.fromApi(share.getShare(), DocumentQueueControlPojo.class); BasicDBObject docQuery1 = new BasicDBObject(DocumentPojo._id_, new BasicDBObject(DbManager.in_, queue.getQueueList())); BasicDBObject docQuery2 = new BasicDBObject(DocumentPojo.updateId_, new BasicDBObject(DbManager.in_, queue.getQueueList())); BasicDBObject docQuery = new BasicDBObject(DbManager.or_, Arrays.asList(docQuery1, docQuery2)); DBCursor dbc = DbManager.getDocument().getMetadata().find(docQuery).limit(query.score.numAnalyze); ScoringUtils scoreStats = new ScoringUtils(); List<BasicDBObject> docs = null; StatisticsPojo stats = new StatisticsPojo(); stats.setSavedScores(query.output.docs.skip, dbc.count()); try { boolean lockAcquired = true; try { lockAcquired = this.acquireConcurrentAccessLock(); } catch (InterruptedException e) { //(that's fine just carry on) lockAcquired = false; } if (!lockAcquired) { rp.setResponse( new ResponseObject("Query", false, "Query engine busy, please try again later.")); return rp; } scoreStats.setAliasLookupTable(_aliasLookup); docs = scoreStats.calcTFIDFAndFilter(DbManager.getDocument().getMetadata(), dbc, query.score, query.output, stats, false, query.output.docs.skip, query.output.docs.numReturn, communityIdStrs, null, null, null, null, null, null, null, null); } finally { scoreStats.clearAsMuchMemoryAsPossible(); this.releaseConcurrentAccessLock(); } rp = new ResponsePojo(); rp.setResponse(new ResponseObject("Query", true, "Saved Query: " + share.getTitle())); rp.setStats(stats); if ((null != docs) && (docs.size() > 0)) { rp.setData(docs, (BasePojoApiMap<BasicDBObject>) null); } else { // (ensure there's always an empty list) docs = new ArrayList<BasicDBObject>(0); rp.setData(docs, (BasePojoApiMap<BasicDBObject>) null); } } //end if user or saved query queue } return rp; }
From source file:com.ikanow.infinit.e.data_model.utils.MongoTransactionLock.java
License:Apache License
protected synchronized boolean getToken() { DBCollection cachedCollection = _collections.get(); boolean bDefinitelyHaveControl = false; String hostname = null;//from w ww. j av a 2 s . co m String oneUp = null; // 1] Get Lock Object (create one an assert control if it doesn't exist) BasicDBObject lockObj = (BasicDBObject) cachedCollection.findOne(); if (null == lockObj) { // Currently the DB is unlocked hostname = getHostname(); oneUp = Long.toString(1000000L * (new Date().getTime() % 10000)); // (ie a randomish start number) lockObj = new BasicDBObject(id_, _lockId); lockObj.put(hostname_, hostname); lockObj.put(oneUp_, oneUp); lockObj.put(lastUpdated_, new Date()); //logger.debug("Creating a new aggregation lock object: " + lockObj.toString()); try { cachedCollection.insert(lockObj, WriteConcern.SAFE); // (will fail if another harvester gets there first) bDefinitelyHaveControl = true; } catch (Exception e) { // Someone else has created it in the meantime lockObj = (BasicDBObject) cachedCollection.findOne(); } } //TESTED // (So by here lockObj is always non-null) // 2] Do I have control? if (bDefinitelyHaveControl) { _bHaveControl = true; _nLastCheck = 0; } else { hostname = lockObj.getString(hostname_); oneUp = lockObj.getString(oneUp_); _bHaveControl = getHostname().equals(hostname); } // 3] If not, has the lock object been static for >= 1 minute if (!_bHaveControl) { // Don't currently have control long nNow = new Date().getTime(); if (0 == _nLastCheck) { _nLastCheck = nNow; } if ((nNow - _nLastCheck) > 60000) { // re-check every minute if (_savedHostname.equals(hostname) && _savedOneUp.equals(oneUp)) { // Now I have control... //logger.debug("I am taking control from: " + hostname + ", " + oneUp); if (updateToken(true)) { // Try to grab control: _bHaveControl = true; } else { // (else someone else snagged control just carry on) _nLastCheck = 0; // (reset clock again anyway) } } //(if lock has remained static) } //(end if >=1 minutes has passed) } //(end if have don't have control) // 4] Update saved state _savedHostname = hostname; _savedOneUp = oneUp; return _bHaveControl; }
From source file:com.korpacz.testproject.HelloWorldMongoDBSparkFreemarkerStyle.java
public static void main(String... args) throws UnknownHostException { //ssssss/*w w w . j a v a 2 s. co m*/ final Configuration config = new Configuration(); config.setClassForTemplateLoading(HelloWorldSparkFreemarkerStyle.class, "/"); MongoClient client = new MongoClient(new ServerAddress("localhost", 27017)); DB database = client.getDB("test"); final DBCollection collection = database.getCollection("names"); Spark.get("/", new Route() { @Override public Object handle(Request rqst, Response rspns) throws Exception { Template helloTemplete = config.getTemplate("hello.ftl"); StringWriter writter = new StringWriter(); DBObject object = collection.findOne(); helloTemplete.process(object, writter); System.out.println(writter); return writter; } }); }