Example usage for com.mongodb BasicDBObject containsField

List of usage examples for com.mongodb BasicDBObject containsField

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject containsField.

Prototype

public boolean containsField(final String field) 

Source Link

Document

Checks if this object contains a given field

Usage

From source file:org.aw20.mongoworkbench.command.MapReduceMongoCommand.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override/*  www . ja  v a2s. c o  m*/
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("mapreduceArgs"))
        throw new Exception("no mapReduce document");

    DBCollection collection = db.getCollection(sColl);

    // Build the Map
    BasicDBObject options = (BasicDBObject) ((BasicDBList) cmdMap.get("mapreduceArgs")).get(2);

    String outputCollection = null;
    String outputDB = null;
    MapReduceCommand.OutputType outputType = MapReduceCommand.OutputType.INLINE;

    if (options.get("out") instanceof String) {
        outputCollection = (String) options.get("out");
        outputType = MapReduceCommand.OutputType.REPLACE;
    } else if (options.get("out") instanceof BasicDBObject) {
        BasicDBObject out = (BasicDBObject) options.get("out");

        if (out.containsField("inline")) {
            outputCollection = null;
        } else if (out.containsField("replace")) {
            outputCollection = (String) out.get("replace");
            outputType = MapReduceCommand.OutputType.REPLACE;
        } else if (out.containsField("merge")) {
            outputCollection = (String) out.get("merge");
            outputType = MapReduceCommand.OutputType.MERGE;
        } else if (out.containsField("reduce")) {
            outputCollection = (String) out.get("reduce");
            outputType = MapReduceCommand.OutputType.REDUCE;
        }

        if (out.containsField("db"))
            outputDB = (String) out.get("db");
    }

    MapReduceCommand mrc = new MapReduceCommand(collection,
            ((Code) ((BasicDBList) cmdMap.get("mapreduceArgs")).get(0)).getCode(),
            ((Code) ((BasicDBList) cmdMap.get("mapreduceArgs")).get(1)).getCode(), outputCollection, outputType,
            (BasicDBObject) options.get("query"));

    if (outputDB != null)
        mrc.setOutputDB(outputDB);

    if (options.containsField("sort") && options.get("sort") instanceof DBObject)
        mrc.setSort((DBObject) options.get("sort"));

    if (options.containsField("scope") && options.get("scope") instanceof DBObject)
        mrc.setScope(((DBObject) options.get("scope")).toMap());

    if (options.containsField("finalize") && options.get("scope") instanceof Code)
        mrc.setFinalize(((Code) options.get("scope")).getCode());

    if (options.containsField("limit"))
        mrc.setLimit(StringUtil.toInteger(options.get("limit"), -1));

    mrc.addExtraOption("jsMode", StringUtil.toBoolean(options.get("jsMode"), false));
    mrc.setVerbose(StringUtil.toBoolean(options.get("verbose"), false));

    // Run the actual mapreduce function
    MapReduceOutput mro = collection.mapReduce(mrc);

    // Pull the inline results
    if (mro.getOutputCollection() == null) {
        dbListResult = new BasicDBList();
        Iterable<DBObject> it = mro.results();
        for (DBObject dbo : it) {
            dbListResult.add(dbo);
        }
    }

    BasicDBObject dbo = mro.getRaw();
    StringBuilder sb = new StringBuilder();

    if (dbo.containsField("timeMillis"))
        sb.append("Time=").append(dbo.get("timeMillis")).append("ms; ");

    if (dbo.containsField("counts")) {
        BasicDBObject counts = (BasicDBObject) dbo.get("counts");
        sb.append("Counts: input=" + counts.get("input"));
        sb.append("; emit=" + counts.get("emit"));
        sb.append("; reduce=" + counts.get("reduce"));
        sb.append("; output=" + counts.get("output"));
    }

    setMessage(sb.toString());
}

From source file:org.aw20.mongoworkbench.command.RemoveMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);//from w  ww .ja va2s  . c o  m
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("removeArgs"))
        throw new Exception("no remove document");

    DBCollection collection = db.getCollection(sColl);

    BasicDBList args = (BasicDBList) cmdMap.get("removeArgs");

    // Run the command
    db.requestStart();
    WriteResult writeresult;
    try {
        writeresult = collection.remove((DBObject) args.get(0), WriteConcern.JOURNAL_SAFE);
    } finally {
        db.requestDone();
    }

    // Get the result
    Map mwriteresult = (Map) JSON.parse(writeresult.toString());
    mwriteresult.put("exeDate", new Date());

    EventWorkBenchManager.getInst().onEvent(Event.WRITERESULT, mwriteresult);

    setMessage("Removed");
}

From source file:org.aw20.mongoworkbench.command.SaveMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);//from  w  ww. j a  va2 s  .c  om
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("saveArg"))
        throw new Exception("no save document");

    DBObject document = fixNumbers((BasicDBObject) cmdMap.get("saveArg"));
    DBCollection collection = db.getCollection(sColl);

    // Run the command
    db.requestStart();
    WriteResult writeresult;
    try {
        writeresult = collection.save(document, WriteConcern.JOURNAL_SAFE);
        id = document.get("_id");
    } finally {
        db.requestDone();
    }

    // Get the result
    Map mwriteresult = (Map) JSON.parse(writeresult.toString());
    mwriteresult.put("exeDate", new Date());

    EventWorkBenchManager.getInst().onEvent(Event.WRITERESULT, mwriteresult);

    setMessage("Saved: updatedExisting=" + mwriteresult.get("updatedExisting") + "; documentsUpdated="
            + mwriteresult.get("n"));
}

From source file:org.aw20.mongoworkbench.command.UpdateMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);/*from  ww  w.  j  a  v a  2  s  . c o  m*/
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("updateArg"))
        throw new Exception("no update document");

    List argList = (List) cmdMap.get("updateArg");
    if (argList.size() == 1)
        throw new Exception("not enough parameters; db.collection.update(query, update, <upsert>, <multi>)");

    DBCollection collection = db.getCollection(sColl);

    db.requestStart();
    WriteResult writeresult = null;
    try {

        if (argList.size() == 2) {

            writeresult = collection.update((DBObject) argList.get(0),
                    fixNumbers((BasicDBObject) argList.get(1)));

        } else if (argList.size() == 3) {

            boolean upsert = StringUtil.toBoolean(argList.get(2), false);
            writeresult = collection.update((DBObject) argList.get(0),
                    fixNumbers((BasicDBObject) argList.get(1)), upsert, false);

        } else if (argList.size() == 4) {

            boolean upsert = StringUtil.toBoolean(argList.get(2), false);
            boolean multi = StringUtil.toBoolean(argList.get(3), false);
            writeresult = collection.update((DBObject) argList.get(0),
                    fixNumbers((BasicDBObject) argList.get(1)), upsert, multi);

        } else
            throw new Exception("too many parameters; db.collection.update(query, update, <upsert>, <multi>)");

    } finally {
        db.requestDone();
    }

    // Get the result
    Map mwriteresult = (Map) JSON.parse(writeresult.toString());
    mwriteresult.put("exeDate", new Date());

    EventWorkBenchManager.getInst().onEvent(Event.WRITERESULT, mwriteresult);

    setMessage("Updated: updatedExisting=" + mwriteresult.get("updatedExisting") + "; documentsUpdated="
            + mwriteresult.get("n"));
}

From source file:org.aw20.mongoworkbench.eclipse.view.wizard.AggregateWizard.java

License:Open Source License

@Override
public boolean onWizardCommand(MongoCommand cmd, BasicDBObject dbo) {
    if (!cmd.getClass().getName().equals(AggregateMongoCommand.class.getName()))
        return false;

    if (!dbo.containsField("aggregateArg"))
        return false;

    BasicDBList args = (BasicDBList) dbo.get("aggregateArg");
    if (args.size() == 0)
        return false;

    // remove all the tabs
    while (tabFolder.getItemCount() > 0)
        tabFolder.getItem(0).dispose();/*w  ww  .  j  a  v a  2 s .  c o m*/

    for (int x = 0; x < args.size(); x++) {
        TabItem tbtmPipe = new TabItem(tabFolder, SWT.NONE);
        tbtmPipe.setText("Pipe#" + (x + 1));
        Text textPipe = MSwtUtil.createText(tabFolder);
        textPipe.setText(JSONFormatter.format(args.get(x)));
        tbtmPipe.setControl(textPipe);
    }

    if (tabFolder.getItemCount() > 1)
        btnRemovePipe.setEnabled(true);
    else
        btnRemovePipe.setEnabled(false);

    return true;
}

From source file:org.aw20.mongoworkbench.eclipse.view.wizard.FindWizard.java

License:Open Source License

@Override
public boolean onWizardCommand(MongoCommand cmd, BasicDBObject dbo) {
    if (!cmd.getClass().getName().equals(FindMongoCommand.class.getName()))
        return false;

    if (!dbo.containsField("findArg"))
        return false;

    BasicDBList dbList = (BasicDBList) dbo.get("findArg");

    if (dbList.size() == 1) {
        textKeys.setText("");
        textQuery.setText(JSONFormatter.format(dbList.get(0)));
    } else if (dbList.size() == 2) {
        textKeys.setText(JSONFormatter.format(dbList.get(1)));
        textQuery.setText(JSONFormatter.format(dbList.get(0)));
    } else {// ww  w.  j a  v  a2s. com
        textKeys.setText("");
        textQuery.setText("");
    }

    if (dbo.containsField("sort")) {
        textSort.setText(JSONFormatter.format(dbo.get("sort")));
    } else {
        textSort.setText("");
    }

    return true;
}

From source file:org.aw20.mongoworkbench.eclipse.view.wizard.GroupWizard.java

License:Open Source License

@Override
public boolean onWizardCommand(MongoCommand cmd, BasicDBObject dbo) {
    if (!cmd.getClass().getName().equals(GroupMongoCommand.class.getName()))
        return false;

    if (!dbo.containsField("groupArg"))
        return false;

    DBObject gmap = (DBObject) dbo.get("groupArg");

    if (gmap.containsField("cond")) {
        textGroupCondition.setText(JSONFormatter.format(gmap.get("cond")));
    } else {/*from   ww w  .  j  a v  a 2s . c o m*/
        textGroupCondition.setText("");
    }

    if (gmap.containsField("initial")) {
        textGroupInitial.setText(JSONFormatter.format(gmap.get("initial")));
    } else {
        textGroupInitial.setText("");
    }

    if (gmap.containsField("key")) {
        textGroupKey.setText(JSONFormatter.format(gmap.get("key")));
    } else {
        textGroupKey.setText("");
    }

    if (gmap.containsField("keyf")) {
        org.bson.types.Code c = (org.bson.types.Code) gmap.get("key");
        textGroupKeyF.setText(c.toString());
    } else {
        textGroupKeyF.setText("");
    }

    if (gmap.containsField("reduce")) {
        org.bson.types.Code c = (org.bson.types.Code) gmap.get("reduce");
        textGroupReduce.setText(c.toString());
    } else {
        textGroupReduce.setText("");
    }

    if (gmap.containsField("finalize")) {
        org.bson.types.Code c = (org.bson.types.Code) gmap.get("finalize");
        textGroupFinalize.setText(c.toString());
    } else {
        textGroupFinalize.setText("");
    }

    return true;
}

From source file:org.aw20.mongoworkbench.eclipse.view.wizard.MapReduceWizard.java

License:Open Source License

@Override
public boolean onWizardCommand(MongoCommand cmd, BasicDBObject dbo) {
    if (!cmd.getClass().getName().equals(MapReduceMongoCommand.class.getName()))
        return false;

    if (!dbo.containsField("mapreduceArgs"))
        return false;

    BasicDBList dbList = (BasicDBList) dbo.get("mapreduceArgs");

    BasicDBObject options = (BasicDBObject) dbList.get(2);

    // Input section
    if (options.containsField("query")) {
        textMRQuery.setText(JSONFormatter.format(options.get("query")));
    } else {//w  ww. j  av a  2  s  .  c om
        textMRQuery.setText("");
    }

    if (options.containsField("sort")) {
        textMRSort.setText(JSONFormatter.format(options.get("sort")));
    } else {
        textMRSort.setText("");
    }

    if (options.containsField("limit")) {
        textMRLimit.setText((String) options.get("sort"));
    } else {
        textMRLimit.setText("");
    }

    // Scope section
    if (options.containsField("scope")) {
        textMRScope.setText(JSONFormatter.format(options.get("scope")));
    } else {
        textMRScope.setText("");
    }

    // Map section
    textMRMap.setText(((Code) (dbList.get(0))).getCode());

    // Reduce Section
    textMRReduce.setText(((Code) (dbList.get(1))).getCode());

    // Finalize
    if (options.containsField("finalize")) {
        textMRFinalize.setText(((Code) options.get("finalize")).getCode());
    } else {
        textMRFinalize.setText("");
    }

    // Output section
    combo.select(0);
    textMRCollection.setText("");
    textMRDatabase.setText("");
    btnSharded.setSelection(false);
    btnJsmode.setSelection(false);
    btnNonatomic.setSelection(false);
    btnVerbose.setSelection(false);

    if (options.get("out") instanceof String) {
        textMRCollection.setText((String) options.get("out"));
    } else if (options.get("out") instanceof BasicDBObject) {
        BasicDBObject out = (BasicDBObject) options.get("out");

        if (out.containsField("inline")) {
        } else if (out.containsField("replace")) {
            combo.select(1);
            textMRCollection.setText((String) out.get("replace"));
        } else if (out.containsField("merge")) {
            combo.select(2);
            textMRCollection.setText((String) out.get("merge"));
        } else if (out.containsField("reduce")) {
            combo.select(3);
            textMRCollection.setText((String) out.get("reduce"));
        }

        if (out.containsField("sharded"))
            btnSharded.setSelection(StringUtil.toBoolean(out.get("sharded"), false));

        if (out.containsField("nonAtomic"))
            btnNonatomic.setSelection(StringUtil.toBoolean(out.get("nonAtomic"), false));

        if (out.containsField("db"))
            textMRDatabase.setText((String) out.get("db"));
    }

    if (options.containsField("jsMode"))
        btnJsmode.setSelection(StringUtil.toBoolean(options.get("jsMode"), false));

    if (options.containsField("verbose"))
        btnVerbose.setSelection(StringUtil.toBoolean(options.get("verbose"), false));

    return true;
}

From source file:org.aw20.mongoworkbench.eclipse.view.wizard.UpdateWizard.java

License:Open Source License

@Override
public boolean onWizardCommand(MongoCommand cmd, BasicDBObject dbo) {
    if (!cmd.getClass().getName().equals(UpdateMongoCommand.class.getName()))
        return false;

    if (!dbo.containsField("updateArg"))
        return false;

    BasicDBList list = (BasicDBList) dbo.get("updateArg");

    // Set the fields of the wizard from the command
    textUpdateQuery.setText(JSONFormatter.format(((BasicDBObject) list.get(0)).toMap()));
    textUpdateUpdate.setText(JSONFormatter.format(((BasicDBObject) list.get(1)).toMap()));

    if (list.size() >= 3)
        btnUpdateUpsert.setSelection(StringUtil.toBoolean(list.get(2), false));
    else/*from w  w w  .j a  va 2  s  .c o  m*/
        btnUpdateUpsert.setSelection(false);

    if (list.size() >= 4)
        btnUpdateMulti.setSelection(StringUtil.toBoolean(list.get(3), false));
    else
        btnUpdateMulti.setSelection(false);

    return true;
}

From source file:org.benjp.server.ChatServer.java

License:Open Source License

@Resource
@Route("/sendMeetingNotes")
public Response.Content sendMeetingNotes(String user, String token, String room, String fromTimestamp,
        String toTimestamp) throws IOException {
    if (!tokenService.hasUserWithToken(user, token)) {
        return Response.notFound("Petit malin !");
    }//w w  w. ja  va  2 s . c  o  m

    Long from = null;
    Long to = null;
    String html = "";
    try {
        if (fromTimestamp != null && !"".equals(fromTimestamp))
            from = Long.parseLong(fromTimestamp);
    } catch (NumberFormatException nfe) {
        log.info("fromTimestamp is not a valid Long number");
    }
    try {
        if (toTimestamp != null && !"".equals(toTimestamp))
            to = Long.parseLong(toTimestamp);
    } catch (NumberFormatException nfe) {
        log.info("fromTimestamp is not a valid Long number");
    }
    String data = chatService.read(room, userService, false, from, to);
    BasicDBObject datao = (BasicDBObject) JSON.parse(data);
    if (datao.containsField("messages")) {
        List<UserBean> users = userService.getUsers(room);
        ReportBean reportBean = new ReportBean();
        reportBean.fill((BasicDBList) datao.get("messages"), users);

        ArrayList<String> tos = new ArrayList<String>();
        String senderFullname = user;
        for (UserBean userBean : users) {
            if (!"".equals(userBean.getEmail())) {
                tos.add(userBean.getEmail());
            }
            if (user.equals(userBean.getName())) {
                senderFullname = userBean.getFullname();
            }
        }

        String roomName = "";
        List<SpaceBean> spaces = userService.getSpaces(user);
        for (SpaceBean spaceBean : spaces) {
            if (room.equals(spaceBean.getRoom())) {
                roomName = spaceBean.getDisplayName();
            }
        }
        List<RoomBean> roomBeans = userService.getTeams(user);
        for (RoomBean roomBean : roomBeans) {
            if (room.equals(roomBean.getRoom())) {
                roomName = roomBean.getFullname();
            }
        }
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String date = formatter.format(new GregorianCalendar().getTime());
        String title = roomName + " : Meeting Notes [" + date + "]";
        html = reportBean.getAsHtml(title);

        try {
            sendMailWithAuth(senderFullname, tos, html.toString(), title);
        } catch (Exception e) {
            log.info(e.getMessage());
        }

    }

    return Response.ok("sent").withMimeType("text/event-stream; charset=UTF-8").withHeader("Cache-Control",
            "no-cache");
}