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.ca.apm.mongo.ShardCluster.java

License:Open Source License

private List<String> getShardsFromConfig(final String host, final int port) {

    final List<String> shardList = new ArrayList<String>();

    MongoClient dbClient = null;//w  w  w. ja  va 2s .c  o m

    try {
        dbClient = setupDbClient(host, port);

        final DB configDB = dbClient.getDB("config");
        final DBCursor shardsCursor = configDB.getCollectionFromString("shards").find();
        while (shardsCursor.hasNext()) {
            final DBObject dbo = shardsCursor.next();
            String shards = (String) dbo.get("host");
            String[] shardMembers = getShardMembers(shards);
            for (String member : shardMembers) {
                shardList.add(member);
            }
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Exception getting shards from cfg servers: {0}", e);
    } finally {
        if (dbClient != null) {
            dbClient.close();
        }
    }
    return shardList;
}

From source file:com.ca.apm.mongo.ShardCluster.java

License:Open Source License

private List<String> getMongosFromConfig(final String host, final int port) {

    final List<String> shardRouters = new ArrayList<String>();

    MongoClient dbClient = null;//ww  w .  j ava 2s. c o  m

    try {
        dbClient = setupDbClient(host, port);
        final DB configDB = dbClient.getDB("config");
        final DBCursor mongosCursor = configDB.getCollectionFromString("mongos").find();
        while (mongosCursor.hasNext()) {
            final DBObject dbo = mongosCursor.next();
            final String mongos = (String) dbo.get("_id");
            shardRouters.add(mongos);
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Exception getting mongos from cfg server(s): {0}", e);
    } finally {
        if (dbClient != null) {
            dbClient.close();
        }
    }
    return shardRouters;
}

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

private Boolean doIdsMatch(List<Pair<String, String>> keys, String json, String table) {
    DBObject obj = json != null && !json.equals("") ? (DBObject) JSON.parse(json) : null;

    if (obj == null) {
        return false;
    }//from   w ww.j av  a  2s  .c  om

    Collection<String> jsonFields = obj.keySet();
    for (Pair<String, String> key : keys) {
        String keyName = key.getKey();
        String jsonField = keyName.equals(":" + table) ? "id" : keyName.substring(1);

        if (!jsonFields.contains(jsonField) || !key.getValue().equals(obj.get(jsonField).toString())) {
            return false;
        }
        break;
    }

    return true;
}

From source file:com.callidusrobotics.droptables.model.DocumentDao.java

License:Open Source License

/**
 * Upserts a document into a collection. Creates the collection if it does not
 * exist. Creates the document if it does not exist.
 *
 * @param collectionName/*from w  ww .  j av  a  2s.com*/
 *          The collection to upsert to
 * @param document
 *          The document to upsert
 * @return ObjectId of the upserted document
 */
public ObjectId upsertDocument(String collectionName, DBObject document) {
    DBCollection collection = getCollection(collectionName);
    collection.insert(document);

    return (ObjectId) document.get(DOC_ID);
}

From source file:com.callidusrobotics.droptables.model.DocumentDao.java

License:Open Source License

protected static DBObject flatten(DBObject item) {
    item.put(DOC_ID, item.get(DOC_ID).toString());
    return item;
}

From source file:com.cc.manage.logic.BcompanyapplyLogic.java

/**
 * ???/*from w  w w .  j  a  v a  2  s . co  m*/
 * 
 * @param request ??
 * @return
 * @author Ron(modify 2014.10.17)
 */
public JSONObject list(HttpServletRequest request) {

    DBObject conditionBean = new BasicDBObject();
    // ?
    String inputname = RequestUtils.getString(request, "inputname");
    String state = RequestUtils.getString(request, "state");
    // ?
    BasicDBList values = new BasicDBList();

    if (StringUtils.isNotBlank(inputname)) {
        Pattern pattern = Pattern.compile("^.*" + inputname + ".*$", Pattern.CASE_INSENSITIVE);// ?
        values.add(new BasicDBObject("name", pattern));
        values.add(new BasicDBObject("contacts", pattern));
        conditionBean.put("$or", values);
    }

    if (StringUtils.isNotBlank(state)) {
        if (StringUtils.equals(state, "exists")) {
            //  ????
            conditionBean.put("state", new BasicDBObject("$exists", false));
        } else {
            conditionBean.put("state", state);
        }
    }

    // ?
    long count = companyapplyDao.count(TableNameConstant.T_COMPANY_APPLY, conditionBean);
    if (count <= 0) {
        return null;
    }

    // ? ??
    String sortOrder = RequestUtils.getString(request, "sortOrder");
    DBObject orderBy = new BasicDBObject();
    if (StringUtils.isNotBlank(sortOrder)) {// StringInt
        orderBy.put(RequestUtils.getString(request, "sortField"), StringUtils.setOrder(sortOrder));
    } else {
        orderBy.put("_id", StringUtils.setOrder("1"));
    }

    DBObject field = new BasicDBObject();
    List<DBObject> dbList = companyapplyDao.list(TableNameConstant.T_COMPANY_APPLY, conditionBean, field,
            orderBy, RequestUtils.getInt(request, "pageIndex") + 1, RequestUtils.getInt(request, "pageSize"));
    // ??
    Map<String, JSONObject> industryMap = this.ccIndustryinfoLogic.getIndustryInfoMap();
    // 
    Map<String, DBObject> areaMap = ccAreaLogic.getAreaMap();

    for (int i = 0; i < dbList.size(); i++) {
        DBObject dbobject = dbList.get(i);
        // ?id??
        if (CollectionUtils.isNotEmpty(industryMap)) {
            dbobject.put("industryName",
                    JSONUtils.getString(industryMap.get(dbobject.get("industryuuid")), "name"));
        }
        // 
        if (CollectionUtils.isNotEmpty(areaMap)) {
            dbobject.put("areaName", DBObejctUtils.getString(areaMap.get(dbobject.get("areauuid")), "name"));
        }
    }
    JSONObject resultBean = new JSONObject();
    JSONArray json = JSONUtils.resertJSON(dbList);// _id
    resultBean.put("data", json.toString());
    resultBean.put("total", count);
    return resultBean;
}

From source file:com.cc.manage.logic.BcompanyapplyLogic.java

/**
 * ????//from  w ww .ja va2  s  .c o  m
 * 
 * @param request ???
 * @return
 */
public String add(HttpServletRequest request) {
    DBObject conditionBean = new BasicDBObject();
    String data = RequestUtils.getString(request, "data");
    if (StringUtils.isNotBlank(data)) {
        JSONObject jsonBean = JSONObject.fromObject(data);
        // ????
        String id = JSONUtils.getString(jsonBean, "id");
        String remark = JSONUtils.getString(jsonBean, "remark");

        // 
        if (StringUtils.isBlank(id)) {
            // ?
            DBObject conditionBeannew = this.addBean(jsonBean);
            companyapplyDao.add(conditionBeannew);
            ObjectId objectId = (ObjectId) conditionBeannew.get("_id");
            if (objectId != null) {
                // ?
                conditionBean.put("_id", objectId);
                HistoryUtils.saveHistory(remark, request, TableNameConstant.T_COMPANY_APPLY, conditionBean);
                return ResultConstant.SUCCESS;

            } else {
                return ResultConstant.FAIL;
            }

        }
        // 
        else {
            DBObject conditionBeannew = this.addBean(jsonBean);
            conditionBean.put("_id", new ObjectId(id));
            companyapplyDao.update(conditionBean, conditionBeannew);
            // ??
            HistoryUtils.saveHistory(remark, request, TableNameConstant.T_COMPANY_APPLY, conditionBean);
            return ResultConstant.SUCCESS;
        }
    }
    return ResultConstant.FAIL;
}

From source file:com.cc.manage.logic.BcompanyapplyLogic.java

/**
 * ?//w  ww  .  j  a  v a  2 s.  c o  m
 * 
 * @param request
 */
public String check(HttpServletRequest request) {
    String data = RequestUtils.getString(request, "param");

    DBObject updateBean = new BasicDBObject();
    if (StringUtils.isNotBlank(data)) {
        JSONObject jsonBean = JSONObject.fromObject(data);
        String flowno = (String) jsonBean.get("flowno");
        String type = JSONUtils.getString(jsonBean, "type");

        if (AuditKey.AGREE_TYPE.equals(type)) {// ??
            DBObject queryBean = new BasicDBObject();
            queryBean.put("flowid", flowno);
            updateBean.put("state", StateConstant.B_COMPANY_APPLY_STATE1);// ??
            companyapplyDao.update(queryBean, updateBean);
            HistoryUtils.saveHistory("", request, "b_companyapply", queryBean);
            // ??
            List<DBObject> dbobject = companyapplyDao.find(TableNameConstant.T_COMPANY_APPLY, queryBean);
            DBObject object = dbobject.get(0);
            // ??
            object.put("companyno", String.valueOf(System.nanoTime()));
            DBObject stateBean = new BasicDBObject();
            stateBean.put("frame", StateConstant.B_COMPANY_UNALLOCAT);
            stateBean.put("role", StateConstant.B_COMPANY_UNALLOCAT);
            stateBean.put("product", StateConstant.B_COMPANY_UNALLOCAT);
            stateBean.put("companycc", StateConstant.B_COMPANY_UNALLOCAT);
            object.put("state", stateBean);
            object.removeField("_id");
            object.removeField("history");
            companyDao.add(object);
            HistoryUtils.saveHistory(object.get("history"), request, TableNameConstant.T_COMPANY,
                    new BasicDBObject());
        }
        JSONObject userSession = JSONObject
                .fromObject(request.getSession().getAttribute(SessionKey.SESSION_KEY_USER));
        if (userSession == null) {
            return ResultConstant.FAIL;
        }
        String uuid = JSONUtils.getString(userSession, "uuid"); // ?uuid
        jsonBean.put("uuid", uuid);

        AuditUtils.AuditRegister(jsonBean.toString());
        // ?
        return ResultConstant.SUCCESS;
    }
    return ResultConstant.FAIL;
}

From source file:com.ccoe.build.alerts.Compare.java

License:Apache License

public void judgeSingleRule(Rule rule, Condition current, Condition previous) {
    String collection = rule.getCollection();
    DBCollection dbc = Connector.connectCollection(db, collection);

    if (!StringUtils.isEmpty(rule.getCollectionPresentName())) {
        collection = rule.getCollectionPresentName();
    }// ww  w .ja  va 2  s .  c om

    DBObject totaldbo = Connector.getLastRecord(dbc, current.getStartDate(), current.getEndDate());

    String field = rule.getField();
    String operatorStr = rule.getOperator();

    Date oneWeekBack = DateUtils.getUTCOneWeekBack(current.getEndDate());
    double movingAverage = Connector.getMovingAverage(dbc, field, oneWeekBack, current.getEndDate());
    String flag = "";
    if (Connector.DAYS < 7) {
        //flag = "~";
    }

    if ("lt".equals(operatorStr)) {
        operatorStr = "<";
    } else if ("le".equals(operatorStr)) {
        operatorStr = "<=";
    } else if ("eq".equals(operatorStr)) {
        operatorStr = "=";
    } else if ("gt".equals(operatorStr)) {
        operatorStr = ">";
    } else if ("ge".equals(operatorStr)) {
        operatorStr = ">=";
    }

    String goalStr = rule.getGoal();
    String lowerLimit = rule.getLower();
    String upperLimit = rule.getUpper();
    // only support type double
    double lower = Double.parseDouble(lowerLimit);
    double upper = Double.parseDouble(upperLimit);
    DecimalFormat df = new DecimalFormat("##0.00");
    SingleResult singleResult = null;

    if (totaldbo == null) {
        singleResult = new SingleResult(collection, field, "N/A", lightRed, operatorStr, goalStr, lowerLimit,
                upperLimit, "N/A", flag);

        if (!StringUtils.isEmpty(rule.getFieldPresentName())) {
            singleResult.setField(rule.getFieldPresentName());
        }
        if (!StringUtils.isEmpty(rule.getLink())) {
            singleResult.setLink(rule.getLink());
        }
        alertResult.getResultlist().add(singleResult);
        return;
    }

    DBObject dbo = (DBObject) totaldbo.get("Data");
    Set<String> keyset = dbo.keySet();

    for (String keyname : keyset) {
        if (field.equals(keyname)) {
            Object keyvalue = dbo.get(keyname);
            double keyvaluenum = 0;
            if (keyvalue instanceof Integer) {
                int k1 = (Integer) keyvalue;
                keyvaluenum = Double.parseDouble("" + k1);
            } else if (keyvalue instanceof Double) {
                keyvaluenum = (Double) keyvalue;
            }

            String color = normalColor;
            if (keyvaluenum >= lower && keyvaluenum <= upper) {
                color = normalColor;
            } else if ((keyvaluenum < lower && "<=".equals(operatorStr))
                    || (keyvaluenum > upper && ">=".equals(operatorStr))) {
                color = lightGreen;
            } else if ((keyvaluenum < lower && ">=".equals(operatorStr))
                    || (keyvaluenum > upper && "<=".equals(operatorStr))) {
                color = lightRed;
            }
            singleResult = new SingleResult(collection, field, df.format(keyvaluenum), color, operatorStr,
                    goalStr, lowerLimit, upperLimit, df.format(movingAverage), flag);
        }
    }
    if (singleResult == null) {
        singleResult = new SingleResult(collection, field, "N/A", lightRed, operatorStr, goalStr, lowerLimit,
                upperLimit, "N/A", flag);
    }

    if (!StringUtils.isEmpty(rule.getFieldPresentName())) {
        singleResult.setField(rule.getFieldPresentName());
    }

    if (!StringUtils.isEmpty(rule.getLink())) {
        singleResult.setLink(rule.getLink());
    }
    alertResult.getResultlist().add(singleResult);
    return;
}

From source file:com.ccoe.build.alerts.connector.Connector.java

License:Apache License

public static double getMovingAverage(DBCollection collection, String field, Date startDate, Date endDate) {
    double weekSum = 0;
    DBObject record = null;
    int count = 0;
    try {/*  ww  w.ja  v  a2 s  . c  o m*/
        BasicDBObject searchQuery = new BasicDBObject();
        QueryBuilder qb = new QueryBuilder();
        qb.put("Date").greaterThanEquals(startDate).lessThanEquals(endDate);
        searchQuery.putAll(qb.get());
        DBCursor cursor = collection.find(searchQuery);

        while (cursor.hasNext()) {
            record = cursor.next();
            DBObject dbo = (DBObject) record.get("Data");
            Set<String> keySet = dbo.keySet();

            for (String keyName : keySet) {
                if (field.equals(keyName)) {
                    count++;
                    Object keyValue = dbo.get(keyName);
                    double keyValueNum = 0;
                    if (keyValue instanceof Integer) {
                        int intValue = (Integer) keyValue;
                        keyValueNum = Double.parseDouble("" + intValue);
                    } else if (keyValue instanceof Double) {
                        keyValueNum = (Double) keyValue;
                    }
                    weekSum += keyValueNum;
                }
            }
        }
    } catch (MongoException e) {
        e.printStackTrace();
    }
    DAYS = count;
    return weekSum * 1.0 / count;
}