Example usage for com.mongodb DBObject containsField

List of usage examples for com.mongodb DBObject containsField

Introduction

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

Prototype

boolean containsField(String s);

Source Link

Document

Checks if this object contains a field with the given name.

Usage

From source file:com.aw.app.action.StrategyAction.java

/**
 * //from w w  w  .j  a  va2  s. c om
 * @param uid 
 */
public void bootStrapAction(Long uid) {
    /********** Perform User Building Checking ***************/
    DBCollection table = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_building_base");
    BasicDBObject query = new BasicDBObject("uid", uid);
    DBCursor userBuildings = table.find(query);
    int count = 0;
    while (userBuildings.hasNext()) {
        DBObject building = userBuildings.next();
        if (building.containsField("tid")) {
            String tid = (String) building.get("tid");
            TroopsAction troopsAction = new TroopsAction();
            if (tid != null && tid.equalsIgnoreCase("TID_BUILDING_TAVERN")) {
                troopsAction.checkToopsUpgrades(uid, building);
                count++;
            } else if (tid != null && tid.equalsIgnoreCase("TID_BUILDING_BARRACK")) {
                int buildingId = (Integer) building.get("building_id");
                troopsAction.checkToopsInBarrack(uid, buildingId);
                count++;
            }

        }
    }
}

From source file:com.aw.app.action.TownHallAction.java

/**
 * /*from   ww w .j  a v a 2 s. c  o m*/
 * @param uid
 * @return 
 */
public BasicDBObject getTownHallOfUser(Object uid) {
    DBObject buildingBase = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_building_base")
            .findOne(new BasicDBObject("uid", uid).append("tid", townHallTid));
    if (buildingBase != null) {
        if (buildingBase.containsField("buildingTownhalls")) {
            List<BuildingTownhall> townHallBuildings = (List<BuildingTownhall>) buildingBase
                    .get("buildingTownhalls");
            return townHallBuildings.get(0);
        }
    }
    return null;
}

From source file:com.aw.app.action.TroopsAction.java

/**
 * /*from w w w  . j a  va  2 s.c  om*/
 * @param data
 * @return 
 */
public Map upgradeTroops(Map data) {
    Map state = new HashMap();
    long time = new Date().getTime();
    DBObject userTroopsDetail = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user_troops_details")
            .findOne(new BasicDBObject("uid", data.get("uid")));
    if (userTroopsDetail == null) {
        userTroopsDetail = new UserTroopsDetails(data);
        userTroopsDetail.put("titan_level", 1);
        MongoDbUtil.saveCollection("aw_user_troops_details", userTroopsDetail);
    }
    String tid = data.get("tid").toString();
    String fildName = tid.replace("TID_", "");
    long level = (Long) userTroopsDetail.get(fildName) + 1;
    DBObject troopsConfig = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_troops_configuration")
            .findOne(new BasicDBObject("level", level).append("tid", data.get("tid")));
    if (troopsConfig != null) {
        long userResource = new UserAction().getUserResource(data.get("uid"),
                troopsConfig.get("upgrade_resource").toString());
        long upgradeCost = (Long) troopsConfig.get("upgrade_cost");
        DBObject userLabBase = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_building_base")
                .findOne(new BasicDBObject("uid", data.get("uid")).append("tid", "TID_BUILDING_TAVERN"));
        BuildingArmy userLab = null;
        if (userLabBase == null || !userLabBase.containsField("buildingArmies")) {
            state.put("errorMessage", "You need research laboratary to upgrade any troop.");
            return state;
        } else {
            List<BuildingArmy> buildingArmies = (List<BuildingArmy>) userLabBase.get("buildingArmies");
            userLab = buildingArmies.get(0);
        }
        long labLevel = (Long) troopsConfig.get("laboratory_level");
        long baseLevel = (Long) userLabBase.get("level");
        if (userLab != null && userLab.containsField("upgrading_character_tid")
                && !"".equals(userLab.getString("upgrading_character_tid"))
                && userLab.getLong("research_start_time") > 0) {
            state.put("errorMessage", "Already another troop/spell is on the research.");
        } else if (labLevel > baseLevel) {
            String errorMessage = "This troop can be upgraded in research lab, Research Lab of lv-'" + labLevel
                    + "\" is required.";
            state.put("errorMessage", errorMessage);
        } else if (userResource >= upgradeCost) {
            userLab.put("upgrading_character_tid", data.get("tid"));
            userLab.put("research_start_time", time);
            //update userLab here
        } else if (userResource < upgradeCost) {
            String errorMessage = "Upgrade resource('" + troopsConfig.get("upgrade_resource")
                    + "') is not enough in the storage.";
            state.put("errorMessage", errorMessage);
        }
    } else {
        state.put("errorMessage", "Troop Configuration is not available.");
    }
    return state;
}

From source file:com.aw.app.action.UserAction.java

/**
 * //from  w w  w. j av  a  2 s . co  m
 * @param uid
 * @param infoType
 * @return 
 */
public Map getUserVillage(long uid, String infoType) {
    Map villageInfo = new HashMap();
    Map data = new HashMap();
    DBObject user = getUserDetail(uid);
    if (user != null) {
        List userBuildings = new BuildingAction().getUserBuildings(uid);
        List troops = new TroopsAction().getUserTroopsData(uid, "other");
        List troopsOwn = null;
        if ("login".equalsIgnoreCase(infoType)) {
            troopsOwn = new TroopsAction().getUserTroopsData(uid, "self");
        }
        if (troopsOwn != null) {
            troops.addAll(troopsOwn);
        }
        List buildingData = null;
        if (userBuildings != null) {
            if ("login".equalsIgnoreCase(infoType)) {
                buildingData = new BuildingAction().getBuildInfoForOwner(userBuildings);
            } else {
                buildingData = new BuildingAction().getBuildInfoForAttack(userBuildings);
            }
        }
        if (buildingData == null)
            buildingData = new ArrayList();
        if (user.containsField("clanUsers")) {
            List<ClanUsers> clanUsers = (List<ClanUsers>) user.get("clanUsers");
            ClanUsers clanUser = clanUsers.get(0);
            villageInfo.put("clan_name", clanUser.get("name"));
            villageInfo.put("clan_flag", clanUser.get("flag"));
            villageInfo.put("clan_id", clanUser.get("clan_id"));
        }
        /// Access Token
        DBCollection table = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user_token");
        BasicDBObject query = new BasicDBObject("uid", user.get("uid"));
        DBObject token = table.findOne(query);
        String userToken = "";
        if (token != null) {
            userToken = (String) token.get("access_token");
        } else {
            userToken = createUserAccessToken((Long) user.get("uid"));
        }
        villageInfo.put("uid", user.get("uid"));
        villageInfo.put("name", user.get("name"));
        villageInfo.put("trophies", user.get("trophies"));
        villageInfo.put("level", (int) user.get("game_level"));
        villageInfo.put("troops", troops);
        villageInfo.put("buildings", buildingData);
        villageInfo.put("access_token", userToken);
        if ("login".equalsIgnoreCase(infoType)) {
            villageInfo.put("spens", user.get("spens"));
        }

        data.put("status", true);
        data.put("message", "");
        data.put("data_set", villageInfo);
        return data;
    } else {
        data.put("status", false);
        data.put("message", "Village Not Found");
        return data;
    }
}

From source file:com.caci.dummyserver.MongoRepository.java

private DBObject getData(DBObject obj) {
    return obj != null && obj.containsField("data") ? (DBObject) ((DBObject) obj).get("data") : null;
}

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.IndexBuildCommand.java

License:Apache License

private Set<String> getUpdateIndex(Map<String, DBObject> exsitingIndexMap, MetaClass meta) {
    Collection<IndexInfo> collection = meta.getIndexes();
    Set<String> updateIndexes = new HashSet<String>();
    for (IndexInfo info : collection) {
        if (exsitingIndexMap.containsKey(info.getIndexName())) {
            boolean diff = false;
            DBObject dbo = exsitingIndexMap.get(info.getIndexName());
            // key check : cast as BasicDBObject, so that we could go through the insert order
            // FIXME :: don't support compare key order. If we support key order specify, then we need to add this comparison 
            BasicDBObject keyObjs = (BasicDBObject) dbo.get("key");
            DBObject keyObject = buildIndexKeyObject(meta, info, onMainBranch);
            diff = !ListUtils.isEqualList(keyObjs.keySet(), keyObject.keySet());

            if (!diff) {
                // option check when keys check passed
                List<IndexOptionEnum> exsitingOption = new ArrayList<IndexInfo.IndexOptionEnum>();
                for (IndexOptionEnum ioe : IndexOptionEnum.values()) {
                    if (dbo.containsField(ioe.name().toLowerCase())
                            && Boolean.parseBoolean(dbo.get(ioe.name().toLowerCase()).toString())) {
                        exsitingOption.add(ioe);
                    }//from   w ww. j a  va2s  .c  om
                }
                if (!ListUtils.subtract(exsitingOption, info.getIndexOptions()).isEmpty()
                        || !ListUtils.subtract(info.getIndexOptions(), exsitingOption).isEmpty()) {
                    diff = true;
                }
            }
            if (diff) {
                updateIndexes.add(info.getIndexName());
            }
        }
    }
    return updateIndexes;
}

From source file:com.ebay.cloud.cms.dal.search.impl.query.EmbedSearchQuery.java

License:Apache License

private DBObject trimOperator(DBObject match, String operator) {
    if (match == null) {
        return null;
    }//from  w w  w.  j a v a2 s. c o m
    return match.containsField(operator) ? (DBObject) match.get(operator) : match;
}

From source file:com.ebay.oss.bark.domain.DataAsset.java

License:Apache License

@SuppressWarnings({ "unchecked", "deprecation" })
public DataAsset(DBObject o) {
    this.set_id(Long.parseLong(o.get("_id").toString()));
    this.setAssetHDFSPath((String) o.get("assetHDFSPath"));
    this.setAssetName((String) o.get("assetName"));
    this.setAssetType((String) o.get("assetType"));

    this.setOwner((String) o.get("owner"));
    this.setPlatform((String) o.get("platform"));
    this.setSystem((String) o.get("system"));

    //      this.setPartitions((List<PartitionFormat>) o.get("partitions")); // this doesn't work
    if (o.get("partitions") != null) {
        List<PartitionFormat> partitionlist = new ArrayList<PartitionFormat>();
        List<DBObject> tlist = (List<DBObject>) o.get("partitions");
        for (DBObject temp : tlist) {
            partitionlist.add(new PartitionFormat(temp.get("name").toString(), temp.get("format").toString()));
        }//from www.j ava 2 s .c om
        this.setPartitions(partitionlist);
    }

    //      this.setSchema((List<DataSchema>) o.get("schema"));
    if (o.get("schema") != null) {
        List<DBObject> tlist = (List<DBObject>) o.get("schema");
        List<DataSchema> list = new ArrayList<DataSchema>();
        for (DBObject temp : tlist) {
            list.add(new DataSchema(temp.get("name").toString(), temp.get("type").toString(),
                    temp.get("desc").toString(), temp.get("sample").toString()));
        }
        this.setSchema(list);
    }

    if (!o.containsField("timestamp")) {
        this.setTimestamp(new Date());
    } else {
        this.setTimestamp(new Date(o.get("timestamp").toString()));
    }
}

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

License:Apache License

public void doImport(final ButtonBase button) throws IOException {
    ImportDialog dia = UMongo.instance.getGlobalStore().getImportDialog();
    if (!dia.show()) {
        return;//from www.  ja va2 s .c  o m
    }
    final boolean dropCollection = dia.getBooleanFieldValue(ImportDialog.Item.dropCollection);
    final boolean continueOnError = dia.getBooleanFieldValue(ImportDialog.Item.continueOnError);
    final boolean upsert = dia.getBooleanFieldValue(ImportDialog.Item.upsert);
    final boolean bulk = dia.getBooleanFieldValue(ImportDialog.Item.bulk);
    String supsertFields = dia.getStringFieldValue(ImportDialog.Item.upsertFields);
    final String[] upsertFields = supsertFields != null ? supsertFields.split(",") : null;
    if (upsertFields != null) {
        for (int i = 0; i < upsertFields.length; ++i) {
            upsertFields[i] = upsertFields[i].trim();
        }
    }
    final DocumentDeserializer dd = dia.getDocumentDeserializer();
    final DBCollection col = getCollectionNode().getCollection();

    new DbJob() {
        @Override
        public Object doRun() throws Exception {
            try {
                if (dropCollection) {
                    col.drop();
                }
                DBObject obj = null;
                List<DBObject> batch = new ArrayList<DBObject>();
                while ((obj = dd.readObject()) != null) {
                    try {
                        if (upsert) {
                            if (upsertFields == null) {
                                col.save(obj);
                            } else {
                                BasicDBObject query = new BasicDBObject();
                                for (int i = 0; i < upsertFields.length; ++i) {
                                    String field = upsertFields[i];
                                    if (!obj.containsField(field)) {
                                        throw new Exception("Upsert field " + field + " not present in object "
                                                + obj.toString());
                                    }
                                    query.put(field, obj.get(field));
                                }
                                col.update(query, obj, true, false);
                            }
                        } else {
                            if (bulk) {
                                if (batch.size() > 1000) {
                                    col.insert(batch);
                                    batch.clear();
                                }
                                batch.add(obj);
                            } else {
                                col.insert(obj);
                            }
                        }
                    } catch (Exception e) {
                        if (continueOnError) {
                            getLogger().log(Level.WARNING, null, e);
                        } else {
                            throw e;
                        }
                    }
                }

                if (!batch.isEmpty()) {
                    col.insert(batch);
                }

            } finally {
                dd.close();
            }
            return null;
        }

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

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

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

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

License:Apache License

public void addField(ButtonBase button) {
    String key = getStringFieldValue(Item.addKey);
    String type = getStringFieldValue(Item.addType);
    DBObject doc = (DBObject) value;
    if (key.isEmpty() || (doc != null && doc.containsField(key))) {
        new InfoDialog(null, "Invalid Key", null, "Please provide a unique key for this field").show();
        return;/*w ww .  j  av a 2  s  .  co m*/
    }
    addNewField(key, type);
}