Example usage for com.mongodb DBCursor sort

List of usage examples for com.mongodb DBCursor sort

Introduction

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

Prototype

public DBCursor sort(final DBObject orderBy) 

Source Link

Document

Sorts this cursor's elements.

Usage

From source file:Highscores.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {//from  w  w  w  .  ja va 2s .  c o  m
        String user;
        int count = 1;
        String highscore;
        jTextArea2.append("SR No.\tUSERNAME\tHIGHSCORE\n");
        int high;
        MongoClient mc = new MongoClient("localhost", 27017);
        DB db = mc.getDB("Classic_Hangman");
        System.out.println("Connected to database successfully!!");
        DBCollection coll = db.getCollection("high_score");
        System.out.println("Collection Retrieved");
        DBCursor cursor = coll.find();
        cursor.sort(new BasicDBObject("value", -1));
        while (cursor.hasNext() && count < 4) {
            DBObject result = cursor.next();
            high = ((Number) result.get("value")).intValue();
            highscore = Integer.toString(high);
            user = (String) result.get("_id");
            jTextArea2.append(count + "\t" + user + "\t" + highscore + "\n");
            count++;
        }
    } catch (UnknownHostException ex) {
        Logger.getLogger(Highscores.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:biopolis.headless.BiopolisSegmentationManagement.java

public List<Long> search(BiopolisSegmentQuery seg) throws BiopolisGeneralException {
    byte[] bytes = Base64.decodeBase64(seg.biopolisid);
    ObjectId someid = new ObjectId(bytes);
    DBCursor cur = dbcol.find(new BasicDBObject("_id", someid));
    if (!cur.hasNext()) {
        throw new BiopolisGeneralException("Search not exists with id " + seg.biopolisid);
    }//www. j ava  2  s  .com
    BasicDBObject setter = new BasicDBObject("$set", new BasicDBObject("biopolisttl", new java.util.Date()));
    dbcol.update(new BasicDBObject("_id", someid), setter);
    dbcol.update(new BasicDBObject("biopolisid", seg.biopolisid), setter);

    List<Long> resus = new ArrayList<Long>();
    cur = dbcol.find(new BasicDBObject("biopolisid", seg.biopolisid));
    cur = cur.sort(new BasicDBObject("biopolisdata", 1));

    int count = 0;
    while (cur.hasNext()) {
        System.out.println("scan " + seg.from);
        DBObject obj = cur.next();
        if ((count >= seg.from) && (count < seg.from + this.segSZ)) {
            System.out.println("add");
            Long i = (Long) obj.get("biopolisdata");
            resus.add(i);
        }
        count++;
    }
    System.out.println(resus.size());
    return resus;
}

From source file:cn.vlabs.clb.server.storage.mongo.extend.MyGridFS.java

License:Apache License

public List<MyGridFSDBFile> find(DBObject query, DBObject sort) {
    List<MyGridFSDBFile> files = new ArrayList<MyGridFSDBFile>();

    DBCursor c = null;
    try {/*w  w w  .  j a  v  a  2  s  .  co m*/
        c = _filesCollection.find(query);
        if (sort != null) {
            c.sort(sort);
        }
        while (c.hasNext()) {
            files.add(_fix(c.next()));
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return files;
}

From source file:co.mcme.themedbuilds.database.DatabaseUtil.java

License:Open Source License

public static Theme getThemeByName(String name) {
    DBObject query = QueryBuilder.start("name").is(name).get();
    try {/*w  w w  . ja  va  2 s  . co  m*/
        DBCursor cursor = ThemedBuildPlugin.getMongoUtil().getThemeCollection().find(query);
        DBObject object = cursor.sort(new BasicDBObject("_id", -1)).limit(1).next();
        Theme theme = ThemedBuildPlugin.getJsonMapper().readValue(object.toString(), Theme.class);
        theme.fetchLots();
        return theme;
    } catch (IOException ex) {
        ThemedLogger.getLog().log(Level.SEVERE, ex.getMessage(), ex);
    }
    return null;
}

From source file:co.mcme.themedbuilds.database.DatabaseUtil.java

License:Open Source License

public static Theme getCurrentTheme() {
    try {/*from   w w  w .j ava 2  s . co m*/
        DBCursor cursor = ThemedBuildPlugin.getMongoUtil().getThemeCollection().find();
        DBObject object = cursor.sort(new BasicDBObject("_id", -1)).limit(1).next();
        Theme theme = ThemedBuildPlugin.getJsonMapper().readValue(object.toString(), Theme.class);
        theme.fetchLots();
        return theme;
    } catch (IOException ex) {
        ThemedLogger.getLog().log(Level.SEVERE, ex.getMessage(), ex);
    }
    return null;
}

From source file:co.mcme.themedbuilds.database.DatabaseUtil.java

License:Open Source License

public static Lot getLot(String playerUUID) {
    DBObject query = QueryBuilder.start("owner").is(playerUUID).get();
    try {//  ww  w.j  av a  2  s  .  co  m
        DBCursor cursor = ThemedBuildPlugin.getMongoUtil().getLotCollection().find(query);
        DBObject object = cursor.sort(new BasicDBObject("_id", -1)).limit(1).next();
        Lot lot = ThemedBuildPlugin.getJsonMapper().readValue(object.toString(), Lot.class);
        lot.generateBounds();
        lotCache.put(lot.getCorner(), lot);
        return lot;
    } catch (IOException ex) {
        ThemedLogger.getLog().log(Level.SEVERE, ex.getMessage(), ex);
    }
    return null;
}

From source file:co.mcme.themedbuilds.database.DatabaseUtil.java

License:Open Source License

public static Lot getLot(String playerUUID, ObjectId themeId) {
    DBObject query = QueryBuilder.start("owner").is(playerUUID).and("belongsToTheme").is(themeId).get();
    try {//ww w.  j a v  a2s. c  o m
        DBCursor cursor = ThemedBuildPlugin.getMongoUtil().getLotCollection().find(query);
        DBObject object = cursor.sort(new BasicDBObject("_id", -1)).limit(1).next();
        Lot lot = ThemedBuildPlugin.getJsonMapper().readValue(object.toString(), Lot.class);
        lot.generateBounds();
        lotCache.put(lot.getCorner(), lot);
        return lot;
    } catch (IOException ex) {
        ThemedLogger.getLog().log(Level.SEVERE, ex.getMessage(), ex);
    }
    return null;
}

From source file:co.mcme.themedbuilds.database.DatabaseUtil.java

License:Open Source License

public static PlayerReport getPlayerReport(OfflinePlayer p) {
    DBObject query = QueryBuilder.start("uuid").is(p.getUniqueId().toString()).get();
    try {//from  w w  w .  j av  a2s.c o m
        DBCursor cursor = ThemedBuildPlugin.getMongoUtil().getPlayerCollection().find(query);
        DBObject object = cursor.sort(new BasicDBObject("_id", -1)).limit(1).next();
        PlayerDocument doc = ThemedBuildPlugin.getJsonMapper().readValue(object.toString(),
                PlayerDocument.class);
        PlayerReport report = new PlayerReport(p, doc.getLots(), doc.getLots().get(doc.getLots().size() - 1));
        return report;
    } catch (IOException ex) {
        ThemedLogger.getLog().log(Level.SEVERE, ex.getMessage(), ex);
    }
    return null;
}

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);//  w  w  w  . j  a v a 2s  .co  m
        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.bugull.mongo.BuguQuery.java

License:Apache License

public List<T> results() {
    DBCursor cursor = null;
    if (fieldsSpecified) {
        cursor = coll.find(condition, fields);
    } else {//from ww  w.  j a  va 2 s.c o m
        cursor = coll.find(condition, keys);
    }
    if (orderBy != null) {
        cursor.sort(MapperUtil.getSort(orderBy));
    }
    if (pageNumber > 0 && pageSize > 0) {
        cursor.skip((pageNumber - 1) * pageSize).limit(pageSize);
    }
    return MapperUtil.toList(clazz, cursor);
}