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:com.jive.myco.seyren.mongo.MongoMapper.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
private Map propertiesToMap(Check check) {
    Map map = new HashMap();
    map.put("_id", check.getId());
    map.put("name", check.getName());
    map.put("description", check.getDescription());
    map.put("target", check.getTarget());
    if (check.getWarn() != null) {
        map.put("warn", check.getWarn().toPlainString());
    }/* w w w.ja v  a 2 s.  c  om*/
    if (check.getError() != null) {
        map.put("error", check.getError().toPlainString());
    }
    map.put("enabled", check.isEnabled());
    map.put("live", check.isLive());
    map.put("state", check.getState().toString());
    if (check.getLastCheck() != null) {
        map.put("lastCheck", new Date(check.getLastCheck().getMillis()));
    }
    if (check.getSubscriptions() != null && !check.getSubscriptions().isEmpty()) {
        final ArrayList<DBObject> dbSubscriptions = new ArrayList<DBObject>();
        for (Subscription s : check.getSubscriptions()) {
            final BasicDBObject dbObject = new BasicDBObject(propertiesToMap(s));
            if (dbObject.get("_id") == null) {
                dbObject.put("_id", new ObjectId().toHexString());
            }
            dbSubscriptions.add(dbObject);
        }

        map.put("subscriptions", dbSubscriptions);
    }
    return map;
}

From source file:com.liferay.mongodb.hook.service.impl.MongoExpandoValueLocalServiceImpl.java

License:Open Source License

protected ExpandoValue toExpandoValue(BasicDBObject expandoValueDBObject, ExpandoColumn expandoColumn)
        throws PortalException {

    ExpandoValue expandoValue = ExpandoValueUtil.create(0);

    expandoValue.setCompanyId(expandoValueDBObject.getLong("companyId"));
    expandoValue.setTableId(expandoValueDBObject.getLong("tableId"));
    expandoValue.setColumnId(expandoColumn.getColumnId());
    expandoValue.setRowId(expandoValueDBObject.getLong("rowId"));
    expandoValue.setClassNameId(expandoValueDBObject.getLong("classNameId"));
    expandoValue.setClassPK(expandoValueDBObject.getLong("classPK"));

    Object value = expandoValueDBObject.get(expandoColumn.getName());

    if (value == null) {
        return expandoValue;
    }//  www  .  j a v a  2  s  .  c  om

    int type = expandoColumn.getType();

    if (type == ExpandoColumnConstants.BOOLEAN) {
        expandoValue.setBoolean((Boolean) value);
    } else if (type == ExpandoColumnConstants.BOOLEAN_ARRAY) {
        List<Boolean> list = (List<Boolean>) value;

        expandoValue.setBooleanArray(ArrayUtil.toArray(list.toArray(new Boolean[list.size()])));
    } else if (type == ExpandoColumnConstants.DATE) {
        expandoValue.setDate((Date) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.DATE_ARRAY) {
        List<Date> list = (List<Date>) value;

        expandoValue.setDateArray(list.toArray(new Date[list.size()]));
    } else if (type == ExpandoColumnConstants.DOUBLE) {
        expandoValue.setDouble((Double) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.DOUBLE_ARRAY) {
        List<Double> list = (List<Double>) value;

        expandoValue.setDoubleArray(ArrayUtil.toArray(list.toArray(new Double[list.size()])));
    } else if (type == ExpandoColumnConstants.FLOAT) {
        expandoValue.setFloat((Float) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.FLOAT_ARRAY) {
        List<Float> list = (List<Float>) value;

        expandoValue.setFloatArray(ArrayUtil.toArray(list.toArray(new Float[list.size()])));
    } else if (type == ExpandoColumnConstants.INTEGER) {
        expandoValue.setInteger((Integer) value);
    } else if (type == ExpandoColumnConstants.INTEGER_ARRAY) {
        List<Integer> list = (List<Integer>) value;

        expandoValue.setIntegerArray(ArrayUtil.toArray(list.toArray(new Integer[list.size()])));
    } else if (type == ExpandoColumnConstants.LONG) {
        expandoValue.setLong((Long) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.LONG_ARRAY) {
        List<Long> list = (List<Long>) value;

        expandoValue.setLongArray(ArrayUtil.toArray(list.toArray(new Long[list.size()])));
    } else if (type == ExpandoColumnConstants.SHORT) {
        expandoValue.setShort((Short) expandoValueDBObject.get(expandoColumn.getName()));
    } else if (type == ExpandoColumnConstants.SHORT_ARRAY) {
        List<Short> list = (List<Short>) value;

        expandoValue.setShortArray(ArrayUtil.toArray(list.toArray(new Short[list.size()])));
    } else if (type == ExpandoColumnConstants.STRING_ARRAY) {
        List<String> list = (List<String>) value;

        expandoValue.setStringArray(list.toArray(new String[list.size()]));
    } else {
        expandoValue.setString((String) value);
    }

    return expandoValue;
}

From source file:com.linuxbox.enkive.imap.mongo.MongoImapAccountCreator.java

License:Open Source License

public void createImapAccount(String username) throws MessageSearchException {
    HashMap<String, String> mailboxTable = new HashMap<String, String>();

    Date earliestMessageDate = searchService.getEarliestMessageDate(username);
    Date latestMessageDate = searchService.getLatestMessageDate(username);

    Calendar latestMessageCalendar = Calendar.getInstance();
    latestMessageCalendar.setTime(latestMessageDate);
    DateUtils.round(latestMessageCalendar, Calendar.DATE);
    Calendar today = Calendar.getInstance();
    DateUtils.round(today, Calendar.DATE);
    if (latestMessageCalendar.equals(today)) {
        latestMessageCalendar.add(Calendar.DATE, -1);
        latestMessageDate = latestMessageCalendar.getTime();
    }//w  w w .  j  av  a2 s.co m

    // Setup Trash and Inbox
    BasicDBObject inboxObject = new BasicDBObject();
    String inboxPath = "INBOX";
    inboxObject.put(MongoEnkiveImapConstants.MESSAGEIDS, new HashMap<String, String>());
    imapCollection.insert(inboxObject);
    ObjectId inboxId = (ObjectId) inboxObject.get("_id");
    mailboxTable.put(inboxPath, inboxId.toString());

    BasicDBObject trashObject = new BasicDBObject();
    String trashPath = "Trash";
    trashObject.put(MongoEnkiveImapConstants.MESSAGEIDS, new HashMap<String, String>());
    imapCollection.insert(trashObject);
    ObjectId trashId = (ObjectId) inboxObject.get("_id");
    mailboxTable.put(trashPath, trashId.toString());

    BasicDBObject rootMailboxObject = new BasicDBObject();
    imapCollection.insert(rootMailboxObject);
    ObjectId id = (ObjectId) rootMailboxObject.get("_id");
    BasicDBObject userMailboxesObject = new BasicDBObject();
    userMailboxesObject.put(MongoEnkiveImapConstants.USER, username);
    mailboxTable.put(MongoEnkiveImapConstants.ARCHIVEDMESSAGESFOLDERNAME, id.toString());

    userMailboxesObject.put(MongoEnkiveImapConstants.MAILBOXES, mailboxTable);
    imapCollection.insert(userMailboxesObject);

    addImapMessages(username, earliestMessageDate, latestMessageDate);
}

From source file:com.linuxbox.enkive.imap.mongo.MongoImapAccountCreator.java

License:Open Source License

private DBObject getMessagesFolder(String username, Date date) {
    Calendar mailboxTime = Calendar.getInstance();
    mailboxTime.setTime(date);/*ww w  .  j a  v  a 2  s. c o m*/
    DBObject mailboxObject = new BasicDBObject();
    String mailboxPath = MongoEnkiveImapConstants.ARCHIVEDMESSAGESFOLDERNAME + "/"
            + mailboxTime.get(Calendar.YEAR) + "/" + String.format("%02d", mailboxTime.get(Calendar.MONTH) + 1);

    // Get table of user mailboxes
    BasicDBObject userMailboxesSearchObject = new BasicDBObject();
    userMailboxesSearchObject.put(MongoEnkiveImapConstants.USER, username);
    DBObject userMailboxesObject = imapCollection.findOne(userMailboxesSearchObject);
    // Check for mailbox we're looking for
    @SuppressWarnings("unchecked")
    HashMap<String, String> mailboxTable = (HashMap<String, String>) userMailboxesObject
            .get(MongoEnkiveImapConstants.MAILBOXES);
    // If it exists, return the associated object
    // If it doesn't exist, create it, and any necessary upper level folders
    if (mailboxTable.containsKey(mailboxPath)) {
        DBObject mailboxSearchObject = new BasicDBObject();
        mailboxSearchObject.put("_id", ObjectId.massageToObjectId(mailboxTable.get(mailboxPath)));
        mailboxObject = imapCollection.findOne(mailboxSearchObject);
        return mailboxObject;
    } else {
        mailboxObject.put(MongoEnkiveImapConstants.MESSAGEIDS, new HashMap<String, String>());
        imapCollection.insert(mailboxObject);
        ObjectId id = (ObjectId) mailboxObject.get("_id");
        mailboxTable.put(mailboxPath, id.toString());
    }

    if (!mailboxTable.containsKey(
            MongoEnkiveImapConstants.ARCHIVEDMESSAGESFOLDERNAME + "/" + mailboxTime.get(Calendar.YEAR))) {
        BasicDBObject yearMailboxObject = new BasicDBObject();
        yearMailboxObject.put(MongoEnkiveImapConstants.MESSAGEIDS, new HashMap<String, String>());
        imapCollection.insert(yearMailboxObject);
        ObjectId id = (ObjectId) yearMailboxObject.get("_id");
        mailboxTable.put(
                MongoEnkiveImapConstants.ARCHIVEDMESSAGESFOLDERNAME + "/" + mailboxTime.get(Calendar.YEAR),
                id.toString());
    }
    userMailboxesObject.put(MongoEnkiveImapConstants.MAILBOXES, mailboxTable);
    imapCollection.findAndModify(userMailboxesSearchObject, userMailboxesObject);

    return mailboxObject;
}

From source file:com.linuxbox.enkive.statistics.gathering.mongodb.MongoStatsDatabaseGatherer.java

License:Open Source License

@Override
protected Map<String, Object> getPointStatistics(Date startTimestamp, Date endTimestamp)
        throws GathererException {
    Map<String, Object> pointStats = VarsMaker.createMap();
    BasicDBObject temp = db.getStats();
    pointStats.put(STAT_NUM_COLLECTIONS, temp.get(MONGO_NUM_COLLECTIONS));
    pointStats.put(STAT_NUM_OBJS, temp.get(MONGO_NUM_OBJS));
    pointStats.put(STAT_AVG_OBJ_SIZE, temp.get(MONGO_AVG_OBJ_SIZE));
    pointStats.put(STAT_DATA_SIZE, temp.get(MONGO_DATA_SIZE));
    pointStats.put(STAT_TOTAL_SIZE, temp.get(MONGO_STORAGE_SIZE));
    pointStats.put(STAT_NUM_INDEX, temp.get(MONGO_INDEXES));
    pointStats.put(STAT_TOTAL_INDEX_SIZE, temp.get(MONGO_INDEX_SIZE));
    pointStats.put(STAT_NUM_EXTENT, temp.get(MONGO_NUM_EXTENT));
    pointStats.put(STAT_FILE_SIZE, temp.get(MONGO_FILE_SIZE));

    return pointStats;
}

From source file:com.mebigfatguy.mongobrowser.dialogs.MongoTreeCellRenderer.java

License:Apache License

@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
        boolean leaf, int row, boolean hasFocus) {

    MongoTreeNode treeNode = (MongoTreeNode) value;

    JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
    label.setHorizontalTextPosition(JLabel.RIGHT);
    label.setVerticalTextPosition(JLabel.CENTER);

    label.setIcon(null);// w ww.  java  2s .  c o m

    if (treeNode.getType() == Type.KeyValue) {
        MongoTreeNode parentTreeNode = treeNode;

        do {
            parentTreeNode = (MongoTreeNode) parentTreeNode.getParent();
        } while ((parentTreeNode != null) && (parentTreeNode.getType() != Type.Collection));

        if (parentTreeNode != null) {

            DBCollection collection = (DBCollection) parentTreeNode.getUserObject();
            List<DBObject> indices = collection.getIndexInfo();
            String key = ((KV) treeNode.getUserObject()).getKey();

            for (DBObject index : indices) {
                BasicDBObject kvIndex = (BasicDBObject) index.get(MongoConstants.KEY);
                if (kvIndex.get(key) != null) {
                    label.setIcon(indexIcon);
                    break;
                }
            }
        }
    }

    return label;
}

From source file:com.mobileman.kuravis.core.services.messaging.weekly_updates.impl.WeeklyUpdatesServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}/*from www .  ja  va 2  s.  c o m*/
 * @see com.mobileman.kuravis.core.services.messaging.weekly_updates.WeeklyUpdatesService#process()
 */
@Override
public Map<String, DBObject> process() {

    // Get all treatment reviews with either new vote or new comment during last week
    Date[] timeWindow = getLastWeekDates();
    Date monday = timeWindow[0];
    //Date sunday = timeWindow[1].getTime();    

    AggregationOperation matchOp = Aggregation.match(Criteria.where(EntityUtils.CREATED_ON).gte(monday));
    AggregationOperation groupOp = Aggregation
            .group(TreatmentReviewEvent.TREATMENT_REVIEW_AUTHOR_ID, TreatmentReviewEvent.TYPE).count()
            .as("typeCount");
    AggregationOperation projectOp = Aggregation.project().andInclude(
            TreatmentReviewEvent.TREATMENT_REVIEW_AUTHOR_ID, TreatmentReviewEvent.TYPE, "typeCount");

    AggregationResults<BasicDBObject> aggregationResults = mongoTemplate.aggregate(
            Aggregation.newAggregation(matchOp, projectOp, groupOp), TreatmentReviewEvent.ENTITY_NAME,
            BasicDBObject.class);
    List<BasicDBObject> mappedResults = aggregationResults.getMappedResults();
    Map<String, DBObject> usersData = new HashMap<>();
    List<String> usersId = new ArrayList<String>();
    for (BasicDBObject result : mappedResults) {
        String authorId = (String) result.get(TreatmentReviewEvent.TREATMENT_REVIEW_AUTHOR_ID);
        usersId.add(authorId);
        String type = (String) result.get(TreatmentReviewEvent.TYPE);
        Number count = (Number) result.get("typeCount");
        if (usersData.containsKey(authorId)) {
            usersData.get(authorId).put(type, count);
        } else {
            result.put(type, count);
            usersData.put(authorId, result);
        }
    }

    Map<String, DBObject> result = new HashMap<String, DBObject>();
    for (List<String> splitedUsersId : CollectionUtil.split(usersId, 1000)) {
        Query query = Query.query(Criteria.where(EntityUtils.ID).in(splitedUsersId)
                .and("settings.privacySettings.emailNotification.weeklyUpdatesCommentsAndVotes")
                .is(Boolean.TRUE).and(User.STATE).is(UserState.ACTIVE.getValue()));
        query.fields().include(User.EMAIL);
        List<User> users = mongoTemplate.find(query, User.class);
        for (User user : users) {
            result.put(user.get_id(), usersData.get(user.get_id()));
            this.mailService.sendWeeklyUpdates(user, usersData.get(user.get_id()));
        }
    }

    return result;
}

From source file:com.mobileman.kuravis.core.services.subscription.impl.SubscriptionServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}// www .j av a2s .c  o  m
 * @see com.mobileman.kuravis.core.services.subscription.SubscriptionService#subscribe(com.mongodb.BasicDBObject)
 */
@Override
public void subscribe(BasicDBObject subscription) {
    if (StringUtils.isEmpty(subscription.get("email"))) {
        throw ErrorUtils.exception("Email is missing", ErrorCodes.INCORRECT_PARAMETER);
    }

    DBObject existing = findOneByProperty(EntityUtils.SUBSCRIPTION, "email", subscription.get("email"));
    if (existing != null) {
        // update modified-on property
        super.update(existing);
    } else {
        super.save(subscription);
    }

    mailService.sendUserSubscribedEmail(subscription);
}

From source file:com.mobileman.kuravis.core.ws.user.InvitationController.java

License:Apache License

/**
 * @param body /*from   ww w.j  a v a2s  .  c  o  m*/
 * @return send the invitation
 */
@RequestMapping(value = "/user/invitations", method = RequestMethod.POST, produces = {
        JsonUtil.MEDIA_TYPE_APPLICATION_JSON })
@ResponseBody
@RequiresAuthentication
@RequiresRoles(value = { Roles.USER, Roles.ADMIN }, logical = Logical.OR)
public ResponseEntity<DBObject> sendInvitation(@RequestBody BasicDBObject body) {
    log.info("sendInvitation(" + body + ") - start");

    this.invitationService.sendInvitation((String) body.get("email"));
    ResponseEntity<DBObject> response = new ResponseEntity<DBObject>(ErrorUtils.success(), HttpStatus.OK);

    log.info("sendInvitation() - end: " + response);
    return response;
}

From source file:com.mongodash.dao.mapper.SettingsDBObjectMapper.java

@Override
public Settings mapDBObject(BasicDBObject object) {
    Settings settings = null;//from   w  w  w.  j  a  v a2  s. co m
    String _id = object.getString(Config.COMMON_FIELDS._id.name());
    if (SETTINGS_KEY.email.name().equals(_id)) {
        settings = new EmailSettings();
        if (object != null) {
            ((EmailSettings) settings).setEnabled(object.getBoolean("enabled"));
            ((EmailSettings) settings).setServer(object.getString("server"));
            ((EmailSettings) settings).setPort(object.getString("port"));
            ((EmailSettings) settings).setSender(object.getString("sender"));
            if (object.containsField("username") && object.containsField("password")) {
                ((EmailSettings) settings).setUsername(object.getString("username"));
                ((EmailSettings) settings).setPassword(PasswordUtil.decrypt(object.getString("password")));
            }
            ((EmailSettings) settings).setSsl(object.getBoolean("ssl"));
        }
    } else if (SETTINGS_KEY.ldap.name().equals(_id)) {
        settings = new LdapSettings();
        if (object != null) {
            ((LdapSettings) settings).setEnabled(object.getBoolean("enabled"));
            ((LdapSettings) settings).setHost(object.getString("host"));
            ((LdapSettings) settings).setPort(object.getString("port"));
            ((LdapSettings) settings).setAdminDn(object.getString("adminDn"));
            ((LdapSettings) settings).setAdminPassword(object.getString("adminPassword"));
            ((LdapSettings) settings).setBaseDn(object.getString("baseDn"));
            ((LdapSettings) settings).setLoginAttribute(object.getString("loginAttr"));
            ((LdapSettings) settings).setSecure(object.getBoolean("secure"));
        }
    } else if (SETTINGS_KEY.alerts.name().equals(_id)) {
        settings = new AlertSettings();
        if (object != null) {
            ((AlertSettings) settings).setEnabled(object.getBoolean("enabled"));
            ((AlertSettings) settings).setEmailSubject(object.getString("emailSubject"));
            ((AlertSettings) settings).setEmailRecipients(object.getString("emailRecipients"));
        }
    } else if (SETTINGS_KEY.notifications.name().equals(_id)) {
        settings = new NotificationSettings();
        if (object != null) {
            ((NotificationSettings) settings).setEnabled(object.getBoolean("enabled"));
            ((NotificationSettings) settings).setEmailEnabled(object.getBoolean("emailEnabled"));
            ((NotificationSettings) settings).setEmailSubject(object.getString("emailSubject"));
            ((NotificationSettings) settings).setEmailRecipients(object.getString("emailRecipients"));
            if (object.containsField("enabledNotifications")) {
                BasicDBList list = (BasicDBList) object.get("enabledNotifications");
                List<String> enabledNotifications = new ArrayList<String>();
                for (int i = 0; i < list.size(); i++) {
                    enabledNotifications.add((String) list.get(i));
                }
                ((NotificationSettings) settings).setEnabledNotifications(enabledNotifications);
            }
        }
    } else if (SETTINGS_KEY.licenseKey.name().equals(_id)) {
        settings = new LicenseKeySettings();
        if (object != null) {
            ((LicenseKeySettings) settings).setPrivateKey(object.getString("privateKey"));
            ((LicenseKeySettings) settings).setPublicKey(object.getString("publicKey"));
        }
    }
    return settings;
}