Example usage for com.mongodb BasicDBObject getString

List of usage examples for com.mongodb BasicDBObject getString

Introduction

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

Prototype

public String getString(final String key) 

Source Link

Document

Returns the value of a field as a string

Usage

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 + "'");
    }/* ww  w .ja v  a2 s  . com*/

    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:com.andiandy.m101j.week2.hw3.SessionDAO.java

License:Apache License

public String startSession(String username) {

    // get 32 byte random number. that's a lot of bits.
    SecureRandom generator = new SecureRandom();
    byte randomBytes[] = new byte[32];
    generator.nextBytes(randomBytes);// w  w  w  .ja v  a 2 s  .co  m

    String sessionID = Base64.encodeBase64(randomBytes).toString();

    // build the BSON object
    BasicDBObject session = new BasicDBObject("username", username);

    session.append("_id", sessionID);

    sessionsCollection.insert(session);

    return session.getString("_id");
}

From source file:com.andiandy.m101j.week3.hw2_3.SessionDAO.java

License:Apache License

public String startSession(String username) {

    String sessionID = generateSessionID();

    // build the BSON object
    BasicDBObject session = new BasicDBObject("username", username);

    session.append("_id", sessionID);

    sessionsCollection.insert(session);//from   w ww  .j av a2 s  . c o  m

    return session.getString("_id");
}

From source file:com.andiandy.m101j.week4.course.SessionDAO.java

License:Apache License

public String startSession(String username) {

    String sessionID = getSessionID();

    // build the BSON object
    BasicDBObject session = new BasicDBObject("username", username);

    session.append("_id", sessionID);

    sessionsCollection.insert(session);//from ww w. j a  v a2  s.  com

    return session.getString("_id");
}

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

License:Apache License

/**
 * Insert the document in a collection/*from w  ww  .j  a  va2 s.com*/
 *
 * @param document
 * @return the <code>_id</code> of the inserted document, <code>null</code>
 * if fails.
 */
public String insert(Object document) {
    String _id = null;
    if (document == null) {
        return _id;
    }
    try {
        BasicDBObject obj = loadDocument(document);
        String collectionName = reflectCollectionName(document);
        db.getCollection(collectionName).insert(obj);
        _id = obj.getString("_id");
        Field field = getFieldByAnnotation(document, ObjectId.class, false);
        if (field != null) {
            field.setAccessible(true);
            field.set(document, _id);
        }
        indexFields(document);
    } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException
            | SecurityException | IllegalArgumentException | NoSuchFieldException ex) {
        LOG.log(Level.SEVERE, "An error occured while inserting this document: {0}", ex.getMessage());
    }
    if (_id != null) {
        LOG.log(Level.INFO, "Object \"{0}\" inserted successfully.", _id);
    }
    return _id;
}

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

License:Apache License

public String save(Object document) {
    //TODO: a better way to throw/treat exceptions
    /*if (!document.getClass().isAnnotationPresent(Document.class)) {
     throw new NoSuchMongoCollectionException(document.getClass() + " is not a valid Document.");
     }*///from www. ja  v  a 2 s.c  om
    String _id = null;
    if (document == null) {
        return _id;
    }
    try {
        BasicDBObject obj = loadDocument(document);
        String collectionName = reflectCollectionName(document);
        db.getCollection(collectionName).save(obj);
        _id = obj.getString("_id");
        indexFields(document);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
        LOG.log(Level.SEVERE, "An error occured while saving this document: {0}", ex.getMessage());
    }
    if (_id != null) {
        LOG.log(Level.INFO, "Object \"{0}\" saved successfully.", _id);
    }
    return _id;
}

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

License:Open Source License

private List<String> getShardsFromMongos(final String host, final int port) throws Exception {

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

    final CommandResult cr = dbAdminCmd(host, port, "listShards");

    if (cr.ok()) {
        final BasicDBList shardList = (BasicDBList) cr.get("shards");
        for (Object obj : shardList) {
            final BasicDBObject bdbo = (BasicDBObject) obj;
            String shards = bdbo.getString("host");
            if (shards.indexOf("/") != -1) {
                final String[] shardMembers = shards.split("/")[1].split(",");
                for (String member : shardMembers) {
                    final MongoServer ms = new MongoServer(member);
                    shardResult.addAll(discoverReplicas(ms.getHost(), ms.getPort()));
                }//w  w  w.  j  a va 2s  . c om
            } else {
                // single node shard
                shardResult.add(shards);
            }
        }
    }
    return shardResult;
}

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

License:Apache License

@Override
public void run() {

    String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbchecks");
    db = m.getDB(dbName);//from w  ww.j a  v  a 2  s .  c  o m

    logger.info("Started MongoCheckWorker");

    while (true) {
        try {
            BasicDBObject doc = mongo_check_queue.take();
            if (doc != null) {

                // index
                if (doc.getString("type").equals("check")) {
                    col = db.getCollection(doc.getString("user_id") + "cid" + doc.getString("cid"));
                } else {
                    col = db.getCollection(doc.getString("user_id") + "traces" + doc.getString("cid"));
                }
                doc.removeField("user_id");
                doc.removeField("type");

                col.insert(doc);
                if (logMore) {
                    logger.info("Mongo: Wrote " + doc.getString("hread") + " / " + doc.getString("cid"));
                }
                //db.requestDone();
            } else {
                Thread.sleep(50);
            }

        } catch (Exception ex) {
            logger.fatal("Error in MongoCheckWorker: " + ex.getLocalizedMessage());
            ex.printStackTrace();
        }

    }
}

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

License:Apache License

@Override
public void run() {

    String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbessentials");
    db = m.getDB(dbName);/*from   w  ww  . j av  a 2  s  .  c o  m*/

    logger.info("Started MongoWorker for MuninMX Essentials");
    String plugin = "";
    while (true) {
        try {
            BasicDBObject doc = mongo_essential_queue.take();
            if (doc != null) {
                // if trackpkg, add package entry, if essential information, store somewhere else
                if (doc.getString("type").equals("trackpkg")) {
                    col = db.getCollection("trackpkg");
                    doc.removeField("type");
                } else {
                    col = db.getCollection(doc.getString("node") + "_ess");
                    doc.removeField("node");
                    doc.removeField("type");
                }

                col.insert(doc);
                if (logMore) {
                    logger.info("Mongo: Wrote " + plugin + " / " + doc.getString("graph") + " / "
                            + doc.getString("value"));
                }
                //db.requestDone();
            } else {
                Thread.sleep(50);
            }

        } catch (Exception ex) {
            logger.fatal("Error in MongoEssentialWorker: " + ex.getLocalizedMessage());
            ex.printStackTrace();
        }

    }
}

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

License:Apache License

@Override
public void run() {

    String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbname");
    db = m.getDB(dbName);//from w w  w .j  a va 2  s.  co m

    logger.info("Started MongoWorker");
    String plugin = "";
    while (true) {
        try {
            BasicDBObject doc = mongo_queue.take();
            if (doc != null) {
                plugin = doc.getString("plugin");
                // each hostname got its own collection
                col = db.getCollection(doc.getString("user_id") + "_" + doc.getString("nodeid"));
                doc.removeField("hostname");
                doc.removeField("nodeid");
                doc.removeField("user_id");
                //doc.removeField("plugin");
                //db.requestStart();
                col.insert(doc);
                if (logMore) {
                    logger.info("Mongo: Wrote " + plugin + " / " + doc.getString("graph") + " / "
                            + doc.getString("value"));
                }
                //db.requestDone();
            } else {
                Thread.sleep(50);
            }

        } catch (Exception ex) {
            logger.fatal("Error in MongoWorker: " + ex.getLocalizedMessage());
            ex.printStackTrace();
        }

    }
}