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:br.bireme.tmp.AddPrettyField.java

License:Open Source License

private static void add(final String mongo_host, final int mongo_port, final String mongo_db,
        final String mongo_col) throws UnknownHostException {
    assert mongo_host != null;
    assert mongo_port > 0;
    assert mongo_db != null;
    assert mongo_col != null;

    final MongoClient client = new MongoClient(mongo_host, mongo_port);
    final DB db = client.getDB(mongo_db);
    final DBCollection coll = db.getCollection(HISTORY_COL);
    final DBCursor cursor = coll.find();
    int total = 0;

    System.out.println("host=" + mongo_host);
    System.out.println("port=" + mongo_port);
    System.out.println("database=" + mongo_db);
    System.out.println("collection=" + mongo_col);
    System.out.println("num of documents=" + cursor.size());

    while (cursor.hasNext()) {
        final BasicDBObject doc1 = (BasicDBObject) cursor.next();
        final BasicDBList list = (BasicDBList) doc1.get(ELEM_LST_FIELD);

        for (Object obj : list) {
            final BasicDBObject doc2 = (BasicDBObject) obj;
            if (!doc2.containsField(PRETTY_BROKEN_URL_FIELD)) {
                final String burl = doc2.getString(BROKEN_URL_FIELD);
                try {
                    final String pburl = EncDecUrl.decodeUrl(burl);
                    doc2.append(PRETTY_BROKEN_URL_FIELD, pburl);

                    final WriteResult wr = coll.save(doc1, WriteConcern.ACKNOWLEDGED);
                    if (wr.getCachedLastError().ok()) {
                        total++;//w ww .ja  v  a2  s .co  m
                    } else {
                        System.err.println("Document[" + doc1.getString("_id") + "] update error.");
                    }
                } catch (IOException ioe) {
                    System.err.println("Document[" + doc1.getString("_id") + "] bad encode conversion"
                            + " url=[" + burl + "]");
                }
            }
        }
    }
    cursor.close();
    System.out.println("num of added fields: " + total);
}

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

License:Apache License

/**
 * The method completes the attribute with the value found for one of the
 * entities in the list and returns true. If no value was found, the method
 * return false. If more than value was found, the one selected corresponds
 * to the first entity encountered in the list.
 * //from   w  w  w.j  a v a2  s .c o m
 * @param chronicles a list of chronicles
 * @param attribute an attribute 
 * @return true if any value found
 * @throws T2DBException
 */
public boolean getAttributeValue(List<Chronicle> chronicles, Attribute<?> attribute) throws T2DBException {
    boolean found = false;
    Surrogate s = attribute.getProperty().getSurrogate();
    Database db = s.getDatabase();
    try {
        ObjectId[] chrOids = new ObjectId[chronicles.size()];
        int offset = 0;
        for (Chronicle chronicle : chronicles) {
            chrOids[offset++] = getId(chronicle);
        }
        DBCursor cursor = getMongoDB(db).getAttributes().find(mongoObject(MongoDatabase.FLD_ATTR_PROP, getId(s),
                MongoDatabase.FLD_ATTR_CHRON, mongoObject(Operator.IN.op(), chrOids)));

        offset = Integer.MAX_VALUE;
        BasicDBObject objAtOffset = null;

        while (cursor.hasNext()) {
            BasicDBObject obj = (BasicDBObject) cursor.next();
            ObjectId chrOid = obj.getObjectId(MongoDatabase.FLD_ATTR_CHRON);
            int offset1 = findOffset(chrOid, chronicles);
            if (offset1 < offset) {
                offset = offset1;
                objAtOffset = obj;
            }
            if (offset == 0)
                break;
        }

        if (objAtOffset != null) {
            ObjectId chrOid = objAtOffset.getObjectId(MongoDatabase.FLD_ATTR_CHRON);
            Surrogate chronicle = makeSurrogate(db, DBObjectType.CHRONICLE, chrOid);
            check(Permission.READ, chronicle);
            attribute.scan(objAtOffset.getString(MongoDatabase.FLD_ATTR_VALUE));
            String description = objAtOffset.getString(MongoDatabase.FLD_ATTR_DESC);
            if (description.length() > 0)
                attribute.setDescription(description);
            found = true;
        }
    } catch (Exception e) {
        throw T2DBMsg.exception(e, E.E40120, attribute.getProperty().getName());
    }
    return found;
}

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

License:Apache License

private Chronicle unpack(Database db, BasicDBObject obj) throws T2DBException {
    try {//from  w  ww  . j  a v a  2s.com
        ObjectId id = obj.getObjectId(MongoDatabase.FLD_ID);
        Surrogate s = makeSurrogate(db, DBObjectType.CHRONICLE, id);
        ChronicleImpl.RawData data = new ChronicleImpl.RawData();
        data.setSurrogate(s);
        data.setName(obj.getString(MongoDatabase.FLD_CHRON_NAME));
        data.setDescription(obj.getString(MongoDatabase.FLD_CHRON_DESC));
        ObjectId parentId = obj.getObjectId(MongoDatabase.FLD_CHRON_PARENT);
        data.setCollection(parentId == null ? db.getTopChronicle()
                : new ChronicleImpl(makeSurrogate(db, DBObjectType.CHRONICLE, parentId)));
        ObjectId schemaId = obj.getObjectId(MongoDatabase.FLD_CHRON_SCHEMA);
        data.setSchema(schemaId == null ? null : makeSurrogate(db, DBObjectType.SCHEMA, schemaId));
        Chronicle chronicle = new ChronicleImpl(data);
        return chronicle;
    } catch (ClassCastException e) {
        throw T2DBMMsg.exception(e, J.J81010, obj.toString());
    }
}

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

License:Apache License

private <T> Property<T> unpack(Database db, BasicDBObject obj) throws T2DBException {
    try {/*from w w  w .java2s. co  m*/
        ObjectId id = obj.getObjectId(MongoDatabase.FLD_ID);
        String name = obj.getString(MongoDatabase.FLD_PROP_NAME);
        ObjectId vtId = obj.getObjectId(MongoDatabase.FLD_PROP_VT);
        Boolean indexed = obj.getBoolean(MongoDatabase.FLD_PROP_INDEXED);
        Surrogate vts = makeSurrogate(db, DBObjectType.VALUE_TYPE, new MongoDBObjectId(vtId));
        ValueType<T> vt = db.getValueType(vts);
        Surrogate s = makeSurrogate(db, DBObjectType.PROPERTY, new MongoDBObjectId(id));
        checkIntegrity(vt, vts, s);
        return new PropertyImpl<T>(name, vt, indexed, s);
    } catch (ClassCastException e) {
        throw T2DBMMsg.exception(e, J.J81010, obj.toString());
    }
}

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

License:Apache License

private UpdatableSchema unpack(Database db, BasicDBObject obj, Set<ObjectId> cycleDetector)
        throws T2DBException {
    if (cycleDetector == null)
        cycleDetector = new HashSet<ObjectId>();
    try {/*w  w w  .  j av  a 2  s.  c o  m*/
        ObjectId id = obj.getObjectId(MongoDatabase.FLD_ID);
        Surrogate s = makeSurrogate(db, DBObjectType.SCHEMA, new MongoDBObjectId(id));
        boolean cycleDetected = !cycleDetector.add(id);
        String name = obj.getString(MongoDatabase.FLD_SCHEMA_NAME);
        UpdatableSchema base = null;
        ObjectId baseId = obj.getObjectId(MongoDatabase.FLD_SCHEMA_BASE);
        if (baseId != null && !cycleDetected) {
            Surrogate baseSurr = makeSurrogate(db, DBObjectType.SCHEMA, new MongoDBObjectId(baseId));
            base = getSchema(baseSurr, cycleDetector);
        }
        Collection<AttributeDefinition<?>> attribs = attributeDefinitions(s, 0, db,
                (BasicDBList) obj.get(MongoDatabase.FLD_SCHEMA_ATTRIBS));
        Collection<SeriesDefinition> series = seriesDefinitions(s, db,
                (BasicDBList) obj.get(MongoDatabase.FLD_SCHEMA_SERIES));
        return new UpdatableSchemaImpl(name, base, attribs, series, s);
    } catch (ClassCastException e) {
        throw T2DBMMsg.exception(e, J.J81010, obj.toString());
    }
}

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

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
private AttributeDefinition<?> attributeDefinition(Surrogate schemaSurrogate, int seriesNr, Database db,
        BasicDBObject bo) throws T2DBException {
    int number = bo.getInt(MongoDatabase.FLD_ATTRIBDEF_NUM);
    boolean era = bo.getBoolean(MongoDatabase.FLD_ATTRIBDEF_ERASING);
    AttributeDefinitionImpl<?> def = null;
    if (era) {//from  www .  j av a2  s  .co  m
        def = new AttributeDefinitionImpl(seriesNr, number, null, null);
        def.edit();
        def.setErasing(true);
    } else {
        ObjectId propId = bo.getObjectId(MongoDatabase.FLD_ATTRIBDEF_PROP);
        Surrogate propSurr = makeSurrogate(db, DBObjectType.PROPERTY, new MongoDBObjectId(propId));
        Property<?> prop = ((MongoDatabase) db).getReadMethodsForProperty().getProperty(propSurr);
        String val = bo.getString(MongoDatabase.FLD_ATTRIBDEF_VAL);
        checkIntegrity(prop, propSurr, schemaSurrogate);
        def = new AttributeDefinitionImpl(seriesNr, number, prop, prop.getValueType().scan(val));
    }
    return def;
}

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

License:Apache License

private SeriesDefinition seriesDefinition(Surrogate schemaSurrogate, Database db, BasicDBObject bo)
        throws T2DBException {
    int number = bo.getInt(MongoDatabase.FLD_SERIESDEF_NUM);
    boolean era = bo.getBoolean(MongoDatabase.FLD_SERIESDEF_ERASING);
    SeriesDefinitionImpl def = null;// ww  w. j  av a  2  s  . c om
    if (era) {
        def = new SeriesDefinitionImpl(number, null, null);
        def.edit();
        def.setErasing(true);
    } else {
        String desc = bo.getString(MongoDatabase.FLD_SERIESDEF_DESC);
        BasicDBList list = (BasicDBList) bo.get(MongoDatabase.FLD_SERIESDEF_ATTRIBS);
        Collection<AttributeDefinition<?>> attribs = attributeDefinitions(schemaSurrogate, number, db, list);
        def = new SeriesDefinitionImpl(number, desc, attribs);
    }
    return def;
}

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

License:Apache License

@SuppressWarnings("unchecked")
private <T> ValueType<T> unpack(Database db, BasicDBObject obj) throws T2DBException {
    try {//from  w ww .j a  v  a 2  s  .  c  om
        ObjectId id = obj.getObjectId(MongoDatabase.FLD_ID);
        String name = obj.getString(MongoDatabase.FLD_VT_NAME);
        String type = obj.getString(MongoDatabase.FLD_VT_TYPE);
        Object values = obj.get(MongoDatabase.FLD_VT_VALUES);
        boolean restricted = values != null;
        Map<String, String> valueMap = null;
        if (restricted)
            valueMap = (Map<String, String>) ((BasicDBObject) values).toMap();
        Surrogate s = makeSurrogate(db, DBObjectType.VALUE_TYPE, new MongoDBObjectId(id));
        return new ValueTypeImpl<T>(name, restricted, type, valueMap, s);
    } catch (ClassCastException e) {
        throw T2DBMMsg.exception(e, J.J81010, obj.toString());
    }
}

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

License:Open Source License

private StationInfo createStationInfo(BasicDBObject stationJson) {
    StationInfo stationInfo = new StationInfo();

    stationInfo.setId(stationJson.getString("_id"));
    stationInfo.setShortName(stationJson.getString("short"));
    stationInfo.setName(stationJson.getString("name"));
    stationInfo.setDataValidity(getDataValidity(new DateTime()));
    stationInfo.setStationLocationType(StationLocationType.TAKEOFF);
    BasicDBList locationJson = (BasicDBList) stationJson.get("loc");
    stationInfo.setWgs84Longitude((Double) locationJson.get(0));
    stationInfo.setWgs84Latitude((Double) locationJson.get(1));
    ;//from   w ww .j  a v a 2 s  .co  m
    stationInfo.setAltitude(stationJson.getInt("alt"));
    stationInfo.setMaintenanceStatus(Status.fromValue(stationJson.getString("status")));

    return stationInfo;
}

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

License:Open Source License

@Override
public List<StationInfo> getStationInfoList(boolean allStation) throws DataSourceException {
    try {//from w ww.  j av  a2 s .  co m
        DBCollection stations = database.getCollection(getStationsCollectionName());

        List<String> list = new ArrayList<String>();
        if (allStation == true) {
            list.add(Status.RED.value());
            list.add(Status.ORANGE.value());
            list.add(Status.GREEN.value());
        } else {
            list.add(Status.GREEN.value());
        }
        DBObject query = BasicDBObjectBuilder.start("prov", getProvider())
                .add("status", new BasicDBObject("$in", list)).get();
        DBCursor cursor = stations.find(query);

        List<StationInfo> stationInfoList = new ArrayList<StationInfo>();
        while (cursor.hasNext()) {
            try {
                BasicDBObject stationJson = (BasicDBObject) cursor.next();
                if (getStationsFilter() != null) {
                    String stationId = stationJson.getString("_id");
                    if (getStationsFilter().contains(stationId)) {
                        stationInfoList.add(createStationInfo(stationJson));
                    }
                } else {
                    stationInfoList.add(createStationInfo(stationJson));
                }
            } catch (Exception e) {
                log.warn("Station was ignored because:", e);
            }
        }

        return stationInfoList;
    } catch (Exception e) {
        throw exceptionHandler(e);
    }
}