Example usage for com.mongodb BasicDBObject getObjectId

List of usage examples for com.mongodb BasicDBObject getObjectId

Introduction

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

Prototype

public ObjectId getObjectId(final String field) 

Source Link

Document

Returns the object id or null if not set.

Usage

From source file:org.opendaylight.controller.samples.onftappingapp.TappingApp.java

License:Apache License

public void addCaptureDevice(CaptureDev captureDev) throws DuplicateEntryException {

    // Check whether there is an existing capture device with the same name
    if (captureDeviceExistsByName(captureDev.getName()))
        throw new DuplicateEntryException();

    // Get the match criteria table
    DBCollection table = database.getCollection(DatabaseNames.getCaptureDevTableName());

    // Create a document containing the new match criteria
    BasicDBObject document = captureDev.getAsDocument();

    // Add the new tap policy document to the tap policy table
    table.insert(document);//w  w w .j a v  a2s. c  o  m

    // Get the object ID from mongo and update it in the switch entry object
    ObjectId objectId = document.getObjectId("_id");
    captureDev.setObjectId(objectId.toString());

    logger.info("Added Next Hop Switch " + captureDev.getName() + " object ID " + captureDev.getObjectId());
}

From source file:org.opendaylight.controller.samples.onftappingapp.TappingApp.java

License:Apache License

public void addPortChain(PortChain portChain) throws DuplicateEntryException {

    // Check whether there is an existing port chain with the same name
    if (portChainExistsByName(portChain.getName()))
        throw new DuplicateEntryException();

    // Get the match criteria table
    DBCollection table = database.getCollection(DatabaseNames.getPortChainTableName());

    // Create a document containing the new match criteria
    BasicDBObject document = portChain.getAsDocument();

    // Add the new tap policy document to the tap policy table
    table.insert(document);//from   ww  w.  ja va2s  . c o m

    // Get the object ID from mongo and update it in the switch entry object
    ObjectId objectId = document.getObjectId("_id");
    portChain.setObjectId(objectId.toString());

    logger.info("Added Port Chain " + portChain.getName() + " object ID " + portChain.getObjectId());
}

From source file:org.opentaps.notes.repository.impl.NoteRepositoryImpl.java

License:Open Source License

/** {@inheritDoc} */
public void persist(List<Note> notes) {
    if (notes == null) {
        throw new IllegalArgumentException();
    }/*from  ww w.jav a  2s  . c o m*/
    DBCollection coll = getNotesCollection();

    for (Note note : notes) {

        // transform POJO into BSON
        BasicDBObject noteDoc = noteToDbObject(note);

        // for creation set the created date
        if (note.getDateTimeCreated() == null) {
            note.setDateTimeCreated(new Timestamp(System.currentTimeMillis()));
        }
        noteDoc.put(Note.Fields.dateTimeCreated.getName(), note.getDateTimeCreated());

        // and the sequence
        if (note.getSequenceNum() == null) {
            note.setSequenceNum(nextSequenceNum(coll));
        }
        noteDoc.put(Note.Fields.sequenceNum.getName(), note.getSequenceNum());

        coll.insert(noteDoc);
        note.setNoteId(noteDoc.getObjectId(NoteMongo.MONGO_ID_FIELD).toString());
    }
}

From source file:poke.server.storage.jdbc.DatabaseStorage.java

License:Apache License

@Override
public boolean addImageDetails(PhotoHeader photoHeader, PhotoPayload imageRequest, String uuid) {
    boolean inserted = false;
    DBCollection dbColl = db.getCollection("ImageRepository");
    BasicDBObject bdo = new BasicDBObject();
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    bdo.put("createdAt", dateFormat.format(cal.getTime()));
    bdo.put("name", imageRequest.getName());
    bdo.put("data", imageRequest.getData().toStringUtf8());
    bdo.put("modifiedAt", Long.parseLong(dateFormat.format(cal.getTime()).toString().replaceAll("\\W", "")));
    bdo.put("uuid", uuid.toString());
    dbColl.insert(bdo);/* w  ww .j  av a  2s .  c  o m*/
    logger.debug("Inserted: " + bdo.getObjectId("_id"));
    if (bdo.getObjectId("_id") != null)
        inserted = true;
    return inserted;
}

From source file:pt.tiago.mongodbteste.MongoDB.java

private void search() {
    //search all... select * from
    DBCursor cursor = collection.get(1).find();
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();//from  w  w w.  j a va2 s  .c om
        BasicDBObject basicObj = (BasicDBObject) obj;
        Person person = new Person();
        person.setID(String.valueOf(basicObj.getObjectId("_id")));
        person.setName(basicObj.getString("name"));
        person.setSurname(basicObj.getString("surname"));
        System.out.println(person.toString());
    }

    //Select from Person where name = Tiago
    System.out.println("------------------------------------------------------------------------");
    BasicDBObject basicObj = new BasicDBObject("name", "Tiago");
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    //Select from Person where name = Tiago and surname = Carvalho
    System.out.println("------------------------------------------------------------------------");
    basicObj = new BasicDBObject("name", "Tiago").append("surname", "Carvalho");
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    //Select * from Person where name = Tiago and surname = Erro
    System.out.println("------------------------------------------------------------------------");
    basicObj = new BasicDBObject("name", "Tiago").append("surname", "Erro");
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    //SELECT * FROM PERSON WHERE surname like '%arval%'
    System.out.println("------------------------------------------------------------------------");
    basicObj = new BasicDBObject("surname", java.util.regex.Pattern.compile("arval"));
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
    //SELECT * FROM PERSON WHERE surname like '%arval%'
    System.out.println("------------------------------------------------------------------------");
    basicObj = new BasicDBObject();
    basicObj.put("surname", java.util.regex.Pattern.compile("arval"));
    cursor = collection.get(1).find(basicObj);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
}

From source file:pt.tiago.mongodbteste.MongoDB.java

private void testReferences() {
    DBCursor cursor = collection.get(1).find();
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();/*from www . j  a va 2  s  .  co  m*/
        BasicDBObject basicObj = (BasicDBObject) obj;
        Person person = new Person();
        person.setID(String.valueOf(basicObj.getObjectId("_id")));
        person.setName(basicObj.getString("name"));
        person.setSurname(basicObj.getString("surname"));
        DBRef addressRef = new DBRef(db, "Person", basicObj.getObjectId("_id"));
        DBObject address = addressRef.fetch();
        BasicDBObject doc = new BasicDBObject().append("name", person.getName())
                .append("surname", person.getSurname()).append("pai", basicObj.getObjectId("_id"));
        collection.get(1).save(doc);
    }
}

From source file:sentiment.SentimentEngine.java

public void saveScores() {

    for (DBObject bson : items.find()) {
        if (bson != null) {
            //get the tweet
            String tweet = (String) bson.get("tweet_text");
            tweets.add(tweet);//  w  w  w .  j  a va  2 s  .  com
            double score = analyzer.calculateTweetPolarity(tweet);
            // get the time
            BasicDBObject bTweet = (BasicDBObject) bson;
            ObjectId objectId = bTweet.getObjectId("_id");
            long millis = objectId.getTime();
            DateTime date = new DateTime(millis);

            //create the sentimetn score and add
            sentiment.SentimentScore singleScore = new SentimentScore(date, score);
            sM.addScore(singleScore);

        }

    }

}

From source file:sentiment.SentimentEngine.java

public void printDates() {
    DBCollection collection = database.getCollection("tweetcoll");

    List<DBObject> temps = collection.find().toArray();
    for (DBObject temp : temps) {
        BasicDBObject tweet = (BasicDBObject) temp;
        ObjectId objectId = tweet.getObjectId("_id");
        long millis = objectId.getTime();
        DateTime date = new DateTime(millis);

        System.out.println(" created on " + date);
    }/* www .j  a va2 s  . co  m*/
}

From source file:tad.grupo7.ccamistadeslargas.DAO.EventoDAO.java

/**
 * Devuelve un Evento que coincida con un ID.
 *
 * @param id ObjectId del evento./* w  w  w.j a va2  s. c o m*/
 * @return Evento
 */
public static Evento read(ObjectId id) {
    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("_id", id);
    BasicDBObject document = (BasicDBObject) eventos.findOne(whereQuery);
    String nombre = document.getString("nombre");
    String divisa = document.getString("divisa");
    ObjectId idCreador = document.getObjectId("idCreador");
    Evento e = new Evento(id, nombre, divisa, idCreador, ParticipanteDAO.readAllFromEvento(id));
    return e;
}

From source file:tad.grupo7.ccamistadeslargas.DAO.EventoDAO.java

/**
 * Devuelve un listado con todos los eventos del usuario.
 *
 * @param idUsuario ObjectId del usuario.
 * @return List/*  ww  w  . j a v a  2  s.com*/
 */
public static List<Evento> readAll(ObjectId idUsuario) {
    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("idCreador", idUsuario);
    DBCursor cursor = eventos.find(whereQuery);
    List<Evento> eventos = new ArrayList<>();
    while (cursor.hasNext()) {
        BasicDBObject e = (BasicDBObject) cursor.next();
        eventos.add(new Evento(e.getObjectId("_id"), e.getString("nombre"), e.getString("divisa"),
                e.getObjectId("idCreador"), ParticipanteDAO.readAllFromEvento(e.getObjectId("_id"))));
    }
    return eventos;
}