Example usage for com.mongodb BasicDBList put

List of usage examples for com.mongodb BasicDBList put

Introduction

In this page you can find the example usage for com.mongodb BasicDBList put.

Prototype

@Override
public Object put(final String key, final Object v) 

Source Link

Document

Puts a value at an index.

Usage

From source file:act.server.MongoDB.java

License:Open Source License

public static BasicDBObject createReactionDoc(Reaction r, int id) {
    BasicDBObject doc = new BasicDBObject();
    doc.put("_id", id);
    doc.put("ecnum", r.getECNum());
    doc.put("easy_desc", r.getReactionName());

    BasicDBList substr = new BasicDBList();
    Long[] ss = r.getSubstrates();
    for (int i = 0; i < ss.length; i++) {
        DBObject o = getObject("pubchem", ss[i]);
        o.put("coefficient", r.getSubstrateCoefficient(ss[i]));
        substr.put(i, o);
    }/*  w ww.  ja  v  a 2 s  .  c o m*/

    BasicDBList prods = new BasicDBList();
    Long[] pp = r.getProducts();
    for (int i = 0; i < pp.length; i++) {
        DBObject o = getObject("pubchem", pp[i]);
        o.put("coefficient", r.getProductCoefficient(pp[i]));
        prods.put(i, o);
    }

    BasicDBList prodCofactors = new BasicDBList();
    Long[] ppc = r.getProductCofactors();
    for (int i = 0; i < ppc.length; i++) {
        DBObject o = getObject("pubchem", ppc[i]);
        prodCofactors.put(i, o);
    }

    BasicDBList substrCofactors = new BasicDBList();
    Long[] ssc = r.getSubstrateCofactors();
    for (int i = 0; i < ssc.length; i++) {
        DBObject o = getObject("pubchem", ssc[i]);
        substrCofactors.put(i, o);
    }

    BasicDBList coenzymes = new BasicDBList();
    Long[] coenz = r.getCoenzymes();
    for (int i = 0; i < coenz.length; i++) {
        DBObject o = getObject("pubchem", coenz[i]);
        coenzymes.put(i, o);
    }

    BasicDBObject enz = new BasicDBObject();
    enz.put("products", prods);
    enz.put("substrates", substr);
    enz.put("product_cofactors", prodCofactors);
    enz.put("substrate_cofactors", substrCofactors);
    enz.put("coenzymes", coenzymes);
    doc.put("enz_summary", enz);

    doc.put("is_abstract", r.getRxnDetailType().name());

    if (r.getDataSource() != null)
        doc.put("datasource", r.getDataSource().name());

    if (r.getMechanisticValidatorResult() != null) {
        doc.put("mechanistic_validator_result", MongoDBToJSON.conv(r.getMechanisticValidatorResult()));
    }

    BasicDBList refs = new BasicDBList();
    for (P<Reaction.RefDataSource, String> ref : r.getReferences()) {
        BasicDBObject refEntry = new BasicDBObject();
        refEntry.put("src", ref.fst().toString());
        refEntry.put("val", ref.snd());
        refs.add(refEntry);
    }
    doc.put("references", refs);

    BasicDBList proteins = new BasicDBList();
    for (JSONObject proteinData : r.getProteinData()) {
        proteins.add(MongoDBToJSON.conv(proteinData));
    }
    doc.put("proteins", proteins);
    ConversionDirectionType cd = r.getConversionDirection();
    doc.put("conversion_direction", cd == null ? null : cd.toString());
    StepDirection psd = r.getPathwayStepDirection();
    doc.put("pathway_step_direction", psd == null ? null : psd.toString());

    return doc;
}

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

License:Apache License

private BasicDBList attributeDefinitions(Collection<AttributeDefinition<?>> defs) throws T2DBException {
    BasicDBList list = new BasicDBList();
    if (defs != null) {
        int i = 0;
        for (AttributeDefinition<?> def : defs) {
            list.put(i++, attributeDefinition(def));
        }//from  ww  w  . j av a  2 s  .co m
    }
    return list;
}

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

License:Apache License

private BasicDBList seriesDefinitions(Collection<SeriesDefinition> defs) throws T2DBException {
    BasicDBList list = new BasicDBList();
    if (defs != null) {
        int i = 0;
        for (SeriesDefinition def : defs) {
            list.put(i++, seriesDefinition(def));
        }/* w  ww  .j  a  va2  s  .c o m*/
    }
    return list;
}

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

License:Apache License

public void rsReconfigure(ButtonBase button) throws Exception {
    ReplSetNode replset = (ReplSetNode) getServerNode().getParentNode();
    final DBCollection col = replset.getMongoClient().getDB("local").getCollection("system.replset");
    DBObject config = col.findOne();//from   www. j a  v  a2 s.  c  o  m

    BasicDBList members = (BasicDBList) config.get("members");
    int i = 0;
    String myhost = getServerNode().getServerAddress().getHost() + ":"
            + getServerNode().getServerAddress().getPort();
    for (; i < members.size(); ++i) {
        if (myhost.equals(((DBObject) members.get(i)).get("host")))
            break;
    }

    if (i == members.size()) {
        throw new Exception("No such server in configuration");
    }

    ReplicaDialog dia = UMongo.instance.getGlobalStore().getReplicaDialog();
    BasicDBObject oldConf = (BasicDBObject) members.get(i);
    dia.updateFromReplicaConfig(oldConf);
    if (!dia.show())
        return;
    BasicDBObject conf = dia.getReplicaConfig(oldConf.getInt("_id"));
    members.put(i, conf);

    ReplSetPanel.reconfigure(replset, config);
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MDbResultSet.java

License:Open Source License

public String getString(String columnName) throws OdaException {
    Object columnValue = getFieldValue(columnName);
    if (columnValue instanceof String)
        return (String) columnValue;

    if (columnValue instanceof List && !(columnValue instanceof BasicDBList)) {
        // convert generic List to JSON-formattable list
        List<?> fromList = (List<?>) columnValue;
        if (!fromList.isEmpty()) {
            BasicDBList fieldValuesList = new BasicDBList();
            for (int index = 0; index < fromList.size(); index++) {
                fieldValuesList.put(index, fromList.get(index));
            }// w w  w  .j  ava 2 s . com
            fieldValuesList.markAsPartialObject();
            return fieldValuesList.toString(); // return JSON expr format
        }
    }

    if (columnValue instanceof byte[])
        return convertToString((byte[]) columnValue);

    return columnValue != null ? columnValue.toString() : null;
}

From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.ResultDataHandler.java

License:Open Source License

private static BasicDBList fetchFieldValuesFromList(String fieldFullName, BasicDBList fromDBList) {
    if (fromDBList == null || fromDBList.size() == 0)
        return null;

    // get the named field value from each element in given array list
    BasicDBList fieldValuesList = new BasicDBList();
    if (fromDBList.isPartialObject())
        fieldValuesList.markAsPartialObject();

    for (int index = 0; index < fromDBList.size(); index++) {
        Object listElementObj = fromDBList.get(String.valueOf(index));
        if (listElementObj instanceof DBObject) // nested complex object, e.g. document
            listElementObj = fetchFieldValues(fieldFullName, (DBObject) listElementObj);
        fieldValuesList.put(index, listElementObj);
    }/*from w  ww . j a  va2 s.  c o m*/

    // check if at least one field value in list is not null, return the list
    for (Object elementValue : fieldValuesList.toMap().values()) {
        if (elementValue != null)
            return fieldValuesList;
    }

    return null; // all values in list is null
}

From source file:org.jongo.json.JsonQueryFactory.java

License:Apache License

private DBObject marshallArray(Object[] parameters) {
    BasicDBList list = new BasicDBList();
    for (int i = 0; i < parameters.length; i++) {
        list.put(i, marshallParameter(parameters[i], false));
    }/*from w  w  w.j av a 2 s.c o  m*/
    return list;
}

From source file:org.pentaho.di.trans.steps.mongodboutput.MongoDbOutputData.java

License:Open Source License

/**
 * Converts a kettle row to a Mongo Object for inserting/updating
 *
 * @param fieldDefs                the document field definitions
 * @param inputMeta                the incoming row format
 * @param row                      the current incoming row
 * @param vars                     environment variables
 * @param topLevelStructure        the top level structure of the Mongo document
 * @param hasTopLevelJSONDocInsert true if the user-specified paths include a single incoming Kettle field value that
 *                                 contains a JSON document that is to be inserted as is
 * @return a DBObject encapsulating the document to insert/upsert or null if there are no non-null incoming fields
 * @throws KettleException if a problem occurs
 *///from   w w w . ja va2  s.c om
protected static DBObject kettleRowToMongo(List<MongoDbOutputMeta.MongoField> fieldDefs,
        RowMetaInterface inputMeta, Object[] row, VariableSpace vars, MongoTopLevel topLevelStructure,
        boolean hasTopLevelJSONDocInsert) throws KettleException {

    // the easy case
    if (hasTopLevelJSONDocInsert) {
        for (MongoDbOutputMeta.MongoField f : fieldDefs) {
            if (f.m_JSON && Const.isEmpty(f.m_mongoDocPath) && !f.m_useIncomingFieldNameAsMongoFieldName) {
                String incomingFieldName = vars.environmentSubstitute(f.m_incomingFieldName);
                int index = inputMeta.indexOfValue(incomingFieldName);
                ValueMetaInterface vm = inputMeta.getValueMeta(index);
                if (!vm.isNull(row[index])) {
                    String jsonDoc = vm.getString(row[index]);
                    DBObject docToInsert = (DBObject) JSON.parse(jsonDoc);
                    return docToInsert;
                } else {
                    return null;
                }
            }
        }
    }

    DBObject root = null;
    if (topLevelStructure == MongoTopLevel.RECORD) {
        root = new BasicDBObject();
    } else if (topLevelStructure == MongoTopLevel.ARRAY) {
        root = new BasicDBList();
    }

    if (vars == null) {
        vars = new Variables();
    }

    boolean haveNonNullFields = false;
    for (MongoDbOutputMeta.MongoField field : fieldDefs) {
        DBObject current = root;

        field.reset();
        List<String> pathParts = field.m_tempPathList;
        String incomingFieldName = vars.environmentSubstitute(field.m_incomingFieldName);
        int index = inputMeta.indexOfValue(incomingFieldName);
        ValueMetaInterface vm = inputMeta.getValueMeta(index);

        Object lookup = getPathElementName(pathParts, current, field.m_useIncomingFieldNameAsMongoFieldName);
        do {
            // array?
            if (lookup != null && lookup instanceof Integer) {
                BasicDBList temp = (BasicDBList) current;
                if (temp.get(lookup.toString()) == null) {
                    if (pathParts.size() == 0 && !field.m_useIncomingFieldNameAsMongoFieldName) {
                        // leaf - primitive element of the array (unless kettle field
                        // value is JSON)
                        boolean res = setMongoValueFromKettleValue(temp, lookup, vm, row[index], field.m_JSON,
                                field.insertNull);
                        haveNonNullFields = (haveNonNullFields || res);
                    } else {
                        // must be a record here (since multi-dimensional array creation
                        // is handled
                        // in getPathElementName())

                        // need to create this record/object
                        BasicDBObject newRec = new BasicDBObject();
                        temp.put(lookup.toString(), newRec);
                        current = newRec;

                        // end of the path?
                        if (pathParts.size() == 0) {
                            if (field.m_useIncomingFieldNameAsMongoFieldName) {
                                boolean res = setMongoValueFromKettleValue(current, incomingFieldName, vm,
                                        row[index], field.m_JSON, field.insertNull);
                                haveNonNullFields = (haveNonNullFields || res);
                            } else {
                                throw new KettleException(BaseMessages.getString(PKG,
                                        "MongoDbOutput.Messages.Error.NoFieldNameSpecifiedForPath")); //$NON-NLS-1$
                            }
                        }
                    }
                } else {
                    // existing element of the array
                    current = (DBObject) temp.get(lookup.toString());

                    // no more path parts so we must be setting a field in an array
                    // element
                    // that is a record
                    if (pathParts == null || pathParts.size() == 0) {
                        if (current instanceof BasicDBObject) {
                            if (field.m_useIncomingFieldNameAsMongoFieldName) {
                                boolean res = setMongoValueFromKettleValue(current, incomingFieldName, vm,
                                        row[index], field.m_JSON, field.insertNull);
                                haveNonNullFields = (haveNonNullFields || res);
                            } else {
                                throw new KettleException(BaseMessages.getString(PKG,
                                        "MongoDbOutput.Messages.Error.NoFieldNameSpecifiedForPath")); //$NON-NLS-1$
                            }
                        }
                    }
                }
            } else {
                // record/object
                if (lookup == null && pathParts.size() == 0) {
                    if (field.m_useIncomingFieldNameAsMongoFieldName) {
                        boolean res = setMongoValueFromKettleValue(current, incomingFieldName, vm, row[index],
                                field.m_JSON, field.insertNull);
                        haveNonNullFields = (haveNonNullFields || res);
                    } else {
                        throw new KettleException(BaseMessages.getString(PKG,
                                "MongoDbOutput.Messages.Error.NoFieldNameSpecifiedForPath")); //$NON-NLS-1$
                    }
                } else {
                    if (pathParts.size() == 0) {
                        if (!field.m_useIncomingFieldNameAsMongoFieldName) {
                            boolean res = setMongoValueFromKettleValue(current, lookup.toString(), vm,
                                    row[index], field.m_JSON, field.insertNull);
                            haveNonNullFields = (haveNonNullFields || res);
                        } else {
                            current = (DBObject) current.get(lookup.toString());
                            boolean res = setMongoValueFromKettleValue(current, incomingFieldName, vm,
                                    row[index], field.m_JSON, field.insertNull);
                            haveNonNullFields = (haveNonNullFields || res);
                        }
                    } else {
                        current = (DBObject) current.get(lookup.toString());
                    }
                }
            }

            lookup = getPathElementName(pathParts, current, field.m_useIncomingFieldNameAsMongoFieldName);
        } while (lookup != null);
    }

    if (!haveNonNullFields) {
        return null; // nothing has been set!
    }

    return root;
}

From source file:org.springframework.data.mongodb.core.convert.QueryMapper.java

License:Apache License

/**
 * Converts the given source assuming it's actually an association to another object.
 * /* ww w .  j a va 2  s  . c o  m*/
 * @param source
 * @param property
 * @return
 */
protected Object convertAssociation(Object source, MongoPersistentProperty property) {

    if (property == null || source == null || source instanceof DBObject) {
        return source;
    }

    if (source instanceof DBRef) {

        DBRef ref = (DBRef) source;
        return new DBRef(ref.getCollectionName(), convertId(ref.getId()));
    }

    if (source instanceof Iterable) {
        BasicDBList result = new BasicDBList();
        for (Object element : (Iterable<?>) source) {
            result.add(createDbRefFor(element, property));
        }
        return result;
    }

    if (property.isMap()) {
        BasicDBObject result = new BasicDBObject();
        DBObject dbObject = (DBObject) source;
        for (String key : dbObject.keySet()) {
            result.put(key, createDbRefFor(dbObject.get(key), property));
        }
        return result;
    }

    return createDbRefFor(source, property);
}

From source file:teste.mongo.example.QuickTourAdmin.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server 
    MongoClient mongoClient = new MongoClient();

    /*/*from w ww  . ja  v  a 2s  . c  o  m*/
    // Authenticate - optional
    MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password);
    MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));
    */

    System.out.println("##### DataBaseInitial");
    // get db names
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // get a db
    DB db = mongoClient.getDB("mydb");

    System.out.println("##### With new DataBase MYDB");
    // do an insert so that the db will really be created.  Calling getDB() doesn't really take any
    // action with the server 
    db.getCollection("testcollection").insert(new BasicDBObject("i", 1));
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // drop a database
    mongoClient.dropDatabase("mydb");

    System.out.println("##### DataBase drop MYDB");
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // create a collection
    db = mongoClient.getDB("mydb");
    db.createCollection("testCollection", new BasicDBObject("capped", true).append("size", 1048576));

    System.out.println("##### ListAllCollection MYDB");
    // List all collections
    for (String s : db.getCollectionNames()) {
        System.out.println(s);
    }

    // Dropping a collection
    DBCollection testCollection = db.getCollection("testCollection");
    testCollection.drop();
    System.out.println("##### ListAllCollection MYDB - Drop testCollection");
    System.out.println(db.getCollectionNames());

    /* Indexes */
    // get a collection object to work with
    DBCollection coll = db.getCollection("testCollection");

    // drop all the data in it
    coll.drop();

    // create an index on the "i" field
    coll.createIndex(new BasicDBObject("i", 1));

    // Geospatial query
    coll.createIndex(new BasicDBObject("loc", "2dsphere"));

    BasicDBList coordinates = new BasicDBList();
    coordinates.put(0, -73.97);
    coordinates.put(1, 40.77);
    coll.insert(new BasicDBObject("name", "Central Park")
            .append("loc", new BasicDBObject("type", "Point").append("coordinates", coordinates))
            .append("category", "Parks"));

    coordinates.put(0, -73.88);
    coordinates.put(1, 40.78);
    coll.insert(new BasicDBObject("name", "La Guardia Airport")
            .append("loc", new BasicDBObject("type", "Point").append("coordinates", coordinates))
            .append("category", "Airport"));

    // Find whats within 500m of my location
    BasicDBList myLocation = new BasicDBList();
    myLocation.put(0, -73.965);
    myLocation.put(1, 40.769);
    DBObject myDoc = coll.findOne(new BasicDBObject("loc", new BasicDBObject("$near",
            new BasicDBObject("$geometry", new BasicDBObject("type", "Point").append("coordinates", myLocation))
                    .append("$maxDistance", 500))));
    System.out.println(myDoc.get("name"));

    // create a text index on the "content" field
    coll.createIndex(new BasicDBObject("content", "text"));

    coll.insert(new BasicDBObject("_id", 0).append("content", "textual content"));
    coll.insert(new BasicDBObject("_id", 1).append("content", "additional content"));
    coll.insert(new BasicDBObject("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    BasicDBObject search = new BasicDBObject("$search", "textual content -irrelevant");
    BasicDBObject textSearch = new BasicDBObject("$text", search);
    int matchCount = coll.find(textSearch).count();
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    textSearch = new BasicDBObject("$text", search.append("$language", "english"));
    matchCount = coll.find(textSearch).count();
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    BasicDBObject projection = new BasicDBObject("score", new BasicDBObject("$meta", "textScore"));
    myDoc = coll.findOne(textSearch, projection);
    System.out.println("Highest scoring document: " + myDoc);

    // list the indexes on the collection
    List<DBObject> list = coll.getIndexInfo();
    for (final DBObject o : list) {
        System.out.println(o);
    }

    // clean up
    mongoClient.dropDatabase("mydb");
    mongoClient.close();
}