Example usage for com.mongodb DBCollection getFullName

List of usage examples for com.mongodb DBCollection getFullName

Introduction

In this page you can find the example usage for com.mongodb DBCollection getFullName.

Prototype

public String getFullName() 

Source Link

Document

Get the full name of a collection, with the database name as a prefix.

Usage

From source file:com.andreig.jetty.WriteServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doPost()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/*ww w. j a v  a  2 s .c  o  m*/
        return;
    }

    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;
        }
    }

    boolean upsert = Boolean.parseBoolean(req.getParameter("upsert"));
    boolean multi = Boolean.parseBoolean(req.getParameter("multi"));

    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);

    BufferedReader r = null;
    DBObject q = null, o = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String q_s = r.readLine();
        if (q_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        String o_s = r.readLine();
        if (o_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("obj to update missing"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(q_s);
            o = (DBObject) JSON.parse(o_s);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }
    //
    // search
    if (do_search) {

        String fn = col.getFullName();
        DBCursor c = col.find(q);
        int cnt = c.count();
        if (!multi)
            c.limit(1);
        long l = multi ? cnt : 1;
        String toupdate[] = new String[(int) l];
        int n = 0;
        boolean insert = false;

        if (upsert && !multi && cnt == 0)
            insert = true;

        while (c.hasNext()) {

            DBObject _o = c.next();
            ObjectId oid = (ObjectId) _o.get("_id");
            String id = oid.toStringMongod();
            toupdate[n++] = id;

        }
        c.close();

        List<String> flds = Config.search_index_fields.get(fn);
        boolean commit = false;
        Document doc = null;
        Search _writer = search.get_writer();
        if (flds != null && flds.size() > 0) {
            doc = new Document();
            try {
                for (String fld : flds) {
                    String val = (String) o.get(fld);
                    if (val == null)
                        continue;
                    Search.add_searchable_s(doc, fld, val);
                    commit = true;
                }
                if (commit)
                    _writer.commit(doc);
            } catch (ClassCastException e) {
                error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String"));
                return;
            } catch (CorruptIndexException e) {
                error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e));
                return;
            }
        }
        if (commit && insert)
            log.warning("upsert with search not implemented yet");
        else
            _writer.update(toupdate, doc);

    }

    WriteResult wr = col.update(q, o, upsert, multi, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_CREATED);

}

From source file:com.andreig.jetty.WriteServlet.java

License:GNU General Public License

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doPut()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from   w  ww  .j av a2 s .co m*/
        return;
    }

    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;
        }
    }
    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);

    BufferedReader r = null;
    ArrayList<DBObject> ar = new ArrayList<DBObject>();
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data;
        while ((data = r.readLine()) != null) {
            if (data != null) {
                DBObject o;
                try {
                    o = (DBObject) JSON.parse(data);
                    ar.add(o);
                } catch (JSONParseException e) {
                    error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
                    return;
                }
            }
        }

    } finally {
        if (r != null)
            r.close();
    }

    if (ar.size() == 0) {
        error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
        return;
    }

    WriteResult wr = col.insert(ar, write_concern);

    // search
    if (do_search) {
        String fn = col.getFullName();
        List<String> flds = Config.search_index_fields.get(fn);
        if (flds != null && flds.size() > 0) {
            Search _writer = search.get_writer();
            try {
                for (DBObject o : ar) {
                    boolean commit = false;
                    Document doc = new Document();
                    for (String fld : flds) {
                        String val = (String) o.get(fld);
                        if (val == null)
                            continue;
                        Search.add_searchable_s(doc, fld, val);
                        commit = true;
                    }
                    if (commit) {
                        ObjectId id = (ObjectId) o.get("_id");
                        String sid = id.toStringMongod();
                        Search.add_storable(doc, "_id", sid);
                        Search.add_searchable_s(doc, "_dbid_", fn);
                        _writer.commit(doc);
                    }
                }
            } catch (ClassCastException e) {
                error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String"));
                return;
            } catch (CorruptIndexException e) {
                error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e));
                return;
            }
        }
    }

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_CREATED);

}

From source file:com.bosscs.spark.mongodb.extractor.MongoNativeExtractor.java

License:Apache License

/**
 * Is sharded collection./* ww  w  . j a  v a  2  s .  co m*/
 *
 * @param collection the collection
 * @return the boolean
 */
private boolean isShardedCollection(DBCollection collection) {

    DB config = collection.getDB().getMongo().getDB("config");
    DBCollection configCollections = config.getCollection("collections");

    DBObject dbObject = configCollections
            .findOne(new BasicDBObject(MONGO_DEFAULT_ID, collection.getFullName()));
    return dbObject != null;
}

From source file:com.bosscs.spark.mongodb.extractor.MongoNativeExtractor.java

License:Apache License

/**
 * Gets chunks./*from  www.j a v  a2 s .  co  m*/
 *
 * @param collection the collection
 * @return the chunks
 */
private DBCursor getChunks(DBCollection collection) {
    DB config = collection.getDB().getSisterDB("config");
    DBCollection configChunks = config.getCollection("chunks");
    return configChunks.find(new BasicDBObject("ns", collection.getFullName()));
}

From source file:com.bosscs.spark.mongodb.extractor.MongoNativeExtractor.java

License:Apache License

/**
 * Gets split data./*from  w  w w .j av  a2  s  .c o m*/
 *
 * @param collection the collection
 * @return the split data
 */
private BasicDBList getSplitData(DBCollection collection) {

    final DBObject cmd = BasicDBObjectBuilder.start("splitVector", collection.getFullName())
            .add("keyPattern", new BasicDBObject(MONGO_DEFAULT_ID, 1)).add("force", false)
            .add("maxChunkSize", splitSize).get();

    CommandResult splitVectorResult = collection.getDB().getSisterDB("admin").command(cmd);
    return (BasicDBList) splitVectorResult.get(SPLIT_KEYS);

}

From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPost()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from w  w  w  .  j a  v  a 2  s .  c o  m*/
        return;
    }

    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;
        }
    }

    boolean upsert = Boolean.parseBoolean(req.getParameter("upsert"));
    boolean multi = Boolean.parseBoolean(req.getParameter("multi"));

    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);

    BufferedReader r = null;
    DBObject q = null, o = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String q_s = r.readLine();
        if (q_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        String o_s = r.readLine();
        if (o_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("obj to update missing"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(q_s);
            o = (DBObject) JSON.parse(o_s);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }
    //
    // search
    if (do_search) {

        String fn = col.getFullName();
        DBCursor c = col.find(q);
        int cnt = c.count();
        if (!multi)
            c.limit(1);
        long l = multi ? cnt : 1;
        String toupdate[] = new String[(int) l];
        int n = 0;
        boolean insert = false;

        if (upsert && !multi && cnt == 0)
            insert = true;

        while (c.hasNext()) {

            DBObject _o = c.next();
            ObjectId oid = (ObjectId) _o.get("_id");
            String id = oid.toStringMongod();
            toupdate[n++] = id;

        }
        c.close();

        List<String> flds = Config.search_index_fields.get(fn);
        boolean commit = false;
        Document doc = null;
        Search _writer = search.get_writer();
        if (flds != null && flds.size() > 0) {
            doc = new Document();
            try {
                for (String fld : flds) {
                    String val = (String) o.get(fld);
                    if (val == null)
                        continue;
                    _writer.add_searchable_s(doc, fld, val);
                    commit = true;
                }
                if (commit)
                    _writer.commit(doc);
            } catch (ClassCastException e) {
                error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String"));
                return;
            } catch (CorruptIndexException e) {
                error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e));
                return;
            }
        }
        if (commit && insert)
            log.warn("upsert with search not implemented yet");
        else
            _writer.update(toupdate, doc);

    }

    WriteResult wr = col.update(q, o, upsert, multi, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_CREATED);

}

From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java

License:GNU General Public License

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPut()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from   ww w. ja v  a 2 s  . c  om*/
        return;
    }

    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;
        }
    }
    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);

    BufferedReader r = null;
    ArrayList<DBObject> ar = new ArrayList<DBObject>();
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data;
        while ((data = r.readLine()) != null) {
            if (data != null) {
                DBObject o;
                try {
                    o = (DBObject) JSON.parse(data);
                    ar.add(o);
                } catch (JSONParseException e) {
                    error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
                    return;
                }
            }
        }

    } finally {
        if (r != null)
            r.close();
    }

    if (ar.size() == 0) {
        error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
        return;
    }

    WriteResult wr = col.insert(ar, write_concern);

    // search
    if (do_search) {
        String fn = col.getFullName();
        List<String> flds = Config.search_index_fields.get(fn);
        if (flds != null && flds.size() > 0) {
            Search _writer = search.get_writer();
            try {
                for (DBObject o : ar) {
                    boolean commit = false;
                    Document doc = new Document();
                    for (String fld : flds) {
                        String val = (String) o.get(fld);
                        if (val == null)
                            continue;
                        _writer.add_searchable_s(doc, fld, val);
                        commit = true;
                    }
                    if (commit) {
                        ObjectId id = (ObjectId) o.get("_id");
                        String sid = id.toStringMongod();
                        _writer.add_storable(doc, "_id", sid);
                        _writer.add_searchable_s(doc, "_dbid_", fn);
                        _writer.commit(doc);
                    }
                }
            } catch (ClassCastException e) {
                error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String"));
                return;
            } catch (CorruptIndexException e) {
                error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e));
                return;
            }
        }
    }

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_CREATED);

}

From source file:com.ebay.cloud.cms.dal.persistence.MongoExecutor.java

License:Apache License

private static void logMongoAction(PersistenceContext context, String operName, long start,
        DBCollection dbCollection, DBObject queryObject, DBObject bodyObject, SearchOption option,
        Integer queryResultSize, String statusMsg) {
    long end = System.currentTimeMillis();
    long cost = end - start; //mili seconds

    //recording the time cost in mongo DB
    context.addDBTimeCost(cost);// w  w  w.ja  va 2  s . c  o  m

    if (logger.isDebugEnabled()) {

        String costStr = Long.toString(cost);
        String queryObjectStr = "{}";
        if (queryObject != null) {
            queryObjectStr = queryObject.toString();
        }
        String bodyObjectStr = "{}";
        if (bodyObject != null) {
            bodyObjectStr = bodyObject.toString();
        }
        String sortObjectStr = "{}";
        if (option != null && option.hasSort()) {
            sortObjectStr = option.getSort().toString();
        }
        StringBuilder optionBuilder = new StringBuilder("{");
        if (option != null && (option.hasSkip() || option.hasLimit())) {
            optionBuilder.append("\"skip\" : ");
            optionBuilder.append(option.getSkip());
            optionBuilder.append(", \"limit\" : ");
            optionBuilder.append(option.getLimit());
        }
        optionBuilder.append("}");

        StringBuilder readPref = new StringBuilder("{");
        StringBuilder writeCon = new StringBuilder("{");
        String dbName = "";
        String[] args;
        if (dbCollection != null) {
            readPref.append(dbCollection.getReadPreference().getName());
            writeCon.append(dbCollection.getWriteConcern().toString());
            dbName = dbCollection.getFullName();
        }
        readPref.append("}");
        writeCon.append("}");

        StringBuilder queryResult = new StringBuilder();
        if (queryResultSize != null) {
            queryResult.append("queryResultSize=").append(queryResultSize);
        }

        args = new String[] { operName, statusMsg, costStr, dbName, queryObjectStr, bodyObjectStr,
                sortObjectStr, optionBuilder.toString(), readPref.toString(), writeCon.toString(),
                queryResult.toString() };
        logger.debug(
                "operation={}|status={}|cost={}ms|collection={}|query={}|body={}|sort={}|option={}|readPrefernce={}|writeConcern={}|{}",
                args);
    }
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

@Override
protected void updateComponentCustom(JPanel old) {
    try {/*  w  w  w  .  j  av a2 s  .c  om*/
        DBCollection collection = getCollectionNode().getCollection();
        setStringFieldValue(Item.name, collection.getName());
        setStringFieldValue(Item.fullName, collection.getFullName());
        setStringFieldValue(Item.queryOptions, MongoUtils.queryOptionsToString(collection.getOptions()));
        ((DocField) getBoundUnit(Item.writeConcern)).setDoc(collection.getWriteConcern().getCommand());
        ((DocField) getBoundUnit(Item.readPreference)).setDoc(collection.getReadPreference().toDBObject());
        ((CmdField) getBoundUnit(Item.stats)).updateFromCmd(collection);
    } catch (Exception e) {
        UMongo.instance.showError(this.getClass().getSimpleName() + " update", e);
    }
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

public void find(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final DBObject query = ((DocBuilderField) getBoundUnit(Item.findQuery)).getDBObject();
    final DBObject fields = ((DocBuilderField) getBoundUnit(Item.findFields)).getDBObject();
    final DBObject sort = ((DocBuilderField) getBoundUnit(Item.findSort)).getDBObject();
    final DBObject hint = ((DocBuilderField) getBoundUnit(Item.findHint)).getDBObject();
    final int skip = getIntFieldValue(Item.findSkip);
    final int limit = getIntFieldValue(Item.findLimit);
    final int batchSize = getIntFieldValue(Item.findBatchSize);
    final boolean explain = getBooleanFieldValue(Item.findExplain);
    final boolean export = getBooleanFieldValue(Item.findExport);

    if (export) {
        exportToFile(col, query, fields, sort, skip, limit, batchSize);
    } else {/*from  w ww . j a  v a  2 s  .  c om*/
        new DbJob() {
            @Override
            public Object doRun() {
                // this does not actually block, may not need dbjob
                DBCursor cur = col.find(query, fields, skip, batchSize);
                if (sort != null) {
                    cur.sort(sort);
                }
                if (limit > 0) {
                    cur.limit(limit);
                }
                if (hint != null) {
                    cur.hint(hint);
                }
                if (explain) {
                    return cur.explain();
                }

                // force cursor to start
                cur.hasNext();
                return cur;
            }

            @Override
            public String getNS() {
                return col.getFullName();
            }

            @Override
            public String getShortName() {
                return "Find";
            }

            @Override
            public DBObject getRoot(Object result) {
                if (result == null || !(result instanceof DBCursor)) {
                    return null;
                }
                DBCursor res = (DBCursor) result;
                BasicDBObject obj = new BasicDBObject("cursorId", res.getCursorId());
                obj.put("server", res.getServerAddress().toString());
                obj.put("query", res.getQuery());
                obj.put("fields", res.getKeysWanted());
                obj.put("options", res.getOptions());
                obj.put("readPreference", res.getReadPreference().toDBObject());
                obj.put("numSeen", res.numSeen());
                obj.put("numGetMores", res.numGetMores());
                // want skip, limit, batchsize
                return obj;
            }

            @Override
            public ButtonBase getButton() {
                return button;
            }
        }.addJob();

    }
}