Example usage for com.mongodb BasicDBObject getLong

List of usage examples for com.mongodb BasicDBObject getLong

Introduction

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

Prototype

public long getLong(final String key) 

Source Link

Document

Returns the value of a field as a long .

Usage

From source file:gMIRC_handler.java

public String GetMessage(String username) {
    String ret = "";
    try {/*from   w  w w.  ja  v  a 2  s .c  o m*/
        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("inbox");
        BasicDBObject query = new BasicDBObject("target", username);
        JSONObject obj = new JSONObject();
        JSONArray arr = new JSONArray();
        DBCursor cursor = coll.find(query);

        try {
            while (cursor.hasNext()) {
                BasicDBObject temp = (BasicDBObject) cursor.next();
                JSONObject sav = new JSONObject();
                sav.put("target", temp.getString("target"));
                sav.put("username", temp.getString("username"));
                sav.put("channel", temp.getString("channel"));
                sav.put("message", temp.getString("message"));
                sav.put("timestamp", temp.getLong("timestamp"));
                arr.add(sav);
                coll.remove(temp);
            }
            obj.put("msg", arr);
            ret = obj.toJSONString();
        } finally {
            cursor.close();
        }
    } catch (UnknownHostException ex) {
        Logger.getLogger(gMIRC_handler.class.getName()).log(Level.SEVERE, null, ex);
    }
    UpdateLastActive(username);
    return ret;
}

From source file:ch.agent.crnickl.mongodb.AccessMethodsForNumber.java

License:Apache License

@Override
public Range getRange(Series<Double> series) throws T2DBException {
    Range range = null;/* w w w .  j  a va 2 s  . c  o  m*/
    try {
        check(Permission.READ, series);
        Surrogate s = series.getSurrogate();
        BasicDBObject obj = (BasicDBObject) getObject(s, false);
        if (obj != null) {
            long first = obj.getLong(MongoDatabase.FLD_SER_FIRST);
            long last = obj.getLong(MongoDatabase.FLD_SER_LAST);
            range = new Range(series.getTimeDomain(), first, last);
        }
    } catch (Exception e) {
        throw T2DBMsg.exception(e, E.E50122, series.getName(true));
    }
    if (range == null)
        range = new Range(series.getTimeDomain());
    return range;
}

From source file:ch.agent.crnickl.mongodb.AccessMethodsForNumber.java

License:Apache License

private Observation<Double> extractLastValue(BasicDBObject obj, TimeDomain domain, TimeIndex t)
        throws Exception {
    long first = obj.getLong(MongoDatabase.FLD_SER_FIRST);
    long last = obj.getLong(MongoDatabase.FLD_SER_LAST);
    Observation<Double> obs = null;
    long time = t == null ? last : t.asLong();
    if (last >= first && time >= first) {
        @SuppressWarnings("unchecked")
        Map<String, Double> values = (Map<String, Double>) obj.get(MongoDatabase.FLD_SER_VALUES);
        String key = null;/*from ww w  .jav  a 2 s.  c om*/
        if (time >= last)
            key = Long.toString(last);
        else {
            TreeMap<String, Double> sorted = new TreeMap<String, Double>(values);
            key = sorted.headMap(Long.toString(time + 1)).lastKey();
        }
        obs = new Observation<Double>(domain.time(Long.valueOf(key)), values.get(key));
    }
    return obs;
}

From source file:ch.agent.crnickl.mongodb.AccessMethodsForNumber.java

License:Apache License

private Observation<Double> extractFirstValue(BasicDBObject obj, TimeDomain domain, TimeIndex t)
        throws Exception {
    long first = obj.getLong(MongoDatabase.FLD_SER_FIRST);
    long last = obj.getLong(MongoDatabase.FLD_SER_LAST);
    Observation<Double> obs = null;
    long time = t == null ? first : t.asLong();
    if (last >= first && time <= last) {
        @SuppressWarnings("unchecked")
        Map<String, Double> values = (Map<String, Double>) obj.get(MongoDatabase.FLD_SER_VALUES);
        String key = null;//  ww w  .  j a va 2s  .  co  m
        if (time <= first)
            key = Long.toString(first);
        else {
            TreeMap<String, Double> sorted = new TreeMap<String, Double>(values);
            key = sorted.tailMap(Long.toString(time)).firstKey();
        }
        obs = new Observation<Double>(domain.time(Long.valueOf(key)), values.get(key));
    }
    return obs;
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

private DateTime getLastUpdateDateTime(BasicDBObject lastDataJson) {
    return new DateTime(lastDataJson.getLong("_id") * 1000);
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

private StationData createStationData(String stationId) throws DataSourceException {
    BasicDBObject stationJson = findStationJson(stationId);
    BasicDBObject lastDataJson = (BasicDBObject) stationJson.get("last");
    if (lastDataJson == null) {
        throw new DataSourceException(DataSourceException.Error.INVALID_DATA,
                "No last data for station '" + stationId + "'");
    }/*from  w  w w .  j  a v  a  2s  .  co m*/

    StationData stationData = new StationData();
    stationData.setStationId(stationId);

    DateTime lastUpdate = getLastUpdateDateTime(lastDataJson);
    stationData.setLastUpdate(lastUpdate);
    DateTime now = new DateTime();
    DateTime expirationDate = getExpirationDate(now, lastUpdate);
    stationData.setExpirationDate(expirationDate);

    // Status
    stationData.setStatus(getDataStatus(stationJson.getString("status"), now, expirationDate));

    // Wind average
    stationData.setWindAverage((float) lastDataJson.getDouble(DataTypeConstant.windAverage.getJsonKey()));

    // Wind max
    stationData.setWindMax((float) lastDataJson.getDouble(DataTypeConstant.windMax.getJsonKey()));

    List<BasicDBObject> datas = getHistoricData(stationId, lastUpdate, getHistoricDuration());
    if (datas.size() > 0) {
        // Wind direction chart
        Serie windDirectionSerie = createSerie(datas, DataTypeConstant.windDirection.getJsonKey());
        windDirectionSerie.setName(DataTypeConstant.windDirection.getName());
        Chart windDirectionChart = new Chart();
        windDirectionChart.setDuration(getHistoricDuration());
        windDirectionChart.getSeries().add(windDirectionSerie);
        stationData.setWindDirectionChart(windDirectionChart);

        // Wind history min/average
        double minValue = Double.MAX_VALUE;
        double maxValue = Double.MIN_VALUE;
        double sum = 0;
        double[][] windTrendMaxDatas = new double[datas.size()][2];
        // double[][] windTrendAverageDatas = new double[windAverageDatas.size()][2];
        for (int i = 0; i < datas.size(); i++) {
            BasicDBObject data = datas.get(i);
            // JDC unix-time is in seconds, windmobile java-time in millis
            long millis = data.getLong("_id") * 1000;
            double windAverage = data.getDouble(DataTypeConstant.windAverage.getJsonKey());
            double windMax = data.getDouble(DataTypeConstant.windMax.getJsonKey());
            minValue = Math.min(minValue, windAverage);
            maxValue = Math.max(maxValue, windMax);
            sum += windAverage;
            windTrendMaxDatas[i][0] = millis;
            windTrendMaxDatas[i][1] = windMax;
        }
        stationData.setWindHistoryMin((float) minValue);
        stationData.setWindHistoryAverage((float) (sum / datas.size()));
        stationData.setWindHistoryMax((float) maxValue);

        // Wind trend
        LinearRegression linearRegression = new LinearRegression(windTrendMaxDatas);
        linearRegression.compute();
        double slope = linearRegression.getBeta1();
        double angle = Math.toDegrees(Math.atan(slope * getWindTrendScale()));
        stationData.setWindTrend((int) Math.round(angle));
    }

    // Air temperature
    stationData.setAirTemperature(
            (float) lastDataJson.getDouble(DataTypeConstant.airTemperature.getJsonKey(), -1));

    // Air humidity
    stationData.setAirHumidity((float) lastDataJson.getDouble(DataTypeConstant.airHumidity.getJsonKey(), -1));

    // Air pressure
    String key = DataTypeConstant.airPressure.getJsonKey();
    if (lastDataJson.containsField(key)) {
        stationData.setAirPressure((float) lastDataJson.getDouble(key));
    }

    // Rain
    key = DataTypeConstant.rain.getJsonKey();
    if (lastDataJson.containsField(key)) {
        stationData.setRain((float) lastDataJson.getDouble(key));
    }

    return stationData;
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

private Serie createSerie(List<BasicDBObject> datas, String key) {
    Serie serie = new Serie();
    for (BasicDBObject data : datas) {
        Point newPoint = new Point();
        // JDC unix-time is in seconds, windmobile java-time in millis
        newPoint.setDate(data.getLong("_id") * 1000);
        newPoint.setValue(((Number) data.get(key)).floatValue());
        serie.getPoints().add(newPoint);
    }/*w w  w. jav a 2 s . c  om*/
    return serie;
}

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

License:Apache License

public void shardingDistribution(ButtonBase button) {
    final DB config = getCollectionNode().getCollection().getDB().getSisterDB("config");

    new DbJob() {
        @Override/*  ww  w .ja v  a  2s.  c  o m*/
        public Object doRun() throws Exception {
            BasicDBObject result = new BasicDBObject();
            BasicDBList shardList = new BasicDBList();
            BasicDBObject stats = getStats();
            BasicDBObject shards = (BasicDBObject) stats.get("shards");
            if (shards == null || shards.isEmpty())
                return null;

            long totalChunks = 0;
            long totalSize = stats.getLong("size");
            long totalCount = stats.getLong("count");

            for (Entry shard : shards.entrySet()) {
                String shardName = (String) shard.getKey();
                BasicDBObject shardStats = (BasicDBObject) shard.getValue();

                BasicDBObject query = new BasicDBObject("ns",
                        getCollectionNode().getCollection().getFullName());
                query.put("shard", shardName);
                long numChunks = config.getCollection("chunks").count(query);
                totalChunks += numChunks;

                double estChunkData = numChunks <= 0 ? 0 : shardStats.getLong("size") / numChunks;
                long estChunkCount = numChunks <= 0 ? 0
                        : (long) Math.floor(shardStats.getLong("count") / numChunks);

                BasicDBObject shardDetails = new BasicDBObject("shard", shardName);
                shardDetails.put("data", shardStats.getLong("size"));
                shardDetails.put("pctData",
                        totalSize <= 0 ? 0 : (shardStats.getLong("size") * 100.0) / totalSize);
                shardDetails.put("docs", shardStats.getLong("count"));
                shardDetails.put("pctDocs",
                        totalCount <= 0 ? 0 : (shardStats.getLong("count") * 100.0) / totalCount);
                shardDetails.put("chunks", numChunks);
                if (shardStats.containsField("avgObjSize"))
                    shardDetails.put("avgDocSize", shardStats.getDouble("avgObjSize"));
                shardDetails.put("estimatedDataPerChunk", estChunkData);
                shardDetails.put("estimatedDocsPerChunk", estChunkCount);
                shardList.add(shardDetails);
            }
            result.put("shards", shardList);

            BasicDBObject total = new BasicDBObject();
            total.put("data", totalSize);
            total.put("docs", totalCount);
            total.put("chunks", totalChunks);
            total.put("avgDocSize", stats.getDouble("avgObjSize"));
            result.put("total", total);
            return result;
        }

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

        @Override
        public String getShortName() {
            return "Sharding Distribution";
        }
    }.addJob();
}

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

License:Apache License

public void settings(ButtonBase button) {
    FormDialog dialog = (FormDialog) ((MenuItem) getBoundUnit(Item.settings)).getDialog();
    BasicDBObject index = (BasicDBObject) getIndexInfo();
    boolean isTTL = false;
    long ttl = 0;
    if (index.containsField("expireAfterSeconds")) {
        isTTL = true;/*from w w w  . ja va 2s. c o  m*/
        ttl = index.getLong("expireAfterSeconds");
    }
    setLongFieldValue(Item.expireAfterSeconds, ttl);
    if (!dialog.show())
        return;

    long newTTL = getLongFieldValue(Item.expireAfterSeconds);
    if (newTTL != ttl) {
        BasicDBObject cmd = new BasicDBObject("collMod",
                getIndexNode().getCollectionNode().getCollection().getName());
        BasicDBObject param = new BasicDBObject();
        param.put("keyPattern", (DBObject) index.get("key"));
        param.put("expireAfterSeconds", newTTL);
        cmd.put("index", param);
        new DbJobCmd(getIndexNode().getCollectionNode().getCollection().getDB(), cmd).addJob();
    }
}

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

License:Apache License

public static DBObject getReplicaSetInfo(MongoClient mongo) {
    DB db = mongo.getDB("local");
    DBObject result = new BasicDBObject();
    DBCollection namespaces = db.getCollection("system.namespaces");
    String oplogName;//w  ww  . j a v  a 2  s.  c  om
    if (namespaces.findOne(new BasicDBObject("name", "local.oplog.rs")) != null) {
        oplogName = "oplog.rs";
    } else if (namespaces.findOne(new BasicDBObject("name", "local.oplog.$main")) != null) {
        oplogName = "oplog.$main";
    } else {
        return null;
    }
    DBObject olEntry = namespaces.findOne(new BasicDBObject("name", "local." + oplogName));
    if (olEntry != null && olEntry.containsField("options")) {
        BasicDBObject options = (BasicDBObject) olEntry.get("options");
        long size = options.getLong("size");
        result.put("logSizeMB", Float.valueOf(String.format("%.2f", size / 1048576f)));
    } else {
        return null;
    }
    DBCollection oplog = db.getCollection(oplogName);
    int size = oplog.getStats().getInt("size");
    result.put("usedMB", Float.valueOf(String.format("%.2f", size / 1048576f)));

    DBCursor firstc = oplog.find().sort(new BasicDBObject("$natural", 1)).limit(1);
    DBCursor lastc = oplog.find().sort(new BasicDBObject("$natural", -1)).limit(1);
    if (!firstc.hasNext() || !lastc.hasNext()) {
        return null;
    }
    BasicDBObject first = (BasicDBObject) firstc.next();
    BasicDBObject last = (BasicDBObject) lastc.next();
    BSONTimestamp tsfirst = (BSONTimestamp) first.get("ts");
    BSONTimestamp tslast = (BSONTimestamp) last.get("ts");
    if (tsfirst == null || tslast == null) {
        return null;
    }

    int ftime = tsfirst.getTime();
    int ltime = tslast.getTime();
    int timeDiffSec = ltime - ftime;
    result.put("timeDiff", timeDiffSec);
    result.put("timeDiffHours", Float.valueOf(String.format("%.2f", timeDiffSec / 3600f)));
    result.put("tFirst", new Date(ftime * 1000l));
    result.put("tLast", new Date(ltime * 1000l));
    result.put("now", new Date());
    return result;
}