Example usage for com.mongodb DBCursor close

List of usage examples for com.mongodb DBCursor close

Introduction

In this page you can find the example usage for com.mongodb DBCursor close.

Prototype

@Override
    public void close() 

Source Link

Usage

From source file:com.sitewhere.mongodb.MongoPersistence.java

License:Open Source License

/**
 * Search the given collection using the provided query and sort. Return the paged
 * seaerch results./*from w  ww  .j a va 2  s.c  o m*/
 * 
 * @param api
 * @param collection
 * @param query
 * @param sort
 * @param pageNumber
 * @param pageSize
 * @return
 */
public static <T> SearchResults<T> search(Class<T> api, DBCollection collection, DBObject query, DBObject sort,
        ISearchCriteria criteria) {
    int offset = Math.max(0, criteria.getPageNumber() - 1) * criteria.getPageSize();
    DBCursor cursor = collection.find(query).skip(offset).limit(criteria.getPageSize()).sort(sort);
    List<T> matches = new ArrayList<T>();
    SearchResults<T> results = new SearchResults<T>(matches);
    MongoConverter<T> converter = MongoConverters.getConverterFor(api);
    try {
        results.setNumResults(cursor.count());
        while (cursor.hasNext()) {
            DBObject match = cursor.next();
            matches.add(converter.convert(match));
        }
    } finally {
        cursor.close();
    }
    return results;
}

From source file:com.sitewhere.mongodb.MongoPersistence.java

License:Open Source License

/**
 * Search the given collection using the provided query and sort.
 * /*from w  ww . ja va 2 s .  c  om*/
 * @param api
 * @param collection
 * @param query
 * @param sort
 * @return
 */
public static <T> SearchResults<T> search(Class<T> api, DBCollection collection, DBObject query,
        DBObject sort) {
    DBCursor cursor = collection.find(query).sort(sort);
    List<T> matches = new ArrayList<T>();
    SearchResults<T> results = new SearchResults<T>(matches);
    MongoConverter<T> converter = MongoConverters.getConverterFor(api);
    try {
        results.setNumResults(cursor.count());
        while (cursor.hasNext()) {
            DBObject match = cursor.next();
            matches.add(converter.convert(match));
        }
    } finally {
        cursor.close();
    }
    return results;
}

From source file:com.sitewhere.mongodb.MongoPersistence.java

License:Open Source License

/**
 * List all items in the collection that match the qiven query.
 * /*from  ww w . j  a  va2 s. c o m*/
 * @param api
 * @param collection
 * @param query
 * @param sort
 * @return
 */
public static <T> List<T> list(Class<T> api, DBCollection collection, DBObject query, DBObject sort) {
    DBCursor cursor = collection.find(query);
    List<T> matches = new ArrayList<T>();
    MongoConverter<T> converter = MongoConverters.getConverterFor(api);
    try {
        while (cursor.hasNext()) {
            DBObject match = cursor.next();
            matches.add(converter.convert(match));
        }
    } finally {
        cursor.close();
    }
    return matches;
}

From source file:com.sitewhere.mongodb.user.MongoUserManagement.java

License:Open Source License

public List<IUser> listUsers(IUserSearchCriteria criteria) throws SiteWhereException {
    DBCollection users = getMongoClient().getUsersCollection();
    DBObject dbCriteria = new BasicDBObject();
    if (!criteria.isIncludeDeleted()) {
        MongoSiteWhereEntity.setDeleted(dbCriteria, false);
    }//from www  .  j a va2s. c  om
    DBCursor cursor = users.find(dbCriteria).sort(new BasicDBObject(MongoUser.PROP_USERNAME, 1));
    List<IUser> matches = new ArrayList<IUser>();
    try {
        while (cursor.hasNext()) {
            DBObject match = cursor.next();
            matches.add(MongoUser.fromDBObject(match));
        }
    } finally {
        cursor.close();
    }
    return matches;
}

From source file:com.sitewhere.mongodb.user.MongoUserManagement.java

License:Open Source License

public List<IGrantedAuthority> listGrantedAuthorities(IGrantedAuthoritySearchCriteria criteria)
        throws SiteWhereException {
    DBCollection auths = getMongoClient().getAuthoritiesCollection();
    DBCursor cursor = auths.find().sort(new BasicDBObject(MongoGrantedAuthority.PROP_AUTHORITY, 1));
    List<IGrantedAuthority> matches = new ArrayList<IGrantedAuthority>();
    try {/*from www . j a v a2s  .co m*/
        while (cursor.hasNext()) {
            DBObject match = cursor.next();
            matches.add(MongoGrantedAuthority.fromDBObject(match));
        }
    } finally {
        cursor.close();
    }
    return matches;
}

From source file:com.skymobi.monitor.action.LogsAction.java

License:Open Source License

@RequestMapping(value = "/projects/{projectName}/logs/more", method = RequestMethod.GET)
public void console(final HttpServletResponse response, ModelMap map, @PathVariable String projectName,
        LogQuery logQuery) throws IOException, ParseException {
    Project project = projectService.findProject(projectName);
    map.put("project", project);
    final MongoConverter converter = project.fetchMongoTemplate().getConverter();
    final DBCursor cursor = logsService.findLogs(projectName, logQuery);
    final StringBuffer buf = new StringBuffer();
    @SuppressWarnings("unchecked")
    FutureTask<String> task = new FutureTask(new Callable<String>() {
        @Override/*w w  w  .  j av  a  2s  . com*/
        public String call() throws Exception {
            long startTime = System.currentTimeMillis();
            //???20
            logger.debug("??:");
            while (cursor.hasNext()) {
                Log log = converter.read(Log.class, cursor.next());

                buf.insert(0, log.toString() + "\n");
                long current = System.currentTimeMillis();
                if ((current - startTime) / 1000 >= mongWaitSeconds)
                    break;
            }
            return buf.toString();
        }
    });
    executor.execute(task);
    try {
        task.get(mongWaitSeconds + 5, TimeUnit.SECONDS);
        cursor.close();
    } catch (Exception e) {
        logger.error(" ", e);
        task.cancel(true);
    }

    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().write(buf.toString());
    response.getWriter().flush();

}

From source file:com.smbtec.xo.mongodb.impl.JSONQuery.java

License:Apache License

private ResultIterator<Map<String, Object>> execute0(String json, Class<?> type,
        Map<String, Object> parameters) {
    // TODO//from   w  w  w.ja v a 2s .  c o  m
    DBCollection collection = database.getCollection("A");

    final DBCursor matches = collection.find((DBObject) JSON.parse(json));

    return new ResultIterator<Map<String, Object>>() {

        public boolean hasNext() {
            return matches.hasNext();
        }

        public Map<String, Object> next() {
            DBObject next = matches.next();
            final Map<String, Object> result = new HashMap<>();
            // TODO
            result.put("result", new MongoDbDocument(next, "A"));
            return result;
        }

        public void remove() {
            throw new XOException("Remove operation is not supported for query results.");
        }

        public void close() {
            matches.close();
        }
    };

}

From source file:com.smbtec.xo.mongodb.impl.MongoDbDocumentManager.java

License:Apache License

@Override
public ResultIterator<MongoDbDocument> findEntity(EntityTypeMetadata<DocumentMetadata> entityTypeMetadata,
        String discriminator, Map<PrimitivePropertyMethodMetadata<PropertyMetadata>, Object> values) {
    if (values.size() > 1) {
        throw new XOException("Only one property value is supported for find operation");
    }/*from  w  w w .j  av  a2s . c o m*/

    Map.Entry<PrimitivePropertyMethodMetadata<PropertyMetadata>, Object> entry = values.entrySet().iterator()
            .next();
    PrimitivePropertyMethodMetadata<PropertyMetadata> propertyMethodMetadata = entry.getKey();
    PropertyMetadata propertyMetadata = propertyMethodMetadata.getDatastoreMetadata();
    Object value = entry.getValue();
    String collectionName = entityTypeMetadata.getDatastoreMetadata().getDiscriminator();

    final DBCursor matches = database.getCollection(collectionName)
            .find(new BasicDBObject(propertyMetadata.getName(), value));

    return new ResultIterator<MongoDbDocument>() {

        public boolean hasNext() {
            return matches.hasNext();
        }

        public MongoDbDocument next() {
            return new MongoDbDocument(matches.next(), discriminator);
        }

        public void close() {
            matches.close();
        }

        @Override
        public void remove() {
            // intentionally left blank
        }
    };
}

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

private void sendBatch(Message<JsonObject> message, final DBCursor cursor, final int max, final int timeout) {
    int count = 0;
    JsonArray results = new JsonArray();
    while (cursor.hasNext() && count < max) {
        DBObject obj = cursor.next();/*from  w  w w  .  ja va2  s .c o m*/
        JsonObject m = new JsonObject(obj.toMap());
        results.add(m);
        count++;
    }
    if (cursor.hasNext()) {
        JsonObject reply = createBatchMessage("more-exist", results);

        // If the user doesn't reply within timeout, close the cursor
        final long timerID = vertx.setTimer(timeout, new Handler<Long>() {
            @Override
            public void handle(Long timerID) {
                container.logger().warn("Closing DB cursor on timeout");
                try {
                    cursor.close();
                } catch (Exception ignore) {
                }
            }
        });

        message.reply(reply, new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> msg) {
                vertx.cancelTimer(timerID);
                // Get the next batch
                sendBatch(msg, cursor, max, timeout);
            }
        });

    } else {
        JsonObject reply = createBatchMessage("ok", results);
        message.reply(reply);
        cursor.close();
    }
}

From source file:com.softlyinspired.jlw.menus.mongoMenuSet.java

License:Open Source License

int readAllCustomMenus() throws UnknownHostException {
    // get handle to "mydb"
    DB db = repoConnection.getConnection();
    DBCollection coll = db.getCollection("customMenus");

    // get all the documents in the collection and print them out
    BasicDBObject query = new BasicDBObject();
    BasicDBObject fields = new BasicDBObject();
    fields.put("menuTitle", 1);
    fields.put("menuId", 1);
    fields.put("concernId", 1);
    fields.put("_id", 0);

    DBCursor cursor = coll.find(query, fields);
    int menuIdFound;
    String menuTitleFound = null;
    String menuConcernFound = null;
    DBObject doc;//from w  ww. j av a 2 s .  c o m

    try {

        while (cursor.hasNext()) {
            doc = cursor.next();
            String menuIdText = doc.get("menuId").toString();
            try {
                menuIdFound = Integer.parseInt(menuIdText);
            } catch (Exception e) {
                menuIdFound = 0;
            }
            menuTitleFound = doc.get("menuTitle").toString();
            menuConcernFound = doc.get("concernId").toString();
            boolean menuFound = false;

            int i = 0;
            while ((i < menuCount) && (menuFound == false)) {
                if (customMenu[i].menuId == menuIdFound) {
                    menuFound = true;
                    mongoMenu currentMenu = new mongoMenu();
                    currentMenu = customMenu[i];
                    currentMenu.menuItem[currentMenu.menuItemCount] = menuConcernFound;
                    currentMenu.menuItemCount += 1;
                    customMenu[i] = currentMenu;
                }
                i += 1;
            }
            if (!menuFound) {
                mongoMenu currentMenu = new mongoMenu();
                currentMenu.menuId = menuIdFound;
                currentMenu.menuTitle = menuTitleFound;
                currentMenu.menuItem[0] = menuConcernFound;
                currentMenu.menuItemCount = 1;
                customMenu[menuCount] = currentMenu;
                menuCount = menuCount + 1;

            }
        }
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        cursor.close();
    }

    return menuCount;

}