Example usage for com.mongodb DBObject put

List of usage examples for com.mongodb DBObject put

Introduction

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

Prototype

Object put(String key, Object v);

Source Link

Document

Sets a name/value pair in this object.

Usage

From source file:act.server.MongoDB.java

License:Open Source License

public void updateRxnRefs(Seq seq) {
    BasicDBObject query = new BasicDBObject().append("_id", seq.getUUID());
    DBObject obj = this.dbSeq.findOne(query);
    obj.put("rxn_refs", seq.getReactionsCatalyzed());
    this.dbSeq.update(query, obj);
}

From source file:act.server.MongoDB.java

License:Open Source License

/**
 * graphByOrganism() returns a list of all reactionIDs containing the given organismID.
 *
 * @param organismID//from  w  ww  .  ja  v  a2s  .  c om
 * @return List<Long> List of reaction IDs for given organismID
 */
public List<Long> graphByOrganism(Long organismID) {

    DBObject query = new BasicDBObject();
    if (organismID == null || organismID > -1)
        query.put("organisms.id", organismID);
    List<Long> graphList = new ArrayList<Long>();

    DBCursor reactionCursor = this.dbReactions.find(query);
    for (DBObject i : reactionCursor) {
        graphList.add(((Integer) i.get("_id")).longValue()); // checked: db type IS int
    }
    return graphList;
}

From source file:act.server.MongoDB.java

License:Open Source License

/**
 * getOrganisms() returns a list of all unique species IDs in database
 * mapped to itself, its parents, and descendants
 *
 * @return//  w w  w.  jav a2 s .  co  m
 */
@SuppressWarnings("unchecked")
public Map<Long, Set<Long>> getOrganisms() {
    List<Long> ids = (List<Long>) this.dbReactions.distinct("organisms.id");
    //map species id to all ids associated with it
    Map<Long, Set<Long>> speciesIDs = new HashMap<Long, Set<Long>>();
    for (Long organismID : ids) {
        //check if organism id on species level
        List<Long> idsToAdd = new ArrayList<Long>();
        Long speciesID;
        DBObject orgQuery = new BasicDBObject();
        orgQuery.put("_id", organismID);
        DBObject org = dbOrganisms.findOne(orgQuery);
        String rank = (String) org.get("rank");
        Long parent = (Long) org.get("parent_id"); // checked: db type IS long
        speciesID = null;
        while (organismID != 1) {
            idsToAdd.add(organismID);
            if (rank.equals("species")) {
                speciesID = organismID;
                //break;
            }
            orgQuery.put("_id", parent);
            org = dbOrganisms.findOne(orgQuery);
            organismID = parent;
            rank = (String) org.get("rank");
            parent = (Long) org.get("parent_id"); // checked: db type IS long
        }
        if (speciesID == null)
            continue;
        if (!speciesIDs.containsKey(speciesID)) {
            speciesIDs.put(speciesID, new HashSet<Long>());
        }
        speciesIDs.get(speciesID).addAll(idsToAdd);
    }
    return speciesIDs;
}

From source file:act.shared.helpers.XMLToImportantChemicals.java

License:Open Source License

private void process(XMLStreamReader xml) throws XMLStreamException {
    String tag;//from   w  w w  .j  a  va 2 s. com
    String root = null;
    Stack<DBObject> json = new Stack<DBObject>();
    DBObject js;
    while (xml.hasNext()) {
        int eventType = xml.next();
        while (xml.isWhiteSpace() || eventType == XMLEvent.SPACE)
            eventType = xml.next();

        switch (eventType) {
        case XMLEvent.START_ELEMENT:
            tag = xml.getLocalName();
            if (root == null) {
                root = tag;
            } else {
                json.push(new BasicDBObject());
            }
            break;
        case XMLEvent.END_ELEMENT:
            tag = xml.getLocalName();
            if (tag.equals(root)) {
                // will terminate in next iteration
            } else {
                js = json.pop();
                if (json.size() == 0) {
                    if (tag.equals(rowTag))
                        printEntry(js);
                    else
                        printUnwantedEntry(js);
                } else {
                    putListStrOrJSON(json.peek(), tag, js);
                }
            }
            break;

        case XMLEvent.CHARACTERS:
            String txt = xml.getText();
            js = json.peek();
            if (js.containsField(strTag)) {
                txt = js.get(strTag) + txt;
                js.removeField(strTag);
            }
            js.put(strTag, txt);
            break;

        case XMLEvent.START_DOCUMENT:
            break;
        case XMLEvent.END_DOCUMENT:
            break;
        case XMLEvent.COMMENT:
        case XMLEvent.ENTITY_REFERENCE:
        case XMLEvent.ATTRIBUTE:
        case XMLEvent.PROCESSING_INSTRUCTION:
        case XMLEvent.DTD:
        case XMLEvent.CDATA:
        case XMLEvent.SPACE:
            System.out.format("%s --\n", eventType);
            break;
        }
    }
}

From source file:act.shared.helpers.XMLToImportantChemicals.java

License:Open Source License

private void putElemOrList(DBObject json, String tag, Object add) {
    // if tag already present then make it a list
    if (json.containsField(tag)) {
        BasicDBList l;/*from w ww .j  av  a2s .c o m*/
        Object already = json.get(tag);
        if (already instanceof BasicDBList) {
            l = (BasicDBList) already;
        } else {
            l = new BasicDBList();
            l.add(already);
        }
        l.add(add);
        json.removeField(tag);
        json.put(tag, l);
        return;
    }

    // else, just add as is
    json.put(tag, add);
    return;
}

From source file:act.storage.db.impl.morphia.MorphiaDbHooker.java

License:Apache License

@Override
public void prePersist(Object ent, DBObject dbObj, Mapper mapper) {
    Class c = ent.getClass();//  ww  w .ja  v a  2  s . co  m
    String cn = c.getName();
    List<String> storageFields = ssm.managedFields(c);
    for (String fieldName : storageFields) {
        UpdatePolicy updatePolicy = ssm.updatePolicy(c, fieldName);
        IStorageService ss = ssm.storageService(c, fieldName);
        String keyCacheField = StorageServiceManager.keyCacheField(fieldName);
        boolean isCollection = ssm.isCollection(cn, fieldName);
        if (!isCollection) {
            ISObject sobj = $.getProperty(cacheService, ent, fieldName);
            String newKey = null == sobj ? null : sobj.getKey();
            String prevKey = $.getProperty(cacheService, ent, keyCacheField);
            updatePolicy.handleUpdate(prevKey, newKey, ss);
            if (null != sobj) {
                if (S.blank(newKey) || !ss.isManaged(sobj)) {
                    newKey = ss.getKey();
                }
                if (S.neq(newKey, prevKey)) {
                    try {
                        sobj = ss.put(newKey, sobj);
                        $.setProperty(cacheService, ent, newKey, keyCacheField);
                        $.setProperty(cacheService, ent, sobj, fieldName);
                    } catch (Exception e) {
                        logger.warn(e, "Error persist sobject by key: %s", newKey);
                    }
                }
                dbObj.put(fieldName, sobj.getKey());
            }
        } else {
            // The field is a collection of ISObject.
            // 1. handle obsolete sobject items
            Collection<ISObject> col = $.getProperty(cacheService, ent, fieldName);
            if (null == col) {
                col = C.newList();
            }
            Set<String> newKeys = C.newSet();
            for (ISObject sobj : col) {
                if (null == sobj) {
                    continue;
                }
                newKeys.add(sobj.getKey());
            }
            Set<String> oldKeys = $.getProperty(cacheService, ent, keyCacheField);
            if (null == oldKeys) {
                oldKeys = C.newSet();
            }
            Set<String> oldKeysCopy = C.newSet(oldKeys);
            oldKeysCopy.removeAll(newKeys);
            for (String toBeRemoved : oldKeysCopy) {
                if (S.isBlank(toBeRemoved)) {
                    continue;
                }
                updatePolicy.handleUpdate(toBeRemoved, null, ss);
            }
            // 2. persist all new sobject items
            Class fieldType = fieldType(c, fieldName);
            Collection<ISObject> updatedCol = $.cast(Act.app().getInstance(fieldType));
            newKeys.clear();
            for (ISObject sobj : col) {
                if (null == sobj) {
                    continue;
                }
                String newKey = sobj.getKey();
                if (S.blank(newKey) || !ss.isManaged(sobj)) {
                    newKey = ss.getKey();
                }
                if (!oldKeys.contains(newKey)) {
                    try {
                        sobj = ss.put(newKey, sobj);
                        updatedCol.add(sobj);
                        newKeys.add(sobj.getKey());
                    } catch (Exception e) {
                        logger.warn(e, "Error persist sobject by key: %s", newKey);
                    }
                }
            }
            $.setProperty(cacheService, ent, newKeys, keyCacheField);
            $.setProperty(cacheService, ent, updatedCol, fieldName);
            dbObj.put(fieldName, newKeys);
        }
    }
}

From source file:alto.plugin.webradio.recommender.MongoDBDataModel.java

License:Apache License

/**
 * <p>/*w  w w  .  j av a 2 s.  c  om*/
 * Translates the MongoDB identifier to Mahout/MongoDBDataModel's internal
 * identifier, if required.
 * </p>
 * <p>
 * If MongoDB identifiers are long datatypes, it returns the id.
 * </p>
 * <p>
 * This conversion is needed since Mahout uses the long datatype to feed the
 * recommender, and MongoDB uses 12 bytes to create its identifiers.
 * </p>
 *
 * @param id     MongoDB identifier
 * @param isUser
 * @return String containing the translation of the external MongoDB ID to
 *         internal long ID (mapping).
 * @see #fromLongToId(long)
 * @see <a href="http://www.mongodb.org/display/DOCS/Object%20IDs">
 *      Mongo Object IDs</a>
 */
public String fromIdToLong(String id, boolean isUser) {
    DBObject objectIdLong = collectionMap.findOne(new BasicDBObject("element_id", id));
    if (objectIdLong != null) {
        Map<String, Object> idLong = (Map<String, Object>) objectIdLong.toMap();
        Object value = idLong.get("long_value");
        return value == null ? null : value.toString();
    } else {
        objectIdLong = new BasicDBObject();
        String longValue = Long.toString(idCounter++);
        objectIdLong.put("element_id", id);
        objectIdLong.put("long_value", longValue);
        collectionMap.insert(objectIdLong);
        log.info("Adding Translation {}: {} long_value: {}", isUser ? "User ID" : "Item ID", id, longValue);
        return longValue;
    }
}

From source file:alto.plugin.webradio.recommender.MongoDBDataModel.java

License:Apache License

private void buildModel() throws UnknownHostException {
    userIsObject = false;// w ww . j a va  2s . co m
    itemIsObject = false;
    idCounter = 0;
    preferenceIsString = true;
    Mongo mongoDDBB = new Mongo(mongoHost, mongoPort);
    DB db = mongoDDBB.getDB(mongoDB);
    mongoTimestamp = new Date(0);
    FastByIDMap<Collection<Preference>> userIDPrefMap = new FastByIDMap<Collection<Preference>>();
    if (!mongoAuth || db.authenticate(mongoUsername, mongoPassword.toCharArray())) {
        collection = db.getCollection(mongoCollection);
        collectionMap = db.getCollection(mongoMapCollection);
        DBObject indexObj = new BasicDBObject();
        indexObj.put("element_id", 1);
        collectionMap.ensureIndex(indexObj);
        indexObj = new BasicDBObject();
        indexObj.put("long_value", 1);
        collectionMap.ensureIndex(indexObj);
        collectionMap.remove(new BasicDBObject());
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            Map<String, Object> user = (Map<String, Object>) cursor.next().toMap();
            if (!user.containsKey("deleted_at")) {
                long userID = Long.parseLong(fromIdToLong(getID(user.get(mongoUserID), true), true));
                long itemID = Long.parseLong(fromIdToLong(getID(user.get(mongoItemID), false), false));
                float ratingValue = getPreference(user.get(mongoPreference));
                Collection<Preference> userPrefs = userIDPrefMap.get(userID);
                if (userPrefs == null) {
                    userPrefs = Lists.newArrayListWithCapacity(2);
                    userIDPrefMap.put(userID, userPrefs);
                }
                userPrefs.add(new GenericPreference(userID, itemID, ratingValue));
                if (user.containsKey("created_at")
                        && mongoTimestamp.compareTo(getDate(user.get("created_at"))) < 0) {
                    mongoTimestamp = getDate(user.get("created_at"));
                }
            }
        }
    }
    delegate = new GenericDataModel(GenericDataModel.toDataMap(userIDPrefMap, true));
}

From source file:analizadorTweet.SavePE.java

License:Apache License

public void onEvent(Event event) {

    if (ImprimerEventoLlegada) {
        System.out.println("Pe: " + event.get("SaveId"));
        System.out.println("@" + event.get("User"));
        System.out.println(event.get("Text"));
        System.out.println("Location: " + event.get("Location"));
        System.out.println("Timestamp: " + event.get("Timestamp"));

        System.out.println("earthPos: " + event.get("earthPos"));
        System.out.println("earthNeg: " + event.get("earthNeg"));
        System.out.println("earthSub: " + event.get("earthSub"));
        System.out.println("earthNeu: " + event.get("earthNeu"));

        System.out.println("elhPos: " + event.get("elhPos"));
        System.out.println("elhNeg: " + event.get("elhNeg"));

        System.out.println("subScore: " + event.get("subScore"));
        System.out.println("earthSub: " + event.get("earthSub"));
        System.out.println("label: " + event.get("label"));

        System.out.println("-------------------------------------------");
    }//from   ww w  .jav a  2  s  .  com

    if (ImprimirDelay) {

        java.util.Date date = new java.util.Date();
        Long Tfinal = Calendar.getInstance().getTimeInMillis();
        Long Tinicio = Long.parseLong(event.get("Location"));

        System.out.println("PE: " + event.get("SaveId") + " delay: " + (Tfinal - Tinicio));

    }

    java.util.Date date = new java.util.Date();
    Long Tfinal = Calendar.getInstance().getTimeInMillis();
    Long Tinicio = Long.parseLong(event.get("Location"));

    //Aca hago el Save en mongo       
    DBObject tweet = new BasicDBObject();

    tweet.put("Content", event.get("Text"));
    tweet.put("Delay", Tfinal - Tinicio);

    mongo.setupMongo();
    mongo.insert(tweet);

    seen = true;
}

From source file:ARS.DBManager.java

public void insertPlane(Plane pObj) {
    try {//from www.  j a  v a 2s .com
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        //Connecting

        MongoDatabase db = mongoClient.getDatabase("ars");
        System.out.println("Connecting to the db...");
        MongoCollection collection = db.getCollection("plane"); //Choosing the collection to insert
        System.out.println(collection);

        List<Object> seatDBList = new BasicDBList();

        Document planeObj = new Document();
        planeObj.put("pNo", 2);
        planeObj.put("flightNo", 2);
        planeObj.put("Type", "Airbus A380");
        for (Seat seatList : pObj.getSeatVector()) //TODO: Change it
        {
            DBObject seatDBObject = new BasicDBObject();
            seatDBObject.put("sNo", seatList.getSeatNumber());
            seatDBObject.put("isEmpty", seatList.getIsEmpty());
            seatDBObject.put("isEconomy", seatList.getIsEconomy());
            seatDBList.add(seatDBObject);
        }
        planeObj.put("Seats", seatDBList);
        collection.insertOne(planeObj);

    } catch (Exception e) {
        e.printStackTrace();
    }
}