Java 类com.mongodb.DBCursor 实例源码

项目:geeCommerce-Java-Shop-Software-and-PIM    文件:SynonymsGenerator.java   
public void generateFile(String filename) {
    DB db = MongoHelper.mongoMerchantDB();

    DBCollection col = db.getCollection(COLLECTION_SYNONYMS);
    DBCursor cursor = col.find();
    try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)))) {
        while (cursor.hasNext()) {
            DBObject doc = cursor.next();
            String word = doc.get(FIELD_KEY_WORLD) != null ? doc.get(FIELD_KEY_WORLD).toString() : null;
            String synonyms = doc.get(FIELD_KEY_WORLD) != null
                ? StringUtils.join((BasicDBList) doc.get(FIELD_KEY_SYNONYMS), ",") : null;
            if (word != null && synonyms != null) {
                out.println(createLine(word, synonyms));
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("IOException: Current db cursor with id: " + cursor.curr().get("_id"), e);
    }
}
项目:tool.lars    文件:PersistenceBeanBasicSearchTest.java   
/**
 * Test that providing a PaginationOptions object results in the correct skip() and limit()
 * methods being called on the result cursor.
 */
@Test
public void testRetrieveAllAssetsPaginated(final @Mocked DBCollection collection, final @Injectable DBCursor cursor) {

    new Expectations() {
        {

            collection.find((DBObject) withNotNull(), (DBObject) withNull());
            result = cursor;
            cursor.skip(20);
            cursor.limit(10);
        }
    };

    List<AssetFilter> filters = new ArrayList<>();
    filters.add(new AssetFilter("key1", Arrays.asList(new Condition[] { new Condition(Operation.EQUALS, "value1") })));
    PaginationOptions pagination = new PaginationOptions(20, 10);
    createTestBean().retrieveAllAssets(filters, null, pagination, null);
}
项目:elastest-instrumentation-manager    文件:AgentConfigurationRepository.java   
public boolean existConfiguration(String agentId){      
    logger.info("Verifying if agent with agentId = " + agentId + " has a configuration stored in DB");
    System.out.println("Verifying if agent with agentId = " + agentId + " has a configuration stored in DB");
       BasicDBObject query = new BasicDBObject();
       query.put("agentId", agentId);

       DBCursor cursor = getAgentConfigurationTable().find(query);
       if (cursor.hasNext()){
        logger.info("Configuration for agent with agentId = " + agentId + " exists");
        System.out.println("Configuration for agent with agentId = " + agentId + " exists");
        return true;
       }
       else {
        logger.info("Not exists any configuration for an agent with agentId = " + agentId);
        System.out.println("Not exists any configuration for an agent with agentId = " + agentId);
        return false;
       }        
}
项目:elastest-instrumentation-manager    文件:AgentConfigurationRepository.java   
public AgentConfigurationDatabase getAgentConfigurationByAgentId(String agentId){
    System.out.println("Searching agent cfg in DB with agentId = " + agentId);
    logger.info("Searching host in DB with agentId = " + agentId);
    BasicDBObject query = new BasicDBObject();
       query.put("agentId", agentId);

       DBCursor cursor = getAgentConfigurationTable().find(query);
       if (cursor.hasNext()){
        logger.info("Agent cfg exists in DB with agentId = " + agentId);
        return this.toAgentCfgDbObject(cursor.next());
       }
       else {
        logger.info("Agent cfg doesn't exists in DB with agentId = " + agentId);
        System.out.println("Agent cfg doesn't exists in DB with agentId = " + agentId);
        return null;
       }        
}
项目:elastest-instrumentation-manager    文件:AgentConfigurationRepository.java   
public List<AgentConfigurationDatabase> findAll(){
    ArrayList<AgentConfigurationDatabase> agents = null;
    logger.info("Getting all agent cfgs from database...");
       DBCursor cur = getAgentConfigurationTable().find();
       while (cur.hasNext()) {
        if (agents == null) {
            agents = new ArrayList<AgentConfigurationDatabase>();
        }
        agents.add(this.toAgentCfgDbObject(cur.next()));        
       }
       if (agents != null){
        logger.info("Retrieved " + agents.size() + " agent configurations from database");
       }
       else {
        logger.info("Retrieved " + 0 + " agent configurations from database");
       }
    return agents;
}
项目:elastest-instrumentation-manager    文件:AgentRepository.java   
public boolean existHost(String ipAddress){     
    logger.info("Verifying if host with ipAddress = " + ipAddress + " exists");
    System.out.println("Verifying if host with ipAddress = " + ipAddress + " exists");
       BasicDBObject query = new BasicDBObject();
       query.put("host", ipAddress);

       DBCursor cursor = getAgentTable().find(query);
       if (cursor.hasNext()){
        logger.info("Host with ipAddress = " + ipAddress + " exists");
        System.out.println("Host with ipAddress = " + ipAddress + " exists");
        return true;
       }
       else {
        logger.info("Not exists any host with ipAddress = " + ipAddress);
        System.out.println("Not exists any host with ipAddress = " + ipAddress);
        return false;
       }        
}
项目:elastest-instrumentation-manager    文件:AgentRepository.java   
public AgentFull getAgentByIpAddress(String ipAddress){
    logger.info("Searching host in DB with ipAddress = " + ipAddress);
    System.out.println("Searching host in DB with ipAddress = " + ipAddress);
    AgentFull agent = null;

    BasicDBObject query = new BasicDBObject();
       query.put("host", ipAddress);

       DBCursor cursor = getAgentTable().find(query);
       if (cursor.hasNext()){
        agent = new AgentFull();
        agent.setAgentId((String) cursor.next().get("agentId"));
        agent.setHost((String) cursor.curr().get("host"));
        agent.setMonitored((boolean) cursor.curr().get("monitored"));
        agent.setLogstashIp((String) cursor.curr().get("logstashIp"));
        agent.setLogstashPort((String) cursor.curr().get("logstashPort"));
        logger.info("Host finded in DB with ipAddress = " + ipAddress + " with ID " + agent.getAgentId());
        System.out.println("Host finded in DB with ipAddress = " + ipAddress + " with ID " + agent.getAgentId());
       }
       else {
        logger.error("Host doesn't exists in DB with ipAddress = " + ipAddress);
        System.out.println("Host doesn't exists in DB with ipAddress = " + ipAddress);
        return null;
       }        
    return agent;
}
项目:elastest-instrumentation-manager    文件:AgentRepository.java   
public AgentFull getAgentByAgentId(String agentId){
    System.out.println("Searching host in DB with agentId = " + agentId);
    logger.info("Searching host in DB with agentId = " + agentId);
    AgentFull agent = null;
    BasicDBObject query = new BasicDBObject();
       query.put("agentId", agentId);

       DBCursor cursor = getAgentTable().find(query);
       if (cursor.hasNext()){
        agent = new AgentFull();
        agent.setAgentId((String) cursor.next().get("agentId"));
        agent.setHost((String) cursor.curr().get("host"));
        agent.setMonitored((boolean) cursor.curr().get("monitored"));
        agent.setLogstashIp((String) cursor.curr().get("logstashIp"));
        agent.setLogstashPort((String) cursor.curr().get("logstashPort"));
        logger.info("Host finded in DB with agentId = " + agentId + " with ipAddress " + agent.getHost());
        System.out.println("Host finded in DB with agentId = " + agentId + " with ipAddress " + agent.getHost());
       }
       else {
        logger.info("Host doesn't exists in DB with agentId = " + agentId);
        System.out.println("Host doesn't exists in DB with agentId = " + agentId);
        return null;
       }        
    return agent;
}
项目:elastest-instrumentation-manager    文件:AgentRepository.java   
public List<AgentFull> findAll(){
    ArrayList<AgentFull> agents = null;
    logger.info("Getting all agents from database...");
       DBCursor cur = getAgentTable().find();
       AgentFull agent = null;
       while (cur.hasNext()) {
        if (agents == null) {
            agents = new ArrayList<AgentFull>();
        }
        agent = new AgentFull();
        agent.setAgentId((String) cur.next().get("agentId"));
        agent.setHost((String) cur.curr().get("host") );
        agent.setMonitored((boolean) cur.curr().get("monitored"));
        agents.add(agent);      
       }
       if (agents != null){
        logger.info("Retrieved " + agents.size() + " agents from database");
       }
       else {
        logger.info("Retrieved " + 0 + " agents from database");
       }
    return agents;
}
项目:spring-data-examples    文件:AdvancedIntegrationTests.java   
/**
 * This test demonstrates usage of {@code $comment} {@link Meta} usage. One can also enable profiling using
 * {@code --profile=2} when starting {@literal mongod}.
 * <p>
 * <strong>NOTE</strong>: Requires MongoDB v. 2.6.4+
 */
@Test
public void findByFirstnameUsingMetaAttributes() {

    // execute derived finder method just to get the comment in the profile log
    repository.findByFirstname(dave.getFirstname());

    // execute another finder without meta attributes that should not be picked up
    repository.findByLastname(dave.getLastname(), new Sort("firstname"));

    DBCursor cursor = operations.getCollection(ApplicationConfiguration.SYSTEM_PROFILE_DB)
            .find(new BasicDBObject("query.$comment", AdvancedRepository.META_COMMENT));

    while (cursor.hasNext()) {

        DBObject dbo = cursor.next();
        DBObject query = (DBObject) dbo.get("query");

        assertThat(query.containsField("$comment"), is(true));
    }
}
项目:sample-acmegifts    文件:OccasionResource.java   
/** Read the occasions that are stored in the database and schedule them to run. */
@PostConstruct
public void afterCreate() {
  String method = "afterCreate";
  logger.entering(clazz, method);

  orchestrator.setOccasionResource(this);

  DBCollection occasions = getCollection();
  DBCursor cursor = occasions.find();
  while (cursor.hasNext()) {
    DBObject dbOccasion = cursor.next();
    Occasion occasion = new Occasion(dbOccasion);
    try {
      // TODO: There was a comment here about how we should mark the event as
      //       popped in the database, which will have different meaning for
      //       one-time or interval occasions.  Need to re-visit this.
      orchestrator.scheduleOccasion(occasion);
    } catch (Throwable t) {
      logger.log(Level.WARNING, "Could not schedule occasion at startup", t);
    }
  }

  logger.exiting(clazz, method);
}
项目:loom    文件:MongoDbConnection.java   
public List<String> getAllIds(final Map<String, Object> conditions) {
    DBObject query = new BasicDBObject(conditions);
    DBCursor cursor = coll.find(query);

    List<String> ids = new ArrayList<String>(cursor.count());
    for (DBObject o : cursor) {
        ids.add(o.get("_id").toString());
    }

    return ids;
}
项目:extension-mongodb    文件:MongoDBCache.java   
public CacheEntry getCacheEntry(String key, CacheEntry defaultValue) {
    DBCursor cur = null;
    DBCollection coll = getCollection();
    BasicDBObject query = new BasicDBObject("key", key.toLowerCase());

    // be sure to flush
    flushInvalid(coll,query);

    cur = coll.find(query);

    if (cur.count() > 0) {
        hits++;
        MongoDBCacheDocument doc = new MongoDBCacheDocument((BasicDBObject) cur.next());
        doc.addHit();
        //update the statistic and persist
        save(doc,0);
        return new MongoDBCacheEntry(doc);
    }
    misses++;
    return defaultValue;
}
项目:extension-mongodb    文件:MongoDBCache.java   
@Override
public int remove(CacheKeyFilter filter) {
    DBCursor cur = qAll_Keys();
    int counter = 0;

    while (cur.hasNext()) {
        DBObject obj = cur.next();
        String key = (String) obj.get("key");
        if (filter.accept(key)) {
            doDelete((BasicDBObject) obj);
            counter++;
        }
    }

    return counter;
}
项目:extension-mongodb    文件:MongoDBCache.java   
@Override
public int remove(CacheEntryFilter filter) {
    DBCursor cur = qAll();
    int counter = 0;

    while (cur.hasNext()) {
        BasicDBObject obj = (BasicDBObject) cur.next();
        MongoDBCacheEntry entry = new MongoDBCacheEntry(new MongoDBCacheDocument(obj));
        if (filter.accept(entry)) {
            doDelete(obj);
            counter++;
        }
    }

    return counter;
}
项目:extension-mongodb    文件:MongoDBCache.java   
@Override
public List<Object> values(CacheKeyFilter filter) {
    DBCursor cur = qAll_Keys_Values();
    List<Object> result = new ArrayList<Object>();

    while (cur.hasNext()) {
        BasicDBObject obj = (BasicDBObject) cur.next();
        MongoDBCacheDocument doc = new MongoDBCacheDocument(obj);

        if (filter.accept(doc.getKey())) {
            try {
                result.add(MongoDBCacheDocument.getValue(obj));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

    return result;
}
项目:extension-mongodb    文件:MongoDBCache.java   
@Override
public List<Object> values(CacheEntryFilter filter) {
    DBCursor cur = qAll_Keys_Values();
    List<Object> result = new ArrayList<Object>();

    while (cur.hasNext()) {
        BasicDBObject obj = (BasicDBObject) cur.next();
        MongoDBCacheEntry entry = new MongoDBCacheEntry(new MongoDBCacheDocument(obj));

        if (filter.accept(entry)) {
            try {
                result.add(MongoDBCacheDocument.getValue(obj));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

    return result;
}
项目:extension-mongodb    文件:DBCollectionImpl.java   
@Override
public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) {
    DBCursor cursor = coll.find();
    Iterator<DBObject> it = cursor.iterator();
    DumpTable table = new DumpTable("struct","#339933","#8e714e","#000000");
    table.setTitle("DBCollection");

    maxlevel--;
    DBObject obj;
    while(it.hasNext()) {
        obj = it.next();
        table.appendRow(0,
                __toDumpData(toCFML(obj), pageContext,maxlevel,dp)
            );
    }
    return table;
}
项目:JerseyRestBoilerplate    文件:EmployeeDao.java   
public StringBuilder getMongoDBData() {
    DBCollection collection = MongoUtil.getCollection("some_db",
            "some_collection");

    DBCursor cursor = collection.find();
    StringBuilder data = new StringBuilder();

    long startTime = System.currentTimeMillis();
    while (cursor.hasNext()) {
        data.append(cursor.next());
    }
    long endTime = System.currentTimeMillis();

    System.out.println("Time taken : " + (endTime - startTime));

    return data;
}
项目:mongodb-aggregate-query-support    文件:AggregateOutTest.java   
@Test
public void outMustPlaceRepositoryObjectsInDifferentRepositoryIfOtherQueryAnnotationsArePresent() {
  String randomStr = randomAlphabetic(10);
  TestAggregateAnnotation2FieldsBean obj1 = new TestAggregateAnnotation2FieldsBean(randomStr);
  TestAggregateAnnotation2FieldsBean obj2 = new TestAggregateAnnotation2FieldsBean(randomAlphabetic(20),
                                                                                   nextInt(1, 10000));
  TestAggregateAnnotation2FieldsBean obj3 = new TestAggregateAnnotation2FieldsBean(randomStr, nextInt(1, 10000));
  testAggregateRepository2.save(obj1);
  testAggregateRepository2.save(obj2);
  testAggregateRepository2.save(obj3);
  String outputRepoName = "tempBroken";
  testAggregateRepository2.aggregateQueryWithMatchAndOut(randomStr, outputRepoName);
  assertTrue(mongoTemplate.collectionExists(outputRepoName));
  List<TestAggregateAnnotation2FieldsBean> copiedObjs = mongoTemplate.findAll(TestAggregateAnnotation2FieldsBean.class,
                                                                              outputRepoName);
  //clear testAggregateAnnotationFieldsBean repo before running this test
  assertSame(copiedObjs.size(), 2);
  DBCursor dbCursor = mongoTemplate.getCollection("tempBroken").find();
  assertTrue(dbCursor.hasNext());
}
项目:beam    文件:MongoDbGridFSIO.java   
@Override
public long getEstimatedSizeBytes(PipelineOptions options) throws Exception {
  Mongo mongo = spec.connectionConfiguration().setupMongo();
  try {
    GridFS gridfs = spec.connectionConfiguration().setupGridFS(mongo);
    DBCursor cursor = createCursor(gridfs);
    long size = 0;
    while (cursor.hasNext()) {
      GridFSDBFile file = (GridFSDBFile) cursor.next();
      size += file.getLength();
    }
    return size;
  } finally {
    mongo.close();
  }
}
项目:Sledgehammer    文件:ModuleFactions.java   
/**
 * (Private Method)
 * <p>
 * Loads MongoFaction Objects from the database.
 */
private void loadMongoFactions() {
    println("Loading Faction(s)...");
    // Create HashMap.
    mapMongoFactions = new HashMap<>();
    // Initiate collection query.
    DBCursor cursor = collectionFactions.find();
    // Go through each entry.
    while (cursor.hasNext()) {
        // Create an object for each entry.
        MongoFaction mongoFaction = new MongoFaction(collectionFactions, cursor.next());
        // Add to the map with the UUID of the Faction.
        mapMongoFactions.put(mongoFaction.getUniqueId(), mongoFaction);
    }
    // Close the query.
    cursor.close();
    // Report statistics.
    int size = mapMongoFactions.size();
    println("Loaded " + (size == 0 ? "no" : size + "") + " Faction" + (size == 1 ? "" : "s") + ".");
}
项目:Sledgehammer    文件:ModuleFactions.java   
/**
 * (Private Method)
 * <p>
 * Loads MongoFactionMember Objects from the database.
 */
private void loadMongoFactionMembers() {
    println("Loading Faction Member(s)...");
    // Create HashMap.
    mapMongoFactionMembers = new HashMap<>();
    // Initiate collection query.
    DBCursor cursor = collectionFactionMembers.find();
    // Go through each entry.
    while (cursor.hasNext()) {
        // Create an object for each entry.
        MongoFactionMember mongoFactionMember = new MongoFactionMember(collectionFactionMembers, cursor.next());
        // Add to the map with the UUID of the FactionMember.
        mapMongoFactionMembers.put(mongoFactionMember.getPlayerId(), mongoFactionMember);
    }
    // Close the query.
    cursor.close();
    // Report statistics.
    int size = mapMongoFactionMembers.size();
    println("Loaded " + (size == 0 ? "no" : size + "") + " Faction Member" + (size == 1 ? "" : "s") + ".");
}
项目:Sledgehammer    文件:ModuleFactions.java   
/**
 * (Private Method)
 * <p>
 * Loads MongoFactionInvite Objects from the database.
 */
private void loadMongoFactionInvites() {
    println("Loading Faction Invite(s)...");
    // Create HashMap.
    mapMongoFactionInvites = new HashMap<>();
    // Initiate collection query.
    DBCursor cursor = collectionFactionInvites.find();
    // Go through each entry.
    while (cursor.hasNext()) {
        // Create an object for each entry.
        MongoFactionInvite mongoFactionInvite = new MongoFactionInvite(collectionFactionInvites, cursor.next());
        // Add to the map with the UUID of the MongoFactionInvite.
        mapMongoFactionInvites.put(mongoFactionInvite.getUniqueId(), mongoFactionInvite);
    }
    // Close the query.
    cursor.close();
    // Report statistics.
    int size = mapMongoFactionInvites.size();
    println("Loaded " + (size == 0 ? "no" : size + "") + " Faction Invite" + (size == 1 ? "" : "s") + ".");
}
项目:Sledgehammer    文件:ModuleChat.java   
/**
 * @param channelId The Unique ID of the channel.
 * @param limit     The Integer limit of ChatMessages to load.
 * @return Returns a List of ChatMessages for the ChatChannel.
 */
private List<ChatMessage> getChatMessages(UUID channelId, int limit) {
    List<ChatMessage> listChatMessages = new LinkedList<>();
    // Grab all the messages with the channel_id set to the one provided.
    DBObject query = new BasicDBObject("channel_id", channelId);
    DBCursor cursor = collectionMessages.find(query);
    // Sort the list by timestamp so that the last messages appear first.
    cursor.sort(new BasicDBObject("timestamp", -1));
    cursor.limit(limit);
    if(cursor.size() > 0) {
        List<DBObject> listObjects = cursor.toArray();
        Collections.reverse(listObjects);
        for(DBObject object : listObjects) {
            // Create the MongoDocument.
            MongoChatMessage mongoChatMessage = new MongoChatMessage(collectionMessages, object);
            // Create the container for the document.
            ChatMessage chatMessage = new ChatMessage(mongoChatMessage);
            // Add this to the list to return.
            listChatMessages.add(chatMessage);
        }
    }
    // Close the cursor to release resources.
    cursor.close();
    // Return the result list of messages for the channel.
    return listChatMessages;
}
项目:Sledgehammer    文件:SledgehammerDatabase.java   
public MongoPlayer getMongoPlayer(UUID uniqueId) {
    if (uniqueId == null) {
        throw new IllegalArgumentException("SledgehammerDatabase: uniqueId given is null!");
    }
    MongoPlayer player;
    player = mapPlayersByUUID.get(uniqueId);
    if (player == null) {
        DBCursor cursor = collectionPlayers.find(new BasicDBObject("uuid", uniqueId.toString()));
        if (cursor.hasNext()) {
            player = new MongoPlayer(collectionPlayers, cursor.next());
            registerPlayer(player);
        }
        cursor.close();
    }
    return player;
}
项目:Sledgehammer    文件:SledgehammerDatabase.java   
public MongoPlayer getMongoPlayer(String username) {
    if (username == null || username.isEmpty()) {
        throw new IllegalArgumentException("SledgehammerDatabase: Username given is null or empty!");
    }
    MongoPlayer player;
    player = mapPlayersByUsername.get(username);
    if (player == null) {
        DBCursor cursor = collectionPlayers.find(new BasicDBObject("username", username));
        if (cursor.hasNext()) {
            player = new MongoPlayer(collectionPlayers, cursor.next());
            registerPlayer(player);
        }
        cursor.close();
    }
    return player;
}
项目:Sledgehammer    文件:SledgehammerDatabase.java   
public MongoPlayer getMongoPlayer(String username, String password) {
    if (username == null || username.isEmpty()) {
        throw new IllegalArgumentException("SledgehammerDatabase: Username given is null or empty!");
    }
    MongoPlayer player;
    player = mapPlayersByUsername.get(username);
    if (player != null && !player.passwordsMatch(password)) {
        player = null;
    }
    if (player == null) {
        DBCursor cursor = collectionPlayers
                .find(new BasicDBObject("username", username).append("password", MD5.encrypt(password)));
        if (cursor.hasNext()) {
            player = new MongoPlayer(collectionPlayers, cursor.next());
            registerPlayer(player);
        }
        cursor.close();
    }
    return player;
}
项目:Sledgehammer    文件:SledgehammerDatabase.java   
public UUID getPlayerID(String username) {
    if (username == null || username.isEmpty()) {
        throw new IllegalArgumentException("SledgehammerDatabase: Username is null or empty!");
    }
    MongoPlayer player = getMongoPlayer(username);
    if (player != null) {
        return player.getUniqueId();
    }
    UUID returned = null;
    DBCursor cursor = collectionPlayers.find(new BasicDBObject("username", username));
    if (cursor.hasNext()) {
        DBObject object = cursor.next();
        returned = UUID.fromString(object.get("uuid").toString());
    }
    cursor.close();
    return returned;
}
项目:Elko    文件:MongoObjectStore.java   
/**
 * Perform a single 'query' operation on the local object store.
 *
 * @param template  Query template indicating what objects are sought.
 * @param collection  Collection to query.
 * @param maxResults  Maximum number of result objects to return, or 0 to
 *    indicate no fixed limit.
 *
 * @return a list of ObjectDesc objects for objects matching the query.
 */
private List<ObjectDesc> doQuery(JSONObject template,
                                 DBCollection collection, int maxResults) {
    List<ObjectDesc> results = new LinkedList<ObjectDesc>();

    try {
        DBObject query = jsonObjectToDBObject(template);
        DBCursor cursor;
        if (maxResults > 0) {
            cursor = collection.find(query, null, 0, -maxResults);
        } else {
            cursor = collection.find(query);
        }
        for (DBObject dbObj : cursor) {
            JSONObject jsonObj = dbObjectToJSONObject(dbObj);
            String obj = jsonObj.sendableString();
            results.add(new ObjectDesc("query", obj, null));
        }
    } catch (Exception e) {
        results.add(new ObjectDesc("query", null, e.getMessage()));
    }
    return results;
}
项目:Trivial5b    文件:Mongo.java   
public static void main(String[] args) throws IOException {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("mydb");
    DBCollection coll = db.getCollection("questionsCollection");
    mongoClient.setWriteConcern(WriteConcern.JOURNALED);
    GIFTParser p = new GIFTParser();
    BasicDBObject doc = null;
    for (Question q : p.parserGIFT("Data/questionsGIFT")) {
        doc = new BasicDBObject("category", q.getCategory())
                .append("question", q.getText())
                .append("correctanswer", q.getCorrectAnswer())
                .append("wrongAnswers",q.getWrongAnswers());
        coll.insert(doc);
    }

    DBCursor cursor = coll.find();
    try {
           while(cursor.hasNext()) {
               System.out.println(cursor.next());
           }
        } finally {
           cursor.close();
        }
}
项目:FinanceAnalytics    文件:MongoDBReferenceDataCache.java   
public Map<String, ReferenceData> load(Set<String> securities) {
  Map<String, ReferenceData> result = new TreeMap<String, ReferenceData>();
  FudgeSerializer serializer = new FudgeSerializer(_fudgeContext);

  BasicDBObject query = new BasicDBObject();
  query.put(SECURITY_DES_KEY_NAME, new BasicDBObject("$in", securities));
  DBCursor cursor = _mongoCollection.find(query);
  while (cursor.hasNext()) {
    DBObject dbObject = cursor.next();
    s_logger.debug("dbObject={}", dbObject);

    String securityDes = (String) dbObject.get(SECURITY_DES_KEY_NAME);
    s_logger.debug("Have security data for des {} in MongoDB", securityDes);
    ReferenceData perSecResult = parseDBObject(serializer, securityDes, dbObject);
    if (result.put(securityDes, perSecResult) != null) {
      s_logger.warn("{}/{} Querying on des {} gave more than one document", 
          new Object[] {_mongoConnector.getName(), _mongoCollection.getName(), securityDes });
    }
  }
  return result;
}
项目:LODVader    文件:GeneralQueries.java   
public  ArrayList<String> getMongoDBObject(String collectionName,
        String field, String value) {

    ArrayList<String> list = new ArrayList<String>();
    try {
        DBCollection collection = DBSuperClass2.getCollection(
                collectionName);
        DBObject query = new BasicDBObject(field, value);
        DBCursor instances = collection.find(query);

        for (DBObject instance : instances) {
            list.add(instance.get(ResourceDB.URI)
                    .toString());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;

}
项目:clotho3crud    文件:JongoConnection.java   
@Override
public List<Map> getCompletionData(){
    DBCursor cursor = rawDataCollection.find();
    Iterator<DBObject> iter = cursor.iterator();
    List<Map> out = new ArrayList<Map>();
    int i = 0;
    while(iter.hasNext()){
        try {
            DBObject temp = iter.next();
            Map map = new HashMap();
            map.put("name", temp.get("name"));
            map.put("schema", temp.get("schema"));
            map.put("id", temp.get("_id").toString());
            if(temp.containsKey("description")) {
                map.put("description", temp.get("description"));
            } else if(temp.containsKey("shortDescription")) {
                map.put("description", temp.get("shortDescription"));
            }
            out.add(map);
        } catch(Exception err) {
            err.printStackTrace();
        }
        i++;
    }
    return out;
}
项目:DOcloud-GreenTruck-sample    文件:TruckingJobInput.java   
private void serializeTruckTypes(JsonGenerator jgen) throws IOException,
        JsonProcessingException {
    jgen.writeArrayFieldStart("TruckTypes");
    DBCursor c = getDB().getCollection("truckTypes").find();
    while (c.hasNext()) {
        DBObject obj = c.next();
        jgen.writeStartObject();
        jgen.writeStringField("truckType", obj.get("_id").toString());
        jgen.writeNumberField("capacity",
                ((Number) obj.get("capacity")).intValue());
        jgen.writeNumberField("costPerMile",
                ((Number) obj.get("costPerMile")).intValue());
        jgen.writeNumberField("milesPerHour",
                ((Number) obj.get("milesPerHour")).intValue());
        jgen.writeEndObject();
    }
    jgen.writeEndArray();
}
项目:LODVader    文件:DistributionQueries.java   
public ArrayList<DistributionDB> getDistributionsByTopDatasetURL(DatasetDB topDataset) {

        ArrayList<DistributionDB> distributionList = new ArrayList<DistributionDB>();

        DBCollection collection;

        try {
            collection = DBSuperClass2.getDBInstance().getCollection(DistributionDB.COLLECTION_NAME);
            DBCursor instances = collection
                    .find(new BasicDBObject(DistributionDB.DEFAULT_DATASETS, topDataset.getLODVaderID()));

            for (DBObject instance : instances) {
                distributionList.add(new DistributionDB(instance));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return distributionList;
    }
项目:LODVader    文件:DatasetQueries.java   
public ArrayList<DatasetDB> getSubsetsAsMongoDBObject(DatasetDB dataset) {

        ArrayList<DatasetDB> list = new ArrayList<DatasetDB>();
        if(dataset.getSubsetsIDs().size()==0)
            return list;
        try {
            DBCollection collection = DBSuperClass2.getDBInstance().getCollection(
                    DatasetDB.COLLECTION_NAME);
            BasicDBObject query = new BasicDBObject(
                    DatasetDB.LOD_VADER_ID, new BasicDBObject("$in", dataset.getSubsetsIDs()));

            // query.append("$where", "this.distributions_uris.length > 0");
            DBCursor instances = collection.find(query);

            for (DBObject instance : instances) {
                list.add(new DatasetDB(instance));  
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
项目:spring-security-mongodb    文件:MongoTokenStore.java   
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
    List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();

    DBObject query = new BasicDBObject(clientIdFieldName, clientId);
    DBObject projection = new BasicDBObject(tokenFieldName, 1);
    DBCursor cursor = null;
    try {
        cursor = getAccessTokenCollection().find(query, projection);
        if (cursor.count() > 0) {
            while (cursor.hasNext()) {
                OAuth2AccessToken token = mapAccessToken(cursor.next());
                if (token != null) {
                    accessTokens.add(token);
                }
            }
        } else {
            LOG.info("Failed to find access token for clientId {}", clientId);
        }
        return accessTokens;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
项目:hadoop-mini-clusters    文件:MongodbLocalServerIntegrationTest.java   
@Test
public void testMongodbLocalServer() throws Exception {
    MongoClient mongo = new MongoClient(mongodbLocalServer.getIp(), mongodbLocalServer.getPort());

    DB db = mongo.getDB(propertyParser.getProperty(ConfigVars.MONGO_DATABASE_NAME_KEY));
    DBCollection col = db.createCollection(propertyParser.getProperty(ConfigVars.MONGO_COLLECTION_NAME_KEY),
            new BasicDBObject());

    col.save(new BasicDBObject("testDoc", new Date()));
    LOG.info("MONGODB: Number of items in collection: {}", col.count());
    assertEquals(1, col.count());

    DBCursor cursor = col.find();
    while(cursor.hasNext()) {
        LOG.info("MONGODB: Document output: {}", cursor.next());
    }
    cursor.close();
}
项目:osa    文件:MongoManager.java   
public List<DisposalListItem> getDisposalListItems(String organization){
    this.selectCollection(DB_DISPOSAL);
    List<DisposalListItem> disposalListItems = new ArrayList<DisposalListItem>();
    DBCursor cursor = table.find(new BasicDBObject("organization", organization), new BasicDBObject("_id", 0));

    if (cursor.size() > 0) {
        while (cursor.hasNext()) {
            List<Map<String,String>> results = new JSONDeserializer<List<Map<String,String>>>().deserialize(cursor.next().get(ARRAY_DISPOSAL).toString());
         for (int i = 0; i < results.size(); i++) {
            Map<String, String> item = results.get(i);
            DisposalListItem disposalItem = new DisposalListItem();

            disposalItem.setPid(item.get("pid"));
            disposalItem.setObjectName(item.get("objname"));
            disposalItem.setObjectType(item.get("objtype"));
            disposalItem.setDeleter(item.get("username"));
            disposalItem.setDisposalDateString(item.get("date"));
            disposalItem.setDisposalDateTimestamp(Long.parseLong(item.get("timestamp")));

    disposalListItems.add(disposalItem);
         }
        }
    }
    cursor.close();
    return disposalListItems;
}