Example usage for com.mongodb DBObject get

List of usage examples for com.mongodb DBObject get

Introduction

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

Prototype

Object get(String key);

Source Link

Document

Gets a field from this object by a given name.

Usage

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

/**
 * /*from   w w w .j  ava 2  s.co m*/
 * @param data
 * @return 
 */
public Map trainTroops(Map data) {
    Map state = new HashMap();
    DBObject troopsConfig = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_troops_configuration")
            .findOne(new BasicDBObject().append("tid", data.get("tid")).append("level", data.get("level")));
    DBObject buildingInfo = BuildingAction.getBuildingDetails(data.get("building_id"));
    if (troopsConfig == null) {
        state.put("errorMessage", "Troop Configuration is not available.");
        return state;
    }
    if (buildingInfo == null) {
        state.put("errorMessage", "Building/Barrack not found.");
        return state;
    }
    long userResource = new UserAction().getUserResource(data.get("uid"),
            troopsConfig.get("training_resource").toString());
    long trainingCost = (Long) troopsConfig.get("training_cost");
    long barrakLevel = (Long) troopsConfig.get("barrack_level");
    long level = (Long) buildingInfo.get("level");
    if (barrakLevel == level && userResource == trainingCost) {
        this.checkToopsInBarrack((Long) data.get("uid"), (Long) data.get("building_id"));
        DBObject barrack = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_barrack_troops")
                .findOne(new BasicDBObject().append("uid", data.get("uid"))
                        .append("building_id", data.get("building_id")).append("tid", data.get("tid"))
                        .append("level", data.get("level")));
        DBObject firstInQueue = this.getFirstInQueue(data);
        if (barrack == null && firstInQueue == null) {
            BasicDBObject barrackTroops = new BarrackTroops(data);
            barrackTroops.put("training_start_time", new Date().getTime());
            barrackTroops.put("count", 1);
            new UserAction().updateUserResource(data.get("uid"), trainingCost,
                    (String) troopsConfig.get("training_resource"), "decrease");
            WriteResult result = MongoDbUtil.saveCollection("aw_barrack_troops", barrackTroops);
            if (!result.getLastError().ok()) {
                new UserAction().updateUserResource(data.get("uid"), trainingCost,
                        (String) troopsConfig.get("training_resource"), "increase");
                state.put("status", false);
                state.put("errorMessage", "Unable to add troops in barrack.");
            }
        } else if (barrack == null && firstInQueue != null) {
            // Copied from existing code. However no difference seen in code 
            // comparing to if block above.
            BasicDBObject barrackTroops = new BarrackTroops(data);
            barrackTroops.put("training_start_time", new Date().getTime());
            barrackTroops.put("count", 1);
            new UserAction().updateUserResource(data.get("uid"), trainingCost,
                    (String) troopsConfig.get("training_resource"), "decrease");
            WriteResult result = MongoDbUtil.saveCollection("aw_barrack_troops", barrackTroops);
            if (!result.getLastError().ok()) {
                new UserAction().updateUserResource(data.get("uid"), trainingCost,
                        (String) troopsConfig.get("training_resource"), "increase");
                state.put("status", false);
                state.put("errorMessage", "Unable to add troops in barrack.");
            }
        } else {
            int barrackCount = (Integer) barrack.get("count");
            ++barrackCount;
            new UserAction().updateUserResource(data.get("uid"), trainingCost,
                    (String) troopsConfig.get("training_resource"), "decrease");
            BasicDBObject updateObject = new BasicDBObject("$set", new BasicDBObject("count", barrackCount));
            WriteResult wResult = MongoDbUtil.updateCollection("aw_barrack_troops", barrack, updateObject);
            if (!wResult.getLastError().ok()) {
                new UserAction().updateUserResource(data.get("uid"), trainingCost,
                        (String) troopsConfig.get("training_resource"), "increase");
                state.put("errorMessage", "Unable to update troops in barrack.");
            }
        }

    } else if (userResource < trainingCost) {
        String errorMessage = "Training resource " + troopsConfig.get("training_resource").toString()
                + " is not enough in the storage.";
        state.put("errorMessage", errorMessage);
    } else {
        int bLevel = (Integer) troopsConfig.get("barrack_level");
        String errorMessage = "You cannot train this troop in this barrack, it requires level '" + bLevel
                + "' barrack.";
        state.put("errorMessage", errorMessage);
    }
    return state;
}

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

/**
 * /*from   www  . ja  va 2  s  .  co m*/
 * @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.TroopsAction.java

/**
 * //from w  w w. ja v a  2  s  . c o  m
 * @param data
 * @return 
 */
public Map removeFromBarracks(Map data) {
    Map state = new HashMap();
    DBObject configuration = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_troops_configuration")
            .findOne(new BasicDBObject("level", data.get("level")).append("tid", data.get("tid")));
    DBObject buildingInfo = BuildingAction.getBuildingDetails(data.get("building_id"));
    if (configuration != null) {
        if (buildingInfo != null) {
            DBObject barrack = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_barrack_troops")
                    .findOne(new BasicDBObject("uid", data.get("uid"))
                            .append("building_id", data.get("building_id")).append("tid", data.get("tid"))
                            .append("level", data.get("level")));
            long trainingCost = (Long) configuration.get("training_cost");
            UserAction action = new UserAction();

            if (barrack != null && (Integer) barrack.get("count") > 0) {
                int barrackCount = (Integer) barrack.get("count");
                switch (barrackCount) {
                case 1:
                    WriteResult deleteResult = MongoDbUtil.removeCollection("aw_barrack_troops", barrack);
                    if (deleteResult.getLastError().ok()) {
                        action.updateUserResource(data.get("uid"), trainingCost,
                                configuration.get("training_resource").toString(), "increase");
                    }
                    state.put("status", true);
                    DBObject nextBarrackTroop = MongoDbUtil
                            .getCollection(MongoDbUtil.defaultDBName, "aw_barrack_troops")
                            .findOne(new BasicDBObject("uid", data.get("uid")).append("building_id",
                                    data.get("building_id")));
                    if (nextBarrackTroop != null) {
                        BasicDBObject updateObject = new BasicDBObject("$set",
                                new BasicDBObject().append("training_start_time", new Date().getTime()));
                        MongoDbUtil.updateCollection("aw_barrack_troops", barrack, updateObject);

                    }
                    break;
                default:
                    BasicDBObject updateObject = new BasicDBObject("$set",
                            new BasicDBObject("count", barrackCount - 1).append("training_start_time",
                                    new Date().getTime()));
                    DBObject query = new BasicDBObject("uid", data.get("uid"))
                            .append("building_id", data.get("building_id")).append("tid", data.get("tid"))
                            .append("level", data.get("level"));
                    WriteResult updateResult = MongoDbUtil.updateCollection("aw_barrack_troops", query,
                            updateObject);
                    //barrack.put("count", barrackCount - 1);
                    //barrack.put("training_start_time", new Date().getTime());
                    if (updateResult.getLastError().ok())
                        state.put("status", true);
                }

                boolean status = (Boolean) state.get("status");
                if (!status) {
                    state.put("errorMessage", "");
                } else {
                    action.updateUserResource(data.get("uid"), trainingCost,
                            configuration.get("training_resource").toString(), "increase");
                }
            } else {
                state.put("errorMessage", "Troops not found in barrack.");
            }
        } else {
            state.put("errorMessage", "Building/Barrack not found.");
        }
    } else {
        state.put("errorMessage", "Troop Configuration is not available.");
    }
    return state;
}

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

/**
 * // ww w .j  av  a2 s . c  o  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.aw.app.action.UserAction.java

/**
 * // w w  w .j av  a  2s  . c  o  m
 * @param token
 * @return 
 */
public int checkAccess(String token) {
    DBCollection collection = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user_token");
    BasicDBObject filter = new BasicDBObject();
    filter.put("access_token", token);
    DBObject record = collection.findOne(filter);
    if (record != null) {
        boolean login = (Boolean) record.get("is_login");
        if (login) {
            return 1;
        } else {
            return 2;
        }
    } else {
        return 3;
    }
}

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

/**
 * /*from  w ww.ja  va  2s .co m*/
 * @param token
 * @return 
 */
public long getLoginUserId(String token) {
    DBCollection collection = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user_token");
    BasicDBObject filter = new BasicDBObject();
    filter.put("access_token", token);
    filter.put("is_login", true);
    DBObject record = collection.findOne(filter);
    if (record != null)
        return (Long) record.get("uid");
    else
        return -1;
}

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

/**
 * /*from w w w .  j a v a 2 s .co m*/
 * @param uid
 * @param buildCost
 * @param type
 * @param action
 * @return 
 */
public boolean updateUserResource(Object uid, Object buildCost, String type, String action) {
    boolean state = false;
    boolean townHallPass = false;
    DBObject user = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user")
            .findOne(new BasicDBObject("uid", uid));
    String tid = BuildingAction.resourceStorage[0];
    String maxField = "";
    String townHallStorageField = "";
    long amount = 0;
    if (user != null) {
        type = type.toLowerCase();
        if ("spens".equalsIgnoreCase(type)) {
            if ("increase".equalsIgnoreCase(action)) {
                long spens = (Long) user.get("spens");
                long cost = (Long) buildCost;
                spens += cost;
                BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("spens", spens));
                WriteResult result = MongoDbUtil.updateCollection("aw_user", new BasicDBObject("uid", uid),
                        update);
                return result.getLastError().ok();
            } else {
                long spens = (Long) user.get("spens");
                long cost = (Long) buildCost;
                spens -= cost;
                BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("spens", spens));
                WriteResult result = MongoDbUtil.updateCollection("aw_user", new BasicDBObject("uid", uid),
                        update);
                return result.getLastError().ok();
            }
        } else if ("gold".equalsIgnoreCase(type)) {
            tid = BuildingAction.resourceStorage[0];
            maxField = "max_stored_gold";
            townHallStorageField = "gold_stored";

        } else if ("mithril".equalsIgnoreCase(type)) {
            tid = BuildingAction.resourceStorage[1];
            maxField = "max_stored_mithril";
            townHallStorageField = "mithril_stored";
        } else if ("dark mithril".equalsIgnoreCase(type)) {
            tid = BuildingAction.resourceStorage[2];
            maxField = "max_stored_dark_mithril";
            townHallStorageField = "dark_mithril_stored";
        }

        DBCursor buildings = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_building_base")
                .find(new BasicDBObject().append("uid", uid).append("tid", tid));
        if ("increase".equalsIgnoreCase(action)) {
            DBObject townHallBase = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_building_base")
                    .findOne(new BasicDBObject().append("uid", uid).append("tid", TownHallAction.townHallTid));
            BuildingBase buildingBase = new BuildingBase(townHallBase.toMap());
            if (buildingBase.containsField("buildingTownhalls")) {
                BuildingTownhall townHall = buildingBase.getBuildingTownhalls().get(0);
                if (townHall.getLong("townHallStorageField") < townHall.getLong("maxField")) {
                    amount = (Long) buildCost;
                    long temp = amount;
                    long total = townHall.getLong("townHallStorageField") + amount;
                    if (total > townHall.getLong("maxField")) {
                        amount = amount - townHall.getLong("maxField")
                                - townHall.getLong("townHallStorageField");
                        total = townHall.getLong("maxField");
                    } else {
                        amount = 0;
                    }
                    townHall.put("townHallStorageField", total);
                    // update
                    BasicDBObject query = new BasicDBObject().append("uid", uid).append("tid",
                            TownHallAction.townHallTid);
                    BasicDBObject update = new BasicDBObject("$set",
                            new BasicDBObject("buildingTownhalls", buildingBase.getBuildingTownhalls()));
                    WriteResult result = MongoDbUtil.updateCollection("aw_building_base", query, update);
                    townHallPass = result.getLastError().ok();
                    if (!result.getLastError().ok())
                        amount = temp;
                }
            }
        }
        long subAmount = amount;
        int resourceCount = 0;
        if (buildings != null) {
            while (buildings.hasNext()) {
                DBObject building = buildings.next();
                BuildingBase bb = new BuildingBase(building.toMap());
                List<BuildingResource> resources = (List<BuildingResource>) bb.get("buildingResources");
                BuildingResource resource = new BuildingResource(resources.get(0).toMap());
                if ("decrease".equalsIgnoreCase(action)) {
                    if (resource.getLong("resource_stored") > 0
                            & resource.getLong("resource_stored") <= subAmount) {
                        subAmount -= resource.getLong("resource_stored");
                        resource.put("resource_stored", 0);
                        // Update here...
                        resourceCount++;
                    } else if (resource.getLong("resource_stored") > 0
                            & resource.getLong("resource_stored") > subAmount) {
                        resource.put("resource_stored", resource.getLong("resource_stored") - subAmount);
                        subAmount = 0;
                        // Update here
                        resourceCount++;
                    }
                } else if ("increase".equalsIgnoreCase(action)) {
                    if (subAmount > 0) {
                        long total = resource.getLong("resource_stored") + subAmount;
                        if (resource.getLong("$maxField") == total) {
                            resource.put("resource_stored", total);
                            // update here
                            subAmount = 0;
                            state = true;
                        } else if (total > resource.getLong("$maxField")
                                && resource.getLong("$maxField") > resource.getLong("resource_stored")) {
                            long difference = resource.getLong("$maxField")
                                    - resource.getLong("resource_stored");
                            subAmount -= difference;
                            resource.put("resource_stored", resource.getLong("$maxField"));
                            resourceCount++;
                            // update resouce
                        }
                    }
                }
            }
        }
        /**** First Fill the Town Hall for increase resource action ***/
        if (subAmount > 0 && "decrease".equalsIgnoreCase(action)) {
            DBObject townHallBase = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_building_base")
                    .findOne(new BasicDBObject().append("uid", uid).append("tid", TownHallAction.townHallTid));
            List<BuildingTownhall> townHallList = (List<BuildingTownhall>) townHallBase
                    .get("buildingTownhalls");
            if (townHallList != null) {
                BuildingTownhall townhall = townHallList.get(0);
                townhall.put("townHallStorageField", townhall.getLong("townHallStorageField") - subAmount);
                if (townhall.getLong("townHallStorageField") < 0) {
                    state = false;
                } else {
                    // update town hall
                    townHallPass = true;
                    state = true;
                }
            }
        }
    }
    if (townHallPass && !state)
        state = townHallPass;

    return state;
}

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

/**
 * /*from   w ww  .j av  a 2  s. c o m*/
 * @param uid
 * @param level 
 */
public void unlockUserTroops(Object uid, Object level) {
    Map tidLevel = new TroopsAction().getTroopsTidLevelForBarrack(level);
    DBObject userTroopsDetail = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user_troops_details")
            .findOne(new BasicDBObject().append("uid", uid));
    if (userTroopsDetail == null) {
        userTroopsDetail = this.createUserTroopDetail(uid);
    }
    if (tidLevel != null && !tidLevel.isEmpty()) {
        Set keys = tidLevel.keySet();
        Iterator keyIterator = keys.iterator();
        while (keyIterator.hasNext()) {
            String key = (String) keyIterator.next();
            long value = (Long) tidLevel.get(key);
            String fieldName = key.replace("TID_", "").concat("_level").toLowerCase();
            long utdValue = (Long) userTroopsDetail.get(fieldName);
            if (value > utdValue)
                userTroopsDetail.put(fieldName, value);
            BasicDBObject updateUser = new BasicDBObject("$set",
                    new BasicDBObject(fieldName, userTroopsDetail.get(fieldName)));
            BasicDBObject query = new BasicDBObject().append("uid", uid);
            WriteResult result = MongoDbUtil.updateCollection("aw_user_troops_details", query, updateUser);
        }
    }
}

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

/**
 * /*from   ww  w . java  2s.c o m*/
 * @param uid
 * @param name
 * @return 
 */
public Map updateUserName(long uid, String name) {
    Map state = new HashMap();
    DBObject user = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user")
            .findOne(new BasicDBObject().append("uid", uid));
    if (user != null) {
        DBCursor cursor = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user")
                .find(new BasicDBObject().append("name", name));
        boolean nameInUse = false;
        while (cursor.hasNext()) {
            DBObject nextUser = cursor.next();
            long nextUserId = (Long) nextUser.get("uid");
            if (nextUserId != uid) {
                nameInUse = true;
                break;
            }
        }
        if (!nameInUse) {
            BasicDBObject update = new BasicDBObject("$set", new BasicDBObject("name", name));
            BasicDBObject query = new BasicDBObject("uid", uid);
            WriteResult result = MongoDbUtil.updateCollection("aw_user", query, update);
            if (!result.getLastError().ok()) {
                state.put("errorMessage", "User update error.");
            }
        } else {
            state.put("errorMessage", "Name is already in use.");
        }
    }
    return state;
}

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

/**
 * //  w  w  w.ja va  2  s  . c  o  m
 * @param uid
 * @param type
 * @return 
 */
public Map getUserBattleLogs(long uid, String type) {
    Map result = new HashMap();
    result.put("status", false);
    result.put("message", "");
    int count = 5;
    BasicDBObject query = new BasicDBObject();
    if (uid > 0) {
        if ("attack".equalsIgnoreCase(type)) {
            query.put("attacker_id", uid);
            query.put("count", BattleAction.attackLogCount);
        } else if ("defense".equalsIgnoreCase(type)) {
            query.put("defender_id", uid);
            query.put("count", BattleAction.defenseLogCount);
        } else {
            query.put("attacker_id", uid);
            query.put("count", BattleAction.attackLogCount);
        }
        DBCursor cursor = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_battle")
                .find(query.append("limit", count));
        List battles = new ArrayList();
        while (cursor.hasNext()) {
            DBObject battle = cursor.next();
            Map detail = new BattleAction().getBattleDetail((Long) battle.get("battled_id"));
            battles.add(detail);
        }
        result.put("dataset", battles);
        result.put("status", true);
    } else {
        result.put("errorMessage", "uid is missing.");
    }
    return result;
}