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:com.cloudbees.gasp.model.MongoConnection.java

License:Apache License

public String newLocation(GeoLocation location) {

    DBCollection locations = getCollection();

    // Search by "name" for existing record
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("name", location.getName());

    // Upsert from GaspLocation object
    DBObject updateExpression = new BasicDBObject();
    updateExpression.put("name", location.getName());
    updateExpression.put("formattedAddress", location.getFormattedAddress());

    // Include Location lat/lng data
    BasicDBObject locObj = new BasicDBObject();
    locObj.put("lng", location.getLocation().getLng());
    locObj.put("lat", location.getLocation().getLat());
    updateExpression.put("location", locObj);

    locations.update(searchQuery, updateExpression, true, false);
    String upsertId = locations.findOne(searchQuery).get("_id").toString();

    if (logger.isDebugEnabled())
        logger.debug("addLocation(): " + upsertId);

    // Return the _id field for the upserted record
    return upsertId;
}

From source file:com.comcast.video.dawg.service.house.AbstractDawgService.java

License:Apache License

/**
 * Helper method to get a DBObject with all the fields of an object and then
 * specify the _id of the object/*from   w w w  .  j av  a 2  s  .  co m*/
 * @param obj The object to get a DBObject for
 * @param idField The name of the field on the object that will server as the id
 * @return
 */
public DBObject getDBObject(Object obj, String idField) {
    try {
        DBObject dbObj = new BasicDBObject();
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String fName = field.getName();
            Object fVal = field.get(obj);
            dbObj.put(fName, fVal);
            if (fName.equals(idField)) {
                dbObj.put("_id", fVal);
            }
        }

        return dbObj;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.continuent.tungsten.replicator.applier.MongoApplier.java

License:Open Source License

/**
 * @param doc//  w w w  . j  a  v a 2  s . c o  m
 * @param columnSpec
 * @param value
 * @throws ReplicatorException
 */
private void setValue(DBObject doc, ColumnSpec columnSpec, Object value) throws ReplicatorException {
    String name = columnSpec.getName();

    if (value == null)
        doc.put(name, value);
    else if (value instanceof SerialBlob)
        doc.put(name, deserializeBlob(name, (SerialBlob) value));
    else if (columnSpec.getType() == Types.TIME) {
        if (value instanceof Timestamp) {
            Timestamp timestamp = ((Timestamp) value);
            StringBuffer time = new StringBuffer(new Time(timestamp.getTime()).toString());
            if (timestamp.getNanos() > 0) {
                time.append(".");
                time.append(String.format("%09d", timestamp.getNanos()));
            }
            doc.put(name, time.toString());
        } else {
            Time t = (Time) value;
            doc.put(name, t.toString());
        }
    } else
        doc.put(name, value.toString());
}

From source file:com.continuent.tungsten.replicator.applier.MongoApplier.java

License:Open Source License

/**
 * {@inheritDoc}// w w  w  . jav a2 s . c o m
 * 
 * @see com.continuent.tungsten.replicator.applier.RawApplier#commit()
 */
@Override
public void commit() throws ReplicatorException, InterruptedException {
    // If we don't have a last header, there is nothing to be done.
    if (latestHeader == null) {
        if (logger.isDebugEnabled())
            logger.debug("Unable to commit; last header is null");
        return;
    }

    // Connect to the schema and collection.
    DB db = m.getDB(serviceSchema);
    DBCollection trepCommitSeqno = db.getCollection("trep_commit_seqno");

    // Construct query.
    DBObject query = new BasicDBObject();
    query.put("task_id", taskId);

    // Construct update.
    BasicDBObject doc = new BasicDBObject();
    doc.put("task_id", taskId);
    doc.put("seqno", latestHeader.getSeqno());
    // Short seems to cast to Integer in MongoDB.
    doc.put("fragno", latestHeader.getFragno());
    doc.put("last_frag", latestHeader.getLastFrag());
    doc.put("source_id", latestHeader.getSourceId());
    doc.put("epoch_number", latestHeader.getEpochNumber());
    doc.put("event_id", latestHeader.getEventId());
    doc.put("extract_timestamp", latestHeader.getExtractedTstamp().getTime());

    // Update trep_commit_seqno.
    DBObject updatedDoc = trepCommitSeqno.findAndModify(query, null, null, false, doc, true, true);
    if (logger.isDebugEnabled()) {
        if (updatedDoc == null)
            logger.debug("Unable to update/insert trep_commit_seqno: query=" + query + " doc=" + doc);
        else
            logger.debug("Trep_commit_seqno updated: updatedDoc=" + updatedDoc);
    }
}

From source file:com.continuent.tungsten.replicator.applier.MongoApplier.java

License:Open Source License

/**
 * {@inheritDoc}//from  ww  w .j  a  v a  2s.  c  o  m
 * 
 * @see com.continuent.tungsten.replicator.applier.RawApplier#getLastEvent()
 */
@Override
public ReplDBMSHeader getLastEvent() throws ReplicatorException, InterruptedException {
    // Connect to the schema and collection.
    DB db = m.getDB(serviceSchema);
    DBCollection trepCommitSeqno = db.getCollection("trep_commit_seqno");

    // Construct query.
    DBObject query = new BasicDBObject();
    query.put("task_id", taskId);

    // Find matching trep_commit_seqno value.
    DBObject doc = trepCommitSeqno.findOne(query);

    // Return a constructed header or null, depending on whether we found
    // anything.
    if (doc == null) {
        if (logger.isDebugEnabled())
            logger.debug("trep_commit_seqno is empty: taskId=" + taskId);
        return null;
    } else {
        if (logger.isDebugEnabled())
            logger.debug("trep_commit_seqno entry found: doc=" + doc);

        long seqno = (Long) doc.get("seqno");
        // Cast to integer in MongoDB.
        int fragno = (Integer) doc.get("fragno");
        boolean lastFrag = (Boolean) doc.get("last_frag");
        String sourceId = (String) doc.get("source_id");
        long epochNumber = (Long) doc.get("epoch_number");
        String eventId = (String) doc.get("event_id");
        String shardId = (String) doc.get("shard_id");
        long extractTimestamp = (Long) doc.get("extract_timestamp");
        ReplDBMSHeaderData header = new ReplDBMSHeaderData(seqno, (short) fragno, lastFrag, sourceId,
                epochNumber, eventId, shardId, new Timestamp(extractTimestamp), 0);
        return header;
    }
}

From source file:com.crosstreelabs.cognitio.service.mongo.MongoReferenceService.java

License:Apache License

protected DBObject toMongoObject(final Reference reference) {
    DBObject result = new BasicDBObject();
    result.put("linker", reference.linker);
    result.put("linkee", reference.linkee);
    if (reference.discovered == null) {
        reference.discovered = new DateTime();
    }/*w  ww. ja  v a 2  s  .  co  m*/
    result.put("discovered", reference.discovered.toDate());
    if (reference.defunct != null) {
        result.put("defunct", reference.defunct.toDate());
    }
    return result;
}

From source file:com.data.DAO.MetodoPagoDAO.java

public static String actualizarRecibo(Integer idMetodoPago, String descripcion, Integer cuotas, float precio,
        Integer idReserva) {//  w  w w  .  jav  a2s . c o  m
    String reciboActualizar = null;
    try {
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("hoex");
        System.out.println("Connect to database successfully");

        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("idMetodoPago", idMetodoPago);

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {
            DBObject updateDocument = cursor.next();
            updateDocument.put("descripcion", descripcion);
            updateDocument.put("cuotas", cuotas);
            updateDocument.put("precio", precio);
            updateDocument.put("idReserva", idReserva);
            coll.update(whereQuery, updateDocument);
        }
        System.out.println("Document updated successfully");
        reciboActualizar = "Success";
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (reciboActualizar != null) {
        return "El recibo se ha actualizado correctamente!";
    } else {
        return "El recibo no se ha actualizado!";
    }
}

From source file:com.deafgoat.ml.prognosticator.MongoImport.java

License:Apache License

/**
 * Returns the JSON configuraiton matching the specified configuration name.
 * /*from  w w w .  j  a va2 s  .  co m*/
 * @param configName
 *            The name of the JSON configuration to find.
 * @return The JSON configurations found. Null if none is found.
 * @throws IOException
 *             If it can not read configuration file.
 * @throws FileNotFoundException
 *             If it can not find configuration file.
 * @throws JSONException
 *             If the configuration file(s) can not be converted to a
 *             JSONObject.
 * @throws MongoException
 *             If it is unable to connect to a running mongod.
 */
public JSONObject getConfiguration(String configName)
        throws FileNotFoundException, IOException, MongoException, JSONException {
    DBObject query = new BasicDBObject();
    query.put("name", configName);
    DBObject result = _collection.findOne(query);
    return result == null ? null : new JSONObject(result.toString());
}

From source file:com.deafgoat.ml.prognosticator.MongoResult.java

License:Apache License

/**
 * Reads a stored WEKA classifier model from the database
 * //from w w  w  . ja  v a 2  s. c o  m
 * @param modelName
 *            The name of the model to read from the database
 * @throws IOException
 * @throws ClassNotFoundException
 */
public Classifier readModel(String modelName) throws IOException, ClassNotFoundException {
    DBObject query = new BasicDBObject();
    query.put("name", modelName);
    DBObject dbObj = _collection.findOne(query);
    if (dbObj == null) {
        return null;
    }
    ByteArrayInputStream bis = new ByteArrayInputStream((byte[]) dbObj.get("serializedModelBytes"));
    ObjectInputStream ois = new ObjectInputStream(bis);
    return (Classifier) ois.readObject();
}

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.embed.AbstractEmbedCommand.java

License:Apache License

protected DBObject buildGetQuery(BitSet arrayBits, String embedId, MetaClass rootMetaClass) {
    DBObject queryObject = new BasicDBObject();
    queryObject.put(InternalFieldEnum.BRANCH.getDbName(), branchId);
    queryObject.put(InternalFieldEnum.STATUS.getDbName(), StatusEnum.ACTIVE.toString());

    String embedPath = helper.getEmbedPath(embedId, rootMetaClass);
    if (StringUtils.isNullOrEmpty(embedPath)) {
        // generate field for root
        queryObject.put(InternalFieldEnum.ID.getDbName(), embedId);
        queryObject.put(InternalFieldEnum.STATUS.getDbName(), StatusEnum.ACTIVE.toString());
    } else if (arrayBits.isEmpty()) {
        // generate dot notation field for single 
        String idFieldName = embedPath + AbstractEntityIDHelper.DOT + InternalFieldEnum.ID.getDbName();
        String statusFieldName = embedPath + AbstractEntityIDHelper.DOT + InternalFieldEnum.STATUS.getDbName();
        queryObject.put(idFieldName, embedId);
        queryObject.put(statusFieldName, StatusEnum.ACTIVE.toString());
    } else {/*from www .j  a  v  a 2 s  . c o m*/
        // generate $elemMatch for array 
        DBObject idQueryObject = new BasicDBObject();
        idQueryObject.put(InternalFieldEnum.ID.getDbName(), embedId);
        idQueryObject.put(InternalFieldEnum.STATUS.getDbName(), StatusEnum.ACTIVE.toString());
        BasicDBObject elemMatchObject = new BasicDBObject();
        elemMatchObject.put("$elemMatch", idQueryObject);
        queryObject.put(embedPath, elemMatchObject);
    }
    return queryObject;
}