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.apifest.oauth20.MongoDBManager.java

License:Apache License

protected Object getObject(DBCollection coll, BasicDBObject query) {
    DBCursor cursor = coll.find(query);
    Object result = null;//from ww  w.jav a  2 s  .com
    try {
        // TODO: if more than once throw exception
        while (cursor.hasNext()) {
            result = cursor.next();
            log.debug("found: " + result);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return result;
}

From source file:com.apifest.oauth20.persistence.mongodb.MongoDBManager.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from   w  w  w .j a v a2  s. c  o  m*/
public AuthCode findAuthCode(String authCode, String redirectUri) {
    BasicDBObject keys = new BasicDBObject();
    keys.put(AUTH_CODE, authCode);
    keys.put(ACCESS_TOKEN_REDIRECT_URI, redirectUri);
    keys.put(ACCESS_TOKEN_VALID, true);
    DBCursor list = db.getCollection(AUTH_CODE_COLLECTION_NAME).find(new BasicDBObject(keys));
    if (list.hasNext()) {
        DBObject result = list.next();
        Map<String, Object> mapLoaded = result.toMap();
        AuthCode loadedAuthCode = AuthCode.loadFromMap(mapLoaded);
        log.debug(loadedAuthCode.getClientId());
        list.close();
        return loadedAuthCode;
    }
    list.close();
    return null;
}

From source file:com.appleframework.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();

    FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
        @Override//from  w  w w.j a  v a 2s. com
        public String call() throws Exception {
            long startTime = System.currentTimeMillis();
            //???20
            logger.debug("result:");
            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("time out ", e);
        task.cancel(true);
    }

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

From source file:com.arquivolivre.mongocom.management.CollectionManager.java

License:Apache License

/**
 * Find all documents that match the specified query in the given
 * collection./*from  w w  w.  j av a2s  .c o m*/
 *
 * @param <A> generic type of the collection.
 * @param collectionClass
 * @param query
 * @return a list of documents.
 */
public <A extends Object> List<A> find(Class<A> collectionClass, MongoQuery query) {
    List<A> resultSet = new ArrayList<>();
    DBCursor cursor = null;
    try {
        A obj = collectionClass.newInstance();
        String collectionName = reflectCollectionName(obj);
        cursor = db.getCollection(collectionName).find(query.getQuery(), query.getConstraits());
        if (query.getSkip() > 0) {
            cursor = cursor.skip(query.getSkip());
        }
        if (query.getLimit() > 0) {
            cursor = cursor.limit(query.getLimit());
        }
        while (cursor.hasNext()) {
            DBObject objDB = cursor.next();
            loadObject(obj, objDB);
            resultSet.add(obj);
            obj = collectionClass.newInstance();
        }
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
        LOG.log(Level.SEVERE, null, ex);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return resultSet;
}

From source file:com.avanza.ymer.MirrorEnvironment.java

License:Apache License

public void removeFormatVersion(Class<?> dataType, Object id) {
    String collectionName = dataType.getSimpleName().substring(0, 1).toLowerCase()
            + dataType.getSimpleName().substring(1);
    DBCollection collection = getMongoDb().getCollection(collectionName);
    DBObject idQuery = BasicDBObjectBuilder.start("_id", id).get();
    DBCursor cursor = collection.find(idQuery);

    cursor.next();//from w  ww  . ja  v  a  2  s.  c om
    DBObject obj = cursor.curr();
    cursor.close();

    obj.removeField("_formatVersion");
    collection.update(idQuery, obj);
}

From source file:com.board.games.dao.nodebb.NodeBBJdbcDAOImpl.java

License:Open Source License

private PlayerProfile selectPlayerProfile(int id, String externalId, int accountId, boolean useExternalId)
        throws Exception {
    WalletAdapter walletAdapter = null;//from ww w.j a v a  2s. co  m

    if (getUseIntegrations().equals("Y")) {
        walletAdapter = new WalletAdapter();
    }

    String query = "";

    query = "select " + " n1.externalId, " + " n1.id,    " + " n3.id   " + " from " + getDbNetworkUserService()
            + "." + "User n1  " + " inner join " + getDbNetworkUserService() + "."
            + "UserAttribute n2 on n1.id=n2.user_id   " + " inner join " + getDbNetWorkWalletService() + "."
            + "Account n3 on n1.id=n3.userId   " + " where  "
            + (useExternalId ? " n1.id= ? " : " n1.externalId= ? ") + " and  " + " n3.name = n2.value ";

    log.warn("**** Query " + query);
    log.warn("User id to query " + (useExternalId ? externalId : id));
    /**
     * Define the connection, preparedStatement and resultSet parameters
     */
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        /**
         * Open the connection
         */
        connection = dataSource.getConnection();
        /**
         * Prepare the statement
         */
        preparedStatement = connection.prepareStatement(query);
        /**
         * Bind the parameters to the PreparedStatement
         */
        // use ipb user id instead only the other for account balance
        log.warn("external id to look : " + Integer.parseInt(externalId));
        preparedStatement.setInt(1, (useExternalId ? Integer.parseInt(externalId) : id));
        /**
         * Execute the statement
         */
        resultSet = preparedStatement.executeQuery();
        PlayerProfile playerProfile = null;

        /**
         * Extract data from the result set
         */
        if (resultSet.next()) {
            playerProfile = new PlayerProfile();
            String avatar_location = "";

            //   playerProfile.setId(resultSet.getInt("t2.uid"));
            //         String imageUrl = resultSet.getString("t2.avatar");
            //      avatar_location = getSiteUrl() + "/" + imageUrl;

            //         String name = resultSet.getString("t2.username");
            //      int groupId = resultSet.getInt("t2.usergroup");
            //   playerProfile.setGroupId(groupId);
            //      log.warn("name " + name);
            //   playerProfile.setName(name);

            int externalRealId = resultSet.getInt("n1.externalId");
            // To connect to mongodb server
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // Now connect to your databases
            DB db = mongoClient.getDB("nodebb");
            //       log.debug("Connect to database successfully");
            log.debug("Execute query: authenticate");
            DBCursor cursor = null;
            try {

                DBCollection collection = db.getCollection("objects");
                log.warn("Collection find " + "user:" + String.valueOf(externalRealId));

                cursor = collection.find(new BasicDBObject("_key", "user:" + String.valueOf(externalRealId)),
                        new BasicDBObject("_id", 0));

                avatar_location = (String) cursor.next().get("picture");
                //Picture /uploads/profile/1-profileimg.png
                log.warn("url before " + avatar_location);
                if (avatar_location.indexOf("uploads") != -1) {
                    log.warn("avatar is an upload avatar");
                    avatar_location = getSiteUrl() + avatar_location;
                }
                log.warn("url after " + avatar_location);
                playerProfile.setAvatar_location(avatar_location);
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
            log.warn("calling wallet account balance");
            int walletAccountId = resultSet.getInt("n3.id");
            AccountBalanceResult accountBalance = walletAdapter
                    .getAccountBalance(new Long(String.valueOf(walletAccountId)));
            if (accountBalance != null) {
                Money playerMoney = (Money) accountBalance.getBalance();
                log.warn(walletAccountId + " has " + playerMoney.getAmount());
                playerProfile.setBalance(playerMoney.getAmount());
            }

            int userAccountId = resultSet.getInt("n1.id");
            log.warn("Getting user level for " + userAccountId);
            int level = walletAdapter.getUserLevel(new Long(String.valueOf(userAccountId)));
            log.warn("Level found : " + level);
            playerProfile.setLevel(level);
            log.warn("Level retrieved as # : " + playerProfile.getLevel());
            return playerProfile;
        } else {
            log.debug("Found no user");
        }

    } catch (SQLException e) {
        e.printStackTrace();
        log.error("SQLException : " + e.toString());
    } catch (Exception e) {
        log.error("Exception in selectPlayerProfile " + e.toString());
        throw e;
    } finally {
        try {
            /**
             * Close the resultSet
             */
            if (resultSet != null) {
                resultSet.close();
            }
            /**
             * Close the preparedStatement
             */
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            /**
             * Close the connection
             */
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            /**
             * Handle any exception
             */
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.bugull.mongo.fs.BuguFS.java

License:Apache License

private List<GridFSDBFile> toFileList(DBCursor cursor) {
    List<GridFSDBFile> list = new ArrayList<GridFSDBFile>();
    while (cursor.hasNext()) {
        DBObject dbo = cursor.next();//from w ww.j av  a  2 s  .  c o m
        list.add((GridFSDBFile) dbo);
    }
    cursor.close();
    return list;
}

From source file:com.bugull.mongo.utils.MapperUtil.java

License:Apache License

public static <T> List<T> toList(Class<T> clazz, DBCursor cursor) {
    List<T> list = new ArrayList<T>();
    while (cursor.hasNext()) {
        DBObject dbo = cursor.next();//from   w  w  w. j  av  a 2s  . c o m
        list.add(fromDBObject(clazz, dbo));
    }
    cursor.close();
    return list;
}

From source file:com.buzz.buzzdata.MongoBuzz.java

private String getBuzz(BasicDBObject query, Double lat, Double lng) {
    String retval = "";
    DBCollection buzzCollection = mongoDB.getCollection("BuzzInfo");
    DBObject sort = new BasicDBObject();
    sort.put("modified", -1);
    DBCursor cursor = buzzCollection.find(query).sort(sort);
    try {/*from www  .  ja  v a2  s.c  o  m*/
        while (cursor.hasNext()) {
            //get buzzid
            DBObject buzz_obj = cursor.next();
            ObjectId buzz_id = (ObjectId) buzz_obj.get("_id");
            //get images for buzzid
            GridFS gridFS = new GridFS(mongoDB);
            BasicDBObject check_images = new BasicDBObject("BuzzID", buzz_id);
            List<GridFSDBFile> dbfiles = gridFS.find(check_images);
            String image_links = "";
            for (GridFSDBFile file : dbfiles) {
                String _buzz_id = buzz_id.toString();
                String pic_num = file.get("PicNum").toString();

                if (!image_links.equals("")) {
                    image_links += ",http://192.168.0.11:8080/BuzzRestAPI/webresources/buzz/Image?buzzid="
                            + _buzz_id + "&pic_num=" + pic_num;
                } else {
                    image_links += "http://192.168.0.11:8080/BuzzRestAPI/webresources/buzz/Image?buzzid="
                            + _buzz_id + "&pic_num=" + pic_num;
                }
            }
            String imgs = "\"Images\": " + "\"" + image_links + "\"";
            retval += buzz_obj;
            retval = retval.substring(0, retval.length() - 1);
            retval += ", " + imgs;
            double lat2 = (double) ((BasicDBList) buzz_obj.get("loc")).get(0);
            double lng2 = (double) ((BasicDBList) buzz_obj.get("loc")).get(1);
            double dist = this.haversine(lat, lng, lat2, lng2);
            retval += ", \"Distance\": " + dist;
            String directions_url = "https://maps.google.com/maps?saddr=" + lat + "," + lng + "&daddr=" + lat2
                    + "," + lng2 + "&hl=en&sll=" + lat + "," + lng + "&sspn=" + lat2 + "," + lng2
                    + "&t=m&mra=mift&mrsp=1&sz=5&z=18";
            retval += ", \"Directions\": \"" + directions_url + "\"";
            retval += "},";
        }
    } catch (Exception exc) {
    } finally {
        cursor.close();
    }
    retval = retval.substring(0, retval.length() - 1);
    retval = "callback({\"Buzzes\": [" + retval + "]})";
    return retval;
}

From source file:com.buzz.buzzdata.MongoBuzz.java

private String executeQueries(BasicDBObject[] queries, String combine, String collName) {
    String retval = "";
    DBCollection buzzCollection = mongoDB.getCollection(collName);
    BasicDBObject filters = new BasicDBObject(combine, queries);
    DBCursor cursor = buzzCollection.find(filters);
    try {//ww  w  . j  a  va 2s.  c o  m
        while (cursor.hasNext()) {
            retval += cursor.next();
            retval += "\n";
        }
    } finally {
        cursor.close();
    }
    return retval;
}