Example usage for com.mongodb BasicDBObject append

List of usage examples for com.mongodb BasicDBObject append

Introduction

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

Prototype

@Override
public BasicDBObject append(final String key, final Object val) 

Source Link

Document

Add a key/value pair to this object

Usage

From source file:com.arquivolivre.mongocom.management.MongoQuery.java

License:Apache License

public DBObject getQuery() {
    if (orderBy != null) {
        BasicDBObject newQuery = new BasicDBObject();
        newQuery.append("$query", query);
        newQuery.append("$orderby", orderBy);
        return newQuery;
    }//from   w  ww.  j  a va2  s  .  c  o m
    return query;
}

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

/**
 * // w ww  . j  a  v a 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;
}

From source file:com.aw.services.AncientWarServiceImpl.java

/**
 * //from   ww  w.  j a  v  a 2  s  .c om
 * @param deviceId
 * @return
 * @throws JSONException 
 */
@Override
public JSONObject login(String deviceId) throws JSONException {
    JSONObject response = new JSONObject();
    if (deviceId != null && !deviceId.equals("")) {
        DBCollection users = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user");
        BasicDBObject filter = new BasicDBObject("selected_market_id", deviceId);
        BasicDBObject user = (BasicDBObject) users.findOne(filter);

        DBCollection devices = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName, "aw_user_devices");
        BasicDBObject deviceQuery = new BasicDBObject("device_id", deviceId);
        BasicDBObject device = (BasicDBObject) devices.findOne(deviceQuery);
        /// System.out.println("Device Id: "+device.get("device_id"));
        long uid = 0;
        if (device != null && device.containsField("uid") && device.get("uid") != null) {
            uid = (Long) device.get("uid");
            user = (BasicDBObject) users.findOne(new User("uid", uid));

            DBCollection troopsDetailsCollection = MongoDbUtil.getCollection(MongoDbUtil.defaultDBName,
                    "aw_user_troops_details");
            UserTroopsDetails userTroopsDetails;
            userTroopsDetails = new UserTroopsDetails("uid", user.get("uid"));
            BasicDBObject details = (BasicDBObject) troopsDetailsCollection.findOne(userTroopsDetails);
            if (details == null) {
                details = new UserTroopsDetails();
                details.put("uid", user.get("uid"));
                details.put("titan_level", 1);
                MongoDbUtil.saveCollection(MongoDbUtil.defaultDBName, "aw_user_troops_details", details);
            }
            user.put("last_visited", new Date().getTime());
            // update user
            BasicDBObject query = new BasicDBObject().append("uid", user.get("uid"));
            BasicDBObject updateUser = new BasicDBObject();
            updateUser.append("$set", new BasicDBObject("last_visited", user.get("last_visited")));
            MongoDbUtil.updateCollection("aw_user", query, updateUser);
            new StrategyAction().bootStrapAction((Long) user.get("uid"));
            return getUserVillage(uid, "login");
        } else {
            JSONObject json = new JSONObject();
            json.put("device_id", deviceId);
            User createdUser = this.createUser(json);
            if (createdUser != null) {
                return this.getUserVillage((Long) createdUser.get("uid"), "login");
            } else {
                response.put("status", false);
                response.put("message", "User is not found and unable to create the user.");
                return response;
            }
        }
    } else if (deviceId == null || deviceId.equals("")) {
        response.put("status", false);
        response.put("message", "Device id is required.");
        return response;
    } else {
        response.put("status", false);
        response.put("message", "No input information provided.");
        return response;
    }
}

From source file:com.biz.mongo.MongoDBConnection.java

public String updateContext(SkillFlowContext skillFlowContext) {
    //    context.findAndModify(new BasicDBObject("sessionId", skillFlowContext.getSessionId()),new BasicDBObject("contextId", skillFlowContext.getContextId()),
    //     new BasicDBObject("$push", new BasicDBObject("nameIdentity", new BasicDBObject("fName", "123").append("lName", "456")
    //    .append("dob", "00").append("address", "789"))));
    //        return "done";
    System.out.println("in siide updateContext : updateContext");
    System.out.println("skillFlowContext.getSessionId() : " + skillFlowContext.getSessionId());
    context.findAndModify(new BasicDBObject("sessionId", skillFlowContext.getSessionId()),
            new BasicDBObject("contextId", skillFlowContext.getContextId()), new BasicDBObject("$push",
                    new BasicDBObject(skillFlowContext.getKeyresponse(), skillFlowContext.getValueresponse())));

    BasicDBObject newDocument = new BasicDBObject();
    System.out.println("skillFlowContext.getSessionId() : " + skillFlowContext.getNextStep());
    newDocument.append("$set", new BasicDBObject().append("nextStep", skillFlowContext.getNextStep()));
    //  newDocument.append("$set", new BasicDBObject().append("FileJson", jsonobject));

    BasicDBObject searchQuery = new BasicDBObject().append("contextId", skillFlowContext.getContextId());

    context.update(searchQuery, newDocument);
    return "done";
}

From source file:com.chdi.kundenverwaltung.KundenVerwaltungsLogic.java

public void insertCustomer(Customer customer) {

    DBCollection table = db.getCollection("user");

    BasicDBObject query = new BasicDBObject();

    query.append("ID", customer.getID());
    query.append("CompanyName", customer.getCompanyName());
    query.append("Name", customer.getName());
    query.append("Adress", customer.getAdress());

    table.insert(query);//from  ww  w .  j a  va  2 s.c om
}

From source file:com.clavain.rca.Methods.java

License:Apache License

public static BigDecimal getTotalForPluginAndGraph(String p_plugin, String p_graph, int start, int end,
        int userId, int nodeId) {
    BigDecimal total = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    try {/*from  w w  w . j a  v a2  s .  c o  m*/
        String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbname");
        db = m.getDB(dbName);
        col = db.getCollection(userId + "_" + nodeId);

        BasicDBObject query = new BasicDBObject("plugin", p_plugin);
        query.append("graph", p_graph);

        BasicDBObject gtlt = new BasicDBObject("$gt", start);
        gtlt.append("$lt", end);
        query.append("recv", gtlt);

        cursor = col.find(query);

        try {
            while (cursor.hasNext()) {

                BigDecimal val = new BigDecimal(cursor.next().get("value").toString());
                val.setScale(2, RoundingMode.HALF_UP);
                total = total.add(val);
            }
        } finally {
            cursor.close();
        }

    } catch (Exception ex) {
        logger.error("[RCA] Error in getTotalForPluginAndGraph: " + ex.getLocalizedMessage());
        ex.printStackTrace();
    }
    return total;
}

From source file:com.clavain.rca.Methods.java

License:Apache License

public static BigDecimal getAverageForPluginAndGraph(String p_plugin, String p_graph, int start, int end,
        int userId, int nodeId) {
    BigDecimal total = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    try {/*from w ww  .j  av a  2  s.  c  o  m*/
        String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbname");
        db = m.getDB(dbName);
        col = db.getCollection(userId + "_" + nodeId);

        BasicDBObject query = new BasicDBObject("plugin", p_plugin);
        query.append("graph", p_graph);

        BasicDBObject gtlt = new BasicDBObject("$gt", start);
        gtlt.append("$lt", end);
        query.append("recv", gtlt);

        cursor = col.find(query);

        int iterations = 0;
        try {
            while (cursor.hasNext()) {

                BigDecimal val = new BigDecimal(cursor.next().get("value").toString());
                val.setScale(2, RoundingMode.HALF_UP);
                total = total.add(val);
                iterations++;
            }
        } finally {
            cursor.close();
        }
        if (iterations == 0) {
            logger.warn("[RCA] Iterations is 0 for Query=> Plugin: " + p_plugin + " Graph: " + p_graph
                    + " start: " + start + " end: " + end + " userid: " + userId + " nodeId:" + nodeId);
            return null;
        }
        total = total.divide(new BigDecimal(iterations).setScale(2), 2, RoundingMode.HALF_UP);
    } catch (Exception ex) {
        logger.error("[RCA] Error in getAverageForPluginAndGraph: " + ex.getLocalizedMessage()
                + " Query=> Plugin: " + p_plugin + " Graph: " + p_graph + " start: " + start + " end: " + end
                + " userid: " + userId + " nodeId:" + nodeId);
        ex.printStackTrace();
    }
    return total;
}

From source file:com.clavain.utils.Database.java

License:Apache License

public static void removeOldPackageTrack(int p_nodeid) {
    try {/*from   w w  w  . jav a  2  s. c o m*/

        logger.info("Purging Package Logs for NodeID: " + p_nodeid);
        DB db;
        String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbessentials");
        db = m.getDB(dbName);
        db.setWriteConcern(WriteConcern.SAFE);
        DBCollection col = db.getCollection("trackpkg");
        BasicDBObject query = new BasicDBObject();
        query.append("node", p_nodeid);
        col.remove(query);
        db.setWriteConcern(WriteConcern.NONE);
    } catch (Exception ex) {
        logger.error("Error in removeOldPackageTrack: " + ex.getLocalizedMessage());
    }
}

From source file:com.clavain.workers.DataRetentionWorker.java

License:Apache License

@Override
public void run() {
    int month = 2629743;
    logger.info("Started DataRetentionWorker");
    try {//from  w ww .j  a v  a2 s  .co  m
        int sleepTime = Integer.parseInt(p.getProperty("dataretention.period")) * 3600000;
        while (true) {
            Thread.sleep(sleepTime);
            logger.info("[DataRetentionWorker] Starting Retention Run");
            Connection conn = connectToDatabase(p);
            java.sql.Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE retention > 0 AND userrole != 'user'");
            while (rs.next()) {
                logger.info("[DataRetentionWorker - User Mode] Processing User: " + rs.getString("username"));
                // get nodes from this user
                Iterator it = v_munin_nodes.iterator();
                List l_nodes = new ArrayList();
                while (it.hasNext()) {
                    MuninNode l_mn = (MuninNode) it.next();
                    if (l_mn.getUser_id().equals(rs.getInt("id"))) {
                        logger.info("[DataRetentionWorker User Mode] probing " + l_mn.getHostname()
                                + " from user: " + rs.getString("username"));
                        String colname = l_mn.getUser_id() + "_" + l_mn.getNode_id(); // recv
                        String colnamees = l_mn.getNode_id() + "_ess"; // time
                        int matchtime = rs.getInt("retention") * month;
                        matchtime = getUnixtime() - matchtime;
                        BasicDBObject query = new BasicDBObject("recv", new BasicDBObject("$lt", matchtime));
                        String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbname");
                        db = m.getDB(dbName);
                        col = db.getCollection(colname);
                        DBCursor cursor = col.find(query);
                        if (cursor.count() > 0) {
                            logger.info("[DataRetentionWorker User Mode] result for " + l_mn.getHostname()
                                    + " from user: " + rs.getString("username") + " affected for deletion: "
                                    + cursor.count() + " matchtime: lt " + matchtime);
                        }
                        col.remove(query);

                        // now ESSENTIALS
                        query = new BasicDBObject("time", new BasicDBObject("$lt", matchtime));
                        dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbessentials");
                        db = m.getDB(dbName);
                        col = db.getCollection(colnamees);
                        cursor = col.find(query);
                        if (cursor.count() > 0) {
                            logger.info("[DataRetentionWorker User Mode] ESSENTIAL result for "
                                    + l_mn.getHostname() + " from user: " + rs.getString("username")
                                    + " affected for deletion: " + cursor.count() + " matchtime: lt "
                                    + matchtime);
                        }
                        col.remove(query);

                    }
                }
            }
            //conn.close();

            logger.info("[DataRetentionWorker User Mode] Finished Retention Run");

            logger.info("[DataRetentionWorker Custom Mode] Starting Retention Run");
            stmt = conn.createStatement();
            rs.close();
            rs = stmt.executeQuery("SELECT * FROM plugins_custom_interval WHERE retention > 0");
            while (rs.next()) {
                logger.info("[DataRetentionWorker - Custom Mode] Processing Custom ID: " + rs.getString("id")
                        + " Node: " + rs.getString("node_id") + " Plugin: " + rs.getString("pluginname"));
                MuninNode l_mn = getMuninNode(rs.getInt("node_id"));
                if (l_mn != null) {
                    String colname = l_mn.getUser_id() + "_" + l_mn.getNode_id(); // recv
                    int matchtime = rs.getInt("retention") * 86400;
                    matchtime = getUnixtime() - matchtime;
                    BasicDBObject query = new BasicDBObject("recv", new BasicDBObject("$lt", matchtime));
                    query.append("customId", rs.getInt("id"));
                    String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbname");
                    db = m.getDB(dbName);
                    col = db.getCollection(colname);
                    DBCursor cursor = col.find(query);
                    if (cursor.count() > 0) {
                        logger.info("[DataRetentionWorker Custom Mode] Custom Interval (CID: " + rs.getInt("id")
                                + ") POSITIVE RESULTS for " + l_mn.getHostname() + " affected for deletion: "
                                + cursor.count() + " collection: " + colname + " matchtime: lt " + matchtime);
                    } else {
                        logger.info("[DataRetentionWorker Custom Mode] Custom Interval (CID: " + rs.getInt("id")
                                + ") NEGATIVE RESULTS for " + l_mn.getHostname() + "count:  " + cursor.count()
                                + " collection: " + colname + " matchtime: lt " + matchtime);
                    }
                    col.remove(query);

                } else {
                    logger.warn("[DataRetentionWorker Custom Mode] getMuninNode returned null for node_id "
                            + rs.getInt("node_id"));
                }
            }
            logger.info("[DataRetentionWorker Custom Mode] Finished Retention Run");

            // Service Checks
            logger.info("[DataRetentionWorker ServiceCheck Mode] Starting Retention Run");
            stmt = conn.createStatement();
            rs.close();
            rs = stmt.executeQuery(
                    "SELECT service_checks.*,users.retention,users.username FROM service_checks LEFT JOIN users on service_checks.user_id = users.id WHERE users.retention > 0");
            while (rs.next()) {
                logger.info("[DataRetentionWorker - ServiceCheck Mode] Processing ServiceCheck ID: "
                        + rs.getString("id") + " Name: " + rs.getString("check_name") + " for User: "
                        + rs.getString("username") + " Retention: " + rs.getString("retention"));

                String colname = rs.getInt("user_id") + "cid" + rs.getInt("id");
                int matchtime = rs.getInt("retention") * month;
                matchtime = getUnixtime() - matchtime;
                BasicDBObject query = new BasicDBObject("time", new BasicDBObject("$lt", matchtime));
                query.append("cid", rs.getInt("id"));
                query.append("status", 0);
                String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbchecks");
                db = m.getDB(dbName);
                col = db.getCollection(colname);
                DBCursor cursor = col.find(query);
                if (cursor.count() > 0) {
                    logger.info("[DataRetentionWorker ServiceCheck Mode] ServiceCheck ID: " + rs.getString("id")
                            + " Name: " + rs.getString("check_name") + " for User: " + rs.getString("username")
                            + " affected for deletion: " + cursor.count() + " matchtime: lt " + matchtime);
                }
                col.remove(query);

            }
            logger.info("[DataRetentionWorker ServiceCheck Mode] Finished Retention Run");
            conn.close();
        }

    } catch (Exception ex) {
        logger.error("Error in DataRetentionWorker: " + ex.getLocalizedMessage());
    }
}

From source file:com.cognitive.cds.invocation.mongo.IntentMappingDao.java

License:Apache License

public DeleteResult deleteIntent(String intentName) throws JsonProcessingException {
    MongoClient mongo = mongoDbDao.getMongoClient();
    MongoDatabase db = mongo.getDatabase("intent");
    MongoCollection<Document> collection = db.getCollection("cdsintent");

    BasicDBObject query = new BasicDBObject();
    query.append("name", intentName);

    DeleteResult result = collection.deleteOne(query);
    return result;
}