Example usage for com.mongodb DBCollection save

List of usage examples for com.mongodb DBCollection save

Introduction

In this page you can find the example usage for com.mongodb DBCollection save.

Prototype

public WriteResult save(final DBObject document) 

Source Link

Document

Update an existing document or insert a document depending on the parameter.

Usage

From source file:gMIRC_handler.java

private int UpdateLastActive(String username) {
    int ret = 0;/*w  w w  .  ja va2s.  c o m*/
    try {

        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("activeUser");
        BasicDBObject query = new BasicDBObject("username", username);

        DBCursor cursor = coll.find(query);

        try {
            if (cursor.hasNext()) {
                DBObject temp = cursor.next();
                java.util.Date date = new java.util.Date();
                temp.put("timestamp", date);
                coll.save(temp);
            } else {
                java.util.Date date = new java.util.Date();
                BasicDBObject doc = new BasicDBObject("username", username).append("timestamp", date);
                coll.insert(doc);
                System.out.println(username + " online !");
            }
        } finally {
            cursor.close();
        }

    } catch (UnknownHostException ex) {
        Logger.getLogger(gMIRC_handler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return 0;
}

From source file:Publisher.java

public static void mongoInsertTest3(DB db, List<AlertTest> alerts) {
    DBCollection coll = db.getCollection("testCollection");
    BasicDBObject doc = new BasicDBObject();
    for (int i = 0; i < alerts.size(); i++) {
        doc.append("_id", alerts.get(i).ID + ": " + new Date().getTime()).append("Cause", alerts.get(i).cause)
                .append("Effect", alerts.get(i).effect).append("Text", alerts.get(i).text);
        for (int j = 0; j < alerts.get(i).agencyID.size(); i++)
            doc.append("agencyID" + j, alerts.get(i).agencyID);
        for (int j = 0; j < alerts.get(i).routeID.size(); i++)
            doc.append("routeID" + j, alerts.get(i).routeID);
        for (int j = 0; j < alerts.get(i).stopID.size(); i++)
            doc.append("stopID" + j, alerts.get(i).stopID);
        coll.save(doc);
    }/*from  w  w w.  ja va2  s  .  c o  m*/
}

From source file:Publisher.java

public static void mongoInsertTest2(DB db, List<TripUpdate> tripUpdates) {
    DBCollection coll = db.getCollection("testCollection");
    BasicDBObject doc = new BasicDBObject();
    // Now, copy and update current agency data to mongo.
    for (int i = 0; i < tripUpdates.size(); i++) {
        doc.append("_id", tripUpdates.get(i).tripId + ": " + new Date().getTime());
        coll.save(doc);
        for (int j = 0; j < tripUpdates.get(i).stopUpdates.size(); j++) {
            doc = new BasicDBObject();
            doc.append("_id", tripUpdates.get(i).tripId + "-" + j + ": " + new Date().getTime())
                    .append("arrivalDelay", tripUpdates.get(i).stopUpdates.get(j).arrivalDelay)
                    .append("arrivalTime", tripUpdates.get(i).stopUpdates.get(j).arrivalTime)
                    .append("departureDelay", tripUpdates.get(i).stopUpdates.get(j).departureDelay)
                    .append("departureTime", tripUpdates.get(i).stopUpdates.get(j).departureTime)
                    .append("stopSeq", tripUpdates.get(i).stopUpdates.get(j).stopSeq)
                    .append("trip", tripUpdates.get(i).tripId);
            coll.save(doc);/*w w  w. j  a  v  a2 s  .  c o m*/
        }
    }
}

From source file:Publisher.java

public static void mongoInsertTest(DB db, List<VehiclePositionTest> positions) {
    DBCollection coll = db.getCollection("testCollection");
    BasicDBObject doc = new BasicDBObject();
    // Now, copy and update current agency data to mongo.
    for (int i = 0; i < positions.size(); i++) {
        doc.append("_id", positions.get(i).getVehicleId() + ": " + new Date().getTime())
                .append("stopId", positions.get(i).getStopId()).append("tripId", positions.get(i).getTripId())
                .append("agencyId", positions.get(i).getAgencyId())
                .append("timeOfRecord", positions.get(i).getTimeOfRecord())
                .append("timeOfLocationUpdate", positions.get(i).getTimeOfLocationUpdate())
                .append("speed", positions.get(i).getSpeed())
                .append("currentLocationLat", positions.get(i).getCurrentLocationLat())
                .append("currentLocationLon", positions.get(i).getCurrentLocationLon())
                .append("odometer", positions.get(i).getOdometer())
                .append("currentOrientation", positions.get(i).getCurrentOrientation())
                .append("congestionLevel", positions.get(i).getCongestionLevel())
                .append("status", positions.get(i).getStatus()).append("label", positions.get(i).getLabel())
                .append("licensePlate", positions.get(i).getLicensePlate());
        coll.save(doc);
    }/*from   w ww. ja  v  a  2s.  c  o  m*/
}

From source file:br.bireme.scl.MongoOperations.java

License:Open Source License

public static boolean updateDocument(final DBCollection coll, final DBCollection hcoll, final String docId,
        final String fixedUrl, final String user, final boolean automatic) throws IOException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }/*from ww w .j  a v a2  s .c  om*/
    if (hcoll == null) {
        throw new NullPointerException("hcoll");
    }
    if (docId == null) {
        throw new NullPointerException("docId");
    }
    if (fixedUrl == null) {
        throw new NullPointerException("fixedUrl");
    }
    if (user == null) {
        throw new NullPointerException("user");
    }
    if (fixedUrl.length() >= 900) {
        throw new IOException("fixedUrl is too long >= 900. [" + fixedUrl + "]");
    }

    final BasicDBObject query = new BasicDBObject(ID_FIELD, docId);
    final BasicDBObject doc = (BasicDBObject) coll.findOne(query);

    if (doc == null) {
        throw new IOException("document not found id[" + docId + "]");
    }

    final BasicDBList lsthdoc;
    BasicDBObject hdoc = (BasicDBObject) hcoll.findOne(query);
    if (hdoc == null) {
        hdoc = new BasicDBObject();
        hdoc.append(ID_FIELD, docId);
        hdoc.append(MST_FIELD, (String) doc.get(MST_FIELD));
        hdoc.append(DATE_FIELD, (Date) doc.get(DATE_FIELD));
        lsthdoc = new BasicDBList();
        hdoc.append(ELEM_LST_FIELD, lsthdoc);
    } else {
        lsthdoc = (BasicDBList) hdoc.get(ELEM_LST_FIELD);
    }

    final String brokenUrl = doc.getString(BROKEN_URL_FIELD);
    final String brokenUrl_D = EncDecUrl.decodeUrl(brokenUrl);
    final String fixedUrl_E = EncDecUrl.encodeUrl(fixedUrl, CODEC, false);
    //final String fixedUrl_D = EncDecUrl.decodeUrl(fixedUrl);
    final BasicDBObject hcurdoc = new BasicDBObject();
    hcurdoc.append(BROKEN_URL_FIELD, brokenUrl).append(PRETTY_BROKEN_URL_FIELD, brokenUrl_D)
            .append(FIXED_URL_FIELD, fixedUrl_E).append(MSG_FIELD, (String) doc.get(MSG_FIELD))
            .append(CENTER_FIELD, (BasicDBList) doc.get(CENTER_FIELD)).append(AUTO_FIX_FIELD, automatic)
            .append(EXPORTED_FIELD, false).append(LAST_UPDATE_FIELD, new Date()).append(USER_FIELD, user);

    lsthdoc.add(0, hcurdoc);

    final boolean ret1 = coll.remove(doc, WriteConcern.ACKNOWLEDGED).getLastError().ok();
    final boolean ret2 = hcoll.save(hdoc).getLastError().ok();

    return ret1 && ret2;
}

From source file:br.bireme.scl.MongoOperations.java

License:Open Source License

public static boolean undoUpdateDocument(final DBCollection coll, final DBCollection hcoll, final String docId,
        final boolean updateBrokenColl) throws IOException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }/*ww  w.  j  av a2 s .  c o m*/
    if (hcoll == null) {
        throw new NullPointerException("hcoll");
    }
    if (docId == null) {
        throw new NullPointerException("docId");
    }

    final BasicDBObject query = new BasicDBObject(ID_FIELD, docId);
    final BasicDBObject hdoc = (BasicDBObject) hcoll.findOne(query);

    if (hdoc == null) {
        throw new IOException("document not found id[" + docId + "]");
    }
    final BasicDBList lst = (BasicDBList) hdoc.get(ELEM_LST_FIELD);
    final BasicDBObject hcurdoc = (BasicDBObject) lst.remove(0);
    if (hcurdoc == null) {
        throw new IOException("document last element found. Id[" + docId + "]");
    }
    final BasicDBObject doc = new BasicDBObject();
    doc.put(DATE_FIELD, hdoc.get(DATE_FIELD));
    doc.put(LAST_UPDATE_FIELD, hcurdoc.get(LAST_UPDATE_FIELD));
    doc.put(MST_FIELD, hdoc.get(MST_FIELD));
    doc.put(ID_FIELD, docId);
    doc.put(BROKEN_URL_FIELD, hcurdoc.get(BROKEN_URL_FIELD));
    doc.put(PRETTY_BROKEN_URL_FIELD, hcurdoc.get(PRETTY_BROKEN_URL_FIELD));
    doc.put(MSG_FIELD, hcurdoc.get(MSG_FIELD));
    doc.put(CENTER_FIELD, hcurdoc.get(CENTER_FIELD));

    final boolean ret1 = updateBrokenColl ? coll.save(doc).getLastError().ok() : true;
    final boolean ret2;

    if (lst.isEmpty()) {
        ret2 = hcoll.remove(query, WriteConcern.ACKNOWLEDGED).getLastError().ok();
    } else {
        ret2 = hcoll.save(hdoc, WriteConcern.ACKNOWLEDGED).getLastError().ok();
    }

    return ret1 && ret2;
}

From source file:br.bireme.scl.MongoOperations.java

License:Open Source License

public static boolean undoUpdateDocument2(final DBCollection coll, final DBCollection hcoll,
        final String fromDate) throws IOException, ParseException {
    if (coll == null) {
        throw new NullPointerException("coll");
    }//from   www .j  a  v  a  2 s  .c om
    if (hcoll == null) {
        throw new NullPointerException("hcoll");
    }
    final SimpleDateFormat simple = new SimpleDateFormat("yyyyMMdd");
    final Date date = (fromDate == null) ? new Date(0) : simple.parse(fromDate);
    final String updated = ELEM_LST_FIELD + ".0." + LAST_UPDATE_FIELD;
    final BasicDBObject qdate = new BasicDBObject("$gte", date);
    final BasicDBObject query = new BasicDBObject(updated, qdate);
    final BasicDBObject sort = new BasicDBObject(updated, -1);
    final DBCursor cursor = coll.find(query).sort(sort);

    boolean ret = true;

    while (cursor.hasNext()) {
        final BasicDBObject hdoc = (BasicDBObject) cursor.next();
        final BasicDBList lst = (BasicDBList) hdoc.get(ELEM_LST_FIELD);
        final BasicDBObject hcurdoc = (BasicDBObject) lst.remove(0);
        if (hcurdoc == null) {
            throw new IOException("document last element found.");
        }
        final BasicDBObject doc = new BasicDBObject();
        doc.put(DATE_FIELD, hdoc.get(DATE_FIELD));
        doc.put(LAST_UPDATE_FIELD, hcurdoc.get(LAST_UPDATE_FIELD));
        doc.put(MST_FIELD, hdoc.get(MST_FIELD));
        doc.put(ID_FIELD, hdoc.get(ID_FIELD));
        doc.put(BROKEN_URL_FIELD, hcurdoc.get(BROKEN_URL_FIELD));
        doc.put(PRETTY_BROKEN_URL_FIELD, hcurdoc.get(PRETTY_BROKEN_URL_FIELD));
        doc.put(MSG_FIELD, hcurdoc.get(MSG_FIELD));
        doc.put(CENTER_FIELD, hcurdoc.get(CENTER_FIELD));

        final boolean ret1 = coll.save(doc).getLastError().ok();
        final boolean ret2;

        if (lst.isEmpty()) {
            ret2 = hcoll.remove(query, WriteConcern.ACKNOWLEDGED).getLastError().ok();
        } else {
            ret2 = hcoll.save(hdoc, WriteConcern.ACKNOWLEDGED).getLastError().ok();
        }
        final boolean auxret = (ret1 && ret2);
        if (!auxret) {
            System.err.println("doc[" + hdoc.get(ID_FIELD) + "] write error");
        }
        ret &= auxret;
    }

    return ret;
}

From source file:br.bireme.scl.ResetExportFlag.java

License:Open Source License

private static void reset(final String host, final int port, final String database, final String collection,
        final String sdate) throws UnknownHostException, ParseException {
    assert host != null;
    assert port > 0;
    assert database != null;
    assert collection != null;

    final MongoClient client = new MongoClient(host, port);
    final DB db = client.getDB(database);
    final DBCollection coll = db.getCollection(collection);
    final String prefix = ELEM_LST_FIELD + ".0.";
    final BasicDBObject query;
    final DBCursor cursor;

    if (sdate == null) {
        query = new BasicDBObject(prefix + EXPORTED_FIELD, true);
    } else {/*from   w w  w.  java 2  s .  c om*/
        final SimpleDateFormat simple = new SimpleDateFormat("yyyyMMdd");
        final Date date = simple.parse(sdate);

        final BasicDBList list = new BasicDBList();
        list.add(new BasicDBObject(prefix + EXPORTED_FIELD, true));
        list.add(new BasicDBObject(prefix + LAST_UPDATE_FIELD, new BasicDBObject("$gte", date)));
        query = new BasicDBObject("$and", list);
    }
    cursor = coll.find(query);

    while (cursor.hasNext()) {
        final BasicDBObject doc = (BasicDBObject) cursor.next();
        final BasicDBList list = (BasicDBList) doc.get(ELEM_LST_FIELD);
        final BasicDBObject elem = (BasicDBObject) list.get(0);
        elem.put(EXPORTED_FIELD, false);
        coll.save(doc);
    }
    cursor.close();
}

From source file:ch.windmobile.server.social.mongodb.UserServiceImpl.java

License:Open Source License

@Override
public List<Favorite> getFavorites(String email) throws UserNotFound {
    if (email == null) {
        throw new IllegalArgumentException("Email cannot be null");
    }// w w w .  j a  v  a2s . c  o  m
    DBCollection col = db.getCollection(MongoDBConstants.COLLECTION_USERS);
    // Search user by email
    DBObject userDb = col.findOne(new BasicDBObject(MongoDBConstants.USER_PROP_EMAIL, email));
    if (userDb == null) {
        throw new UserNotFound("Unable to find user with email '" + email + "'");
    }

    DBObject favoritesDb = (DBObject) userDb.get(MongoDBConstants.USER_PROP_FAVORITES);
    if (favoritesDb == null) {
        favoritesDb = new BasicDBObject();

        userDb.put(MongoDBConstants.USER_PROP_FAVORITES, favoritesDb);
        col.save(userDb);
    }

    List<Favorite> returnValue = new ArrayList<Favorite>(favoritesDb.keySet().size());
    for (String stationId : favoritesDb.keySet()) {
        Favorite favorite = new Favorite();
        favorite.setStationId(stationId);
        DBObject favoriteItemsDb = (DBObject) favoritesDb.get(stationId);
        favorite.setLastMessageId(
                (Long) favoriteItemsDb.get(MongoDBConstants.USER_PROP_FAVORITE_LASTMESSAGEID));
        returnValue.add(favorite);
    }
    return returnValue;
}

From source file:ch.windmobile.server.social.mongodb.UserServiceImpl.java

License:Open Source License

@Override
public List<Favorite> addToFavorites(String email, List<Favorite> localFavorites) throws UserNotFound {
    if (email == null) {
        throw new IllegalArgumentException("Email cannot be null");
    }//from w  w w. j  a v a2s .c o m
    DBCollection col = db.getCollection(MongoDBConstants.COLLECTION_USERS);
    // Search user by email
    DBObject userDb = col.findOne(new BasicDBObject(MongoDBConstants.USER_PROP_EMAIL, email));
    if (userDb == null) {
        throw new UserNotFound("Unable to find user with email '" + email + "'");
    }

    DBObject favoritesDb = (DBObject) userDb.get(MongoDBConstants.USER_PROP_FAVORITES);
    if (favoritesDb == null) {
        favoritesDb = new BasicDBObject();
    }

    if (localFavorites != null) {
        for (Favorite localFavorite : localFavorites) {
            DBObject favoriteItemsDb = (DBObject) favoritesDb.get(localFavorite.getStationId());
            long lastMessageIdDb = -1;
            if (favoriteItemsDb == null) {
                favoriteItemsDb = new BasicDBObject();
            } else {
                if (favoriteItemsDb.containsField(MongoDBConstants.USER_PROP_FAVORITE_LASTMESSAGEID)) {
                    lastMessageIdDb = (Long) favoriteItemsDb
                            .get(MongoDBConstants.USER_PROP_FAVORITE_LASTMESSAGEID);
                }
            }

            favoriteItemsDb.put(MongoDBConstants.USER_PROP_FAVORITE_LASTMESSAGEID,
                    Math.max(lastMessageIdDb, localFavorite.getLastMessageId()));
            favoritesDb.put(localFavorite.getStationId(), favoriteItemsDb);
        }
    }
    userDb.put(MongoDBConstants.USER_PROP_FAVORITES, favoritesDb);
    col.save(userDb);

    List<Favorite> returnValue = new ArrayList<Favorite>(favoritesDb.keySet().size());
    for (String stationId : favoritesDb.keySet()) {
        Favorite favorite = new Favorite();
        favorite.setStationId(stationId);
        DBObject favoriteItemDb = (DBObject) favoritesDb.get(stationId);
        favorite.setLastMessageId((Long) favoriteItemDb.get(MongoDBConstants.USER_PROP_FAVORITE_LASTMESSAGEID));
        returnValue.add(favorite);
    }
    return returnValue;
}