List of usage examples for com.mongodb DBCollection find
public DBCursor find(@Nullable final DBObject query, final DBCollectionFindOptions options)
From source file:calliope.db.MongoConnection.java
License:Open Source License
/** * List all the documents in a Mongo collection * @param collName the name of the collection * @return a String array of document keys * @throws AeseException /*from ww w .ja v a2 s . co m*/ */ @Override public String[] listCollection(String collName) throws AeseException { if (!collName.equals(Database.CORPIX)) { try { connect(); } catch (Exception e) { throw new AeseException(e); } DBCollection coll = getCollectionFromName(collName); BasicDBObject keys = new BasicDBObject(); keys.put(JSONKeys.DOCID, 1); DBCursor cursor = coll.find(new BasicDBObject(), keys); System.out.println("Found " + cursor.count() + " documents"); cursor.count(); if (cursor.length() > 0) { String[] docs = new String[cursor.length()]; Iterator<DBObject> iter = cursor.iterator(); int i = 0; while (iter.hasNext()) docs[i++] = (String) iter.next().get(JSONKeys.DOCID); return docs; } else { return new String[0]; } } else { GridFS gfs = new GridFS(db, collName); DBCursor curs = gfs.getFileList(); int i = 0; List<DBObject> list = curs.toArray(); HashSet<String> set = new HashSet<String>(); Iterator<DBObject> iter = list.iterator(); while (iter.hasNext()) { String name = (String) iter.next().get("filename"); set.add(name); } String[] docs = new String[set.size()]; set.toArray(docs); return docs; } }
From source file:cn.vlabs.clb.server.storage.mongo.MongoStorageService.java
License:Apache License
private Set<Integer> queryChunkMap(String storageKey, String tableName) { DB db = options.getCollection(TABLE_TEMP_KEY).getDB(); DBObject query = new BasicDBObject(); query.put("storageKey", new ObjectId(storageKey)); Set<Integer> result = new HashSet<Integer>(); DBCollection chunkTable = db.getCollection(tableName + ".chunks"); DBObject ref = new BasicDBObject(); ref.put("files_id", new ObjectId(storageKey)); DBObject keys = new BasicDBObject(); keys.put("n", 1); DBCursor cursor = chunkTable.find(ref, keys); while (cursor.hasNext()) { DBObject o = cursor.next();//from www . ja v a 2 s. c o m result.add(Integer.parseInt(o.get("n").toString())); } return result; }
From source file:com.Aleksandar.Zoric.MongoMain.java
public String retreiveUser() { DB db = mongoClient.getDB("amarokforumdb"); DBCollection collection = db.getCollection("users"); BasicDBObject allQuery = new BasicDBObject(); BasicDBObject fields = new BasicDBObject(); fields.put("name", 1); String result = null;// w ww . j av a 2 s. c om DBCursor cursor = collection.find(allQuery, fields); while (cursor.hasNext()) { result += "\n" + cursor.next(); //System.out.println(cursor.next()); } return "All current user's are as follows: \n" + result; }
From source file:com.andreig.jetty.QueryServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doPost()"); // server auth if (!can_read(req)) { res.sendError(SC_UNAUTHORIZED);// ww w . j a va 2 s .c om return; } String ret = null; InputStream is = req.getInputStream(); String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); if (db_name == null || col_name == null) { String names[] = req2mongonames(req); if (names != null) { db_name = names[0]; col_name = names[1]; } if (db_name == null || col_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } } String skip = req.getParameter("skip"); String limit = req.getParameter("limit"); String _fields = req.getParameter("fields"); String fields[] = null; if (_fields != null) fields = _fields.split("[,]"); DB db = mongo.getDB(db_name); // mongo auth String user = req.getParameter("user"); String passwd = req.getParameter("passwd"); if (user != null && passwd != null && (!db.isAuthenticated())) { boolean auth = db.authenticate(user, passwd.toCharArray()); if (!auth) { res.sendError(SC_UNAUTHORIZED); return; } } DBCollection col = db.getCollection(col_name); StringBuilder buf = tl.get(); // reset buf buf.setLength(0); BufferedReader r = null; DBObject q = null, sort = null; try { r = new BufferedReader(new InputStreamReader(is)); String data = r.readLine(); if (data == null) { error(res, SC_BAD_REQUEST, Status.get("no data")); return; } try { q = (DBObject) JSON.parse(data); if (cache != null) { buf.append(db_name); buf.append(col_name); buf.append(data); } } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } // sort param data = r.readLine(); if (data != null) { try { sort = (DBObject) JSON.parse(data); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg")); return; } if (cache != null) buf.append(data); } } finally { if (r != null) r.close(); } // limit int lim; if (limit != null) { try { lim = Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN); } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse limit")); return; } } else { lim = MAX_FIELDS_TO_RETURN; } if (cache != null) { buf.append(";limit="); buf.append(lim); } // skip int sk = -1; if (skip != null) { try { sk = Integer.parseInt(skip); if (cache != null) { buf.append(";skip="); buf.append(sk); } } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse skip")); return; } } // fields if (cache != null && _fields != null) { buf.append(";fields="); buf.append(_fields); } // from cache String cache_key = null; if (cache != null) { cache_key = buf.toString(); try { ret = (String) cache.get(cache_key); } // some wrong char in key catch (IllegalArgumentException e) { int l = buf.length(); for (int i = 0; i < l; i++) { if (buf.charAt(i) == ' ') buf.setCharAt(i, '*'); } cache_key = buf.toString(); ret = (String) cache.get(cache_key); } if (ret != null) { out_str(req, ret, "application/json"); return; } } // cursor DBCursor c; if (fields != null) { StringBuilder sb = new StringBuilder(); sb.append("{"); int len = fields.length; for (int i = 0; i < len; i++) { String s = fields[i]; sb.append('"'); sb.append(s); sb.append('"'); sb.append(":1"); if (i != (len - 1)) sb.append(","); } sb.append("}"); c = col.find(q, (DBObject) JSON.parse(sb.toString())); } else c = col.find(q); if (c == null || c.count() == 0) { error(res, SC_NOT_FOUND, Status.get("no documents found")); return; } if (sort != null) c.sort(sort); res.setIntHeader("X-Documents-Count", c.count()); c.limit(lim); if (sk != -1) c.skip(sk); // reset buf buf.setLength(0); int no = 0; buf.append("["); while (c.hasNext()) { DBObject o = c.next(); if (rm_id) o.removeField("_id"); JSON.serialize(o, buf); buf.append(","); no++; } c.close(); if (no > 0) buf.setCharAt(buf.length() - 1, ']'); else buf.append(']'); res.setIntHeader("X-Documents-Returned", no); ret = buf.toString(); if (cache != null) cache.set(cache_key, ret); out_str(req, ret, "application/json"); }
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;// www . ja v a 2 s . com 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.board.games.handler.nodebb.NodeBBPokerLoginServiceImpl.java
License:Open Source License
private String authenticate(String user, String password, ServerConfig serverConfig, boolean checkAge, int authTypeId) throws Exception { try {//from ww w.j a va 2 s . c om if (serverConfig == null) { log.error("ServerConfig is null."); return "-3"; } int idx = user.indexOf("_"); if (idx != -1) { // let bots through String idStr = user.substring(idx + 1); if (user.toUpperCase().startsWith("BOT")) { if (serverConfig.isUseIntegrations()) { WalletAdapter walletAdapter = new WalletAdapter(); log.debug("Calling createWalletAccount"); //walletAdapter.createWalletAccount(new Long(String.valueOf(member_id))); Long userId = walletAdapter.checkCreateNewUser(idStr, idStr, "UNUSED", new Long(0), serverConfig.getCurrency(), serverConfig.getWalletBankAccountId(), (serverConfig.getInitialAmount().multiply(new BigDecimal(20))), true, false, 0); return String.valueOf(userId); } else { return idStr; } } } if (user.toUpperCase().startsWith("GUESTXDEMO")) { return String.valueOf(pid.incrementAndGet()); } log.debug("Execute query: authenticate"); String members_pass_hash = null; String members_display_name = null; boolean authenticated = false; int member_id = 0; int posts = 0; // 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"); DBCollection collection = db.getCollection("objects"); cursor = collection.find(new BasicDBObject("username", user), new BasicDBObject("_id", 0)); members_pass_hash = (String) cursor.next().get("password"); log.error("DB members_pass_hash = " + members_pass_hash); cursor2 = collection.find(new BasicDBObject("username", user), new BasicDBObject("_id", 0)); member_id = (int) cursor2.next().get("uid"); log.error("DB member_id = " + member_id); log.debug("User: " + user + " Password " + "********"); if (members_pass_hash != null) { // Check it against database stored hash authenticated = BCrypt.checkpw(password, members_pass_hash); } else { log.debug("failed verification of hashing"); } if (authenticated) { log.debug("Authentication successful"); log.debug("Member id " + String.valueOf(member_id)); if (serverConfig.isUseIntegrations()) { WalletAdapter walletAdapter = new WalletAdapter(); log.error("Calling createWalletAccount"); //walletAdapter.createWalletAccount(new Long(String.valueOf(member_id))); Long userId = walletAdapter.checkCreateNewUser(String.valueOf(member_id), user, "UNUSED", new Long(1), serverConfig.getCurrency(), serverConfig.getWalletBankAccountId(), serverConfig.getInitialAmount(), checkAge, needAgeAgreement, authTypeId); if (userId < 0) { // user did not accept age clauses return "-5"; } log.debug("assigned new id as #" + String.valueOf(userId)); return String.valueOf(userId); } else { return String.valueOf(member_id); } /* if (posts >= 1) { return String.valueOf(member_id); } else { log.error("Required number of posts not met, denied login"); return "-2"; }*/ } else { log.error("hash not matched for user " + user + " password " + password); return "-1"; } } catch (Exception e) { log.error("Error : " + e.toString()); // throw e; } finally { close(); } return "-3"; }
From source file:com.cloudbees.gasp.model.MongoConnection.java
License:Apache License
public String getLocations() { DBCollection locations = getCollection(); // Omit object id from result BasicDBObject omits = new BasicDBObject(); omits.put("_id", 0); // Search//from ww w . ja va2 s . c o m BasicDBObject findLocations = new BasicDBObject(); List<DBObject> listLocations = locations.find(findLocations, omits).limit(200).toArray(); if (logger.isDebugEnabled()) logger.debug("getLocations(): " + listLocations.toString()); // Return the JSON string with the locations collection return (listLocations.toString()); }
From source file:com.cloudbees.gasp.model.MongoConnection.java
License:Apache License
public String getLocationsByGeoCenter(Location center, double radius) { if (logger.isDebugEnabled()) { logger.debug("getLocationsByGeoCenter(): lng = " + center.getLng()); logger.debug("getLocationsByGeoCenter(): lat = " + center.getLat()); logger.debug("getLocationsByGeoCenter(): radius = " + radius); }//w ww . j a v a2s.c om DBCollection locations = getCollection(); locations.ensureIndex(new BasicDBObject("location", "2d")); // Omit object id from result BasicDBObject omits = new BasicDBObject(); omits.put("_id", 0); // Perform geo-search List<Object> circle = new ArrayList<Object>(); circle.add(new double[] { center.getLng(), center.getLat() }); circle.add(radius); BasicDBObject query = new BasicDBObject("location", new BasicDBObject("$within", new BasicDBObject("$center", circle))); List<DBObject> listLocations = locations.find(query, omits).limit(200).toArray(); if (logger.isDebugEnabled()) logger.debug("getLocationsByGeoCenter(): " + listLocations.toString()); // Return the JSON string with the locations collection return (listLocations.toString()); }
From source file:com.cyslab.craftvm.rest.mongo.QueryServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.trace("doPost()"); // server auth if (!can_read(req)) { res.sendError(SC_UNAUTHORIZED);//from www. j av a2 s.c om return; } String ret = null; InputStream is = req.getInputStream(); String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); if (db_name == null || col_name == null) { String names[] = req2mongonames(req); if (names != null) { db_name = names[0]; col_name = names[1]; } if (db_name == null || col_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return; } } String skip = req.getParameter("skip"); String limit = req.getParameter("limit"); String _fields = req.getParameter("fields"); String fields[] = null; if (_fields != null) fields = _fields.split("[,]"); DB db = mongo.getDB(db_name); // mongo auth String user = req.getParameter("user"); String passwd = req.getParameter("passwd"); if (user != null && passwd != null && (!db.isAuthenticated())) { boolean auth = db.authenticate(user, passwd.toCharArray()); if (!auth) { res.sendError(SC_UNAUTHORIZED); return; } } DBCollection col = db.getCollection(col_name); StringBuilder buf = tl.get(); // reset buf buf.setLength(0); BufferedReader r = null; DBObject q = null, sort = null; try { r = new BufferedReader(new InputStreamReader(is)); String data = r.readLine(); if (data == null) { error(res, SC_BAD_REQUEST, Status.get("no data")); return; } try { q = (DBObject) JSON.parse(data); if (cache != null) { buf.append(db_name); buf.append(col_name); buf.append(data); } } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse data")); return; } // sort param data = r.readLine(); if (data != null) { try { sort = (DBObject) JSON.parse(data); } catch (JSONParseException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg")); return; } if (cache != null) buf.append(data); } } finally { if (r != null) r.close(); } // limit int lim; if (limit != null) { try { lim = Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN); } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse limit")); return; } } else { lim = MAX_FIELDS_TO_RETURN; } if (cache != null) { buf.append(";limit="); buf.append(lim); } // skip int sk = -1; if (skip != null) { try { sk = Integer.parseInt(skip); if (cache != null) { buf.append(";skip="); buf.append(sk); } } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse skip")); return; } } // fields if (cache != null && _fields != null) { buf.append(";fields="); buf.append(_fields); } // from cache String cache_key = null; if (cache != null) { cache_key = buf.toString(); try { ret = (String) cache.get(cache_key); } // some wrong char in key catch (IllegalArgumentException e) { int l = buf.length(); for (int i = 0; i < l; i++) { if (buf.charAt(i) == ' ') buf.setCharAt(i, '*'); } cache_key = buf.toString(); ret = (String) cache.get(cache_key); } if (ret != null) { out_str(req, ret, "application/json"); return; } } // cursor DBCursor c; if (fields != null) { StringBuilder sb = new StringBuilder(); sb.append("{"); int len = fields.length; for (int i = 0; i < len; i++) { String s = fields[i]; sb.append('"'); sb.append(s); sb.append('"'); sb.append(":1"); if (i != (len - 1)) sb.append(","); } sb.append("}"); c = col.find(q, (DBObject) JSON.parse(sb.toString())); } else c = col.find(q); if (c == null || c.count() == 0) { error(res, SC_NOT_FOUND, Status.get("no documents found")); return; } if (sort != null) c.sort(sort); res.setIntHeader("X-Documents-Count", c.count()); c.limit(lim); if (sk != -1) c.skip(sk); // reset buf buf.setLength(0); int no = 0; buf.append("["); while (c.hasNext()) { DBObject o = c.next(); if (rm_id) o.removeField("_id"); JSON.serialize(o, buf); buf.append(","); no++; } c.close(); if (no > 0) buf.setCharAt(buf.length() - 1, ']'); else buf.append(']'); res.setIntHeader("X-Documents-Returned", no); ret = buf.toString(); if (cache != null) cache.set(cache_key, ret); out_str(req, ret, "application/json"); }
From source file:com.ebay.cloud.cms.dal.persistence.MongoExecutor.java
License:Apache License
public static List<DBObject> find(PersistenceContext context, MetaClass metadata, DBObject queryObject, DBObject fieldObject, SearchOption option) { long start = System.currentTimeMillis(); String msg = "success"; DBCollection dbCollection = context.getDBCollection(metadata); DBCursor findCursor = null;// ww w . j a v a 2s .c om Integer size = 0; try { findCursor = dbCollection.find(queryObject, fieldObject); // set option if (option.hasLimit()) { findCursor.limit(option.getLimit()); } if (option.hasSkip()) { findCursor.skip(option.getSkip()); } if (option.hasSort()) { findCursor.sort(option.getSort()); } // populate search result List<DBObject> result = findCursor.toArray(); size = result.size(); return result; } catch (Throwable t) { msg = t.getMessage(); handleMongoException(t); } finally { if (findCursor != null) { findCursor.close(); } logMongoAction(context, "find", start, dbCollection, queryObject, fieldObject, option, size, msg); } return Collections.emptyList(); }