Example usage for com.mongodb BasicDBObject get

List of usage examples for com.mongodb BasicDBObject get

Introduction

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

Prototype

public Object get(final String key) 

Source Link

Document

Gets a value from this object

Usage

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();/*from w  ww.  jav a2  s  .  com*/

    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 {/*from w  ww  . j  ava2s . c  o  m*/
        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  . ja  v  a2 s .  co  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 w w  .  jav a  2  s  . c  o m
        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   ww  w  .  j a  v a 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 !");
    }/*from  w  w  w . j  av  a2  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");
}

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

License:Open Source License

@Resource
@Route("/getMeetingNotes")
public Response.Content getMeetingNotes(String user, String token, String room, String fromTimestamp,
        String toTimestamp, String serverBase) throws IOException {
    if (!tokenService.hasUserWithToken(user, token)) {
        return Response.notFound("Petit malin !");
    }/*from  w w  w .  j  a va  2 s.  com*/

    Long from = null;
    Long to = null;
    String xwiki = "";
    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);

        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();
            }
        }
        xwiki = reportBean.getAsXWiki(serverBase);

    }

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

From source file:org.benjp.services.mongodb.UserServiceImpl.java

License:Open Source License

public void setSpaces(String user, List<SpaceBean> spaces) {
    List<String> spaceIds = new ArrayList<String>();
    DBCollection coll = db().getCollection(M_ROOMS_COLLECTION);
    for (SpaceBean bean : spaces) {
        String room = ChatUtils.getRoomId(bean.getId());
        spaceIds.add(room);/*from w  ww.ja  v a2 s . com*/

        BasicDBObject query = new BasicDBObject();
        query.put("_id", room);
        DBCursor cursor = coll.find(query);
        if (!cursor.hasNext()) {
            BasicDBObject doc = new BasicDBObject();
            doc.put("_id", room);
            doc.put("space_id", bean.getId());
            doc.put("displayName", bean.getDisplayName());
            doc.put("groupId", bean.getGroupId());
            doc.put("shortName", bean.getShortName());
            doc.put("type", ChatService.TYPE_ROOM_SPACE);
            coll.insert(doc);
        } else {
            DBObject doc = cursor.next();
            String displayName = doc.get("displayName").toString();
            if (!bean.getDisplayName().equals(displayName)) {
                doc.put("_id", room);
                doc.put("displayName", bean.getDisplayName());
                doc.put("groupId", bean.getGroupId());
                doc.put("shortName", bean.getShortName());
                coll.save(doc);
            }
        }

    }
    coll = db().getCollection(M_USERS_COLLECTION);
    BasicDBObject query = new BasicDBObject();
    query.put("user", user);
    DBCursor cursor = coll.find(query);
    if (cursor.hasNext()) {
        DBObject doc = cursor.next();
        doc.put("spaces", spaceIds);
        coll.save(doc, WriteConcern.SAFE);
    } else {
        BasicDBObject doc = new BasicDBObject();
        doc.put("_id", user);
        doc.put("user", user);
        doc.put("spaces", spaceIds);
        coll.insert(doc);
    }
}

From source file:org.breizhbeans.thrift.tools.thriftmongobridge.protocol.TBSONUnstackedProtocol.java

License:Apache License

@Override
public TMap readMapBegin() throws TException {
    //System.out.println("readMapBegin");
    // Get the IO Stack
    Stack<ThriftIO> stack = threadSafeSIOStack.get();

    ThriftIO currentIO = stack.peek();/*from  w  w w . ja  v a 2 s . c o  m*/
    ThriftFieldMetadata thriftFieldMetadata = currentIO.fieldsStack.peek();

    // field related to the list
    MapMetaData mapMetaData = (MapMetaData) thriftFieldMetadata.fieldMetaData.valueMetaData;

    // extract the DBMap (BasicDbObject)
    BasicDBObject dbObject = null;
    BasicDBObject securedDObject = null;
    if (thriftFieldMetadata.securedFieldMetaData.isSecured()) {
        // from the mongoIO securedWrap for a secured map
        BasicDBObject securedWrap = (BasicDBObject) currentIO.mongoIO.get("securedwrap");
        securedDObject = (BasicDBObject) securedWrap
                .get(Short.toString(currentIO.fieldsStack.peek().tfield.id));
        dbObject = securedDObject;
    } else {
        // from the mongoIO field for an unsecured map
        dbObject = (BasicDBObject) currentIO.mongoIO.get(currentIO.fieldsStack.peek().tfield.name);
    }

    ThriftIO thriftListIO = null;
    if (mapMetaData.valueMetaData.isStruct()) {
        thriftListIO = new ThriftIO(((StructMetaData) mapMetaData.valueMetaData).structClass, dbObject,
                securedDObject, true, false);
    } else {
        thriftListIO = new ThriftIO(null, dbObject, securedDObject, true, false);
    }
    thriftListIO.mapIterator = dbObject.entrySet().iterator();

    stack.push(thriftListIO);
    threadSafeSIOStack.set(stack);

    return new TMap(TType.STRING, TType.STRING, dbObject.size());
}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

public List<Fields> list(int offset, int count) {
    if (logger.isDebug())
        logger.debug("Listing entities, Database is {0}, Collection is {1}, offset is {2}, count is {3}.",
                getSchema(), getName(), offset, count);
    List<Fields> rlt = new ArrayList<Fields>();

    BasicDBObject options = new BasicDBObject();
    DBCursor cursor = null;/*www.ja v  a 2  s  .c o m*/

    try {
        validateState();

        MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl();
        BasicDBObject projection = new BasicDBObject();
        Limiter limiter = new Limiter.Default();
        BasicDBObject sorter = new BasicDBObject();

        IntentParser.parse(getIntent(), expFactory, null, projection, limiter, sorter, options);

        if (!options.isEmpty())
            prepareOptions(options);

        if (null != getCache()) {// cache
            cursor = getCollection().find(expFactory.toQuery(), new BasicDBObject().append("_id", 1));
        } else {// no cache
            // projection
            if (projection.isEmpty())
                cursor = getCollection().find(expFactory.toQuery());
            else
                cursor = getCollection().find(expFactory.toQuery(), projection);
        }

        // sort
        if (!sorter.isEmpty())
            cursor.sort(sorter);

        if (offset > 0)
            limiter.offset(offset);

        if (count > 0)
            limiter.count(count);

        if (limiter.offset() > 0)
            cursor.skip(limiter.offset());
        if (limiter.count() > 0)
            cursor.limit(limiter.count());

        if (null != getCache()) {
            Map<Object, MongoFields> missedCacheHits = new HashMap<Object, MongoFields>();

            while (cursor.hasNext()) {
                BasicDBObject dbo = (BasicDBObject) cursor.next();
                Object key = dbo.get("_id");
                String cacheKey = getKey().concat("#").concat(key.toString());

                MongoFields ele = null;
                if (getCache().isAlive(cacheKey)) {// load from cache
                    MongoFields mf = (MongoFields) getCache().restore(cacheKey);
                    if (null != mf)
                        ele = mf.clone();// pooling
                }

                if (null != ele && !projection.isEmpty())
                    ele.project(projection.keySet());

                if (null == ele) {
                    ele = new MongoFields(this, getIntent());
                    missedCacheHits.put(key, ele);
                }

                rlt.add(ele);
            }

            // load missed cache hits.
            if (!missedCacheHits.isEmpty()) {
                loadForMissedCacheHits(missedCacheHits, projection.keySet());
                missedCacheHits.clear();
            }

            if (logger.isDebug())
                logger.debug("Listed entities hit cache ...");
        } else {
            while (cursor.hasNext()) {
                BasicDBObject dbo = (BasicDBObject) cursor.next();

                rlt.add(new MongoFields(this, getIntent(), dbo));
            }

            if (logger.isDebug())
                logger.debug("Listed entities ...");
        }

        return rlt;
    } catch (AnalyzeBehaviourException abe) {
        if (logger.isDebug())
            logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage());

        throw new RuntimeException(abe);
    } finally {
        if (!options.getBoolean(Options.RETAIN))
            getIntent().reset();

        if (cursor != null)
            cursor.close();
    }
}