Example usage for com.mongodb DBCollection findOne

List of usage examples for com.mongodb DBCollection findOne

Introduction

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

Prototype

@Nullable
public DBObject findOne(final Object id) 

Source Link

Document

Get a single document from collection by '_id'.

Usage

From source file:cfel.servlet.ServiceServlet.java

License:Open Source License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from w ww  . j a va  2 s . c o m*/
 * 
 *      Insert a new resource
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String type = request.getParameter("type");
    String id = request.getParameter("id");
    String data = request.getParameter("data");
    System.out.println("doPost: type=" + type + " id=" + id + " data=" + data);

    if ("file".equals(type)) {
        // Save a file with id
        doPut(request, response);
        return;
    }

    DBCollection collection = mDS.getCollection(type);
    if (collection == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown collection %s", type));
        return;
    }

    String action = request.getParameter("action");
    if (action != null) {
        // Manipulate database
        if ("update".equals(action)) {
            String query = request.getParameter("query");
            String update = request.getParameter("update");
            String upsert = request.getParameter("upsert");
            String multi = request.getParameter("multi");
            DBObject queryObj = null;
            if (id != null) {
                queryObj = new BasicDBObject("_id", new ObjectId(id));
            } else if (query != null) {
                queryObj = (DBObject) JSON.parse(query);
            }
            DBObject updateObj = update != null ? (DBObject) JSON.parse(update) : null;
            if (queryObj == null || updateObj == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No query or update parameters");
                return;
            }
            sendJSON(collection.update(queryObj, updateObj, "true".equals(upsert), "true".equals(multi)),
                    response);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown action %s", action));
        }
        return;
    }

    if (data == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No data specified");
        return;
    }

    // Insert a document
    DBObject dataObject = (DBObject) JSON.parse(data);
    Object dataID = dataObject.get("_id");
    if (dataID != null && collection.findOne(dataID) != null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Duplicated id");
        return;
    }
    collection.insert(dataObject);
    sendJSON(dataObject, response);
}

From source file:cfel.servlet.ServiceServlet.java

License:Open Source License

/**
 * @see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse)
 * /* ww w.  jav a  2 s  .  c  o  m*/
 *      Delete a resource
 */
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String type = request.getParameter("type");
    String id = request.getParameter("id");
    System.out.println("doDelete: type=" + type + " id=" + id);

    if (id == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Delete all is not supported");
        return;
    }

    if ("file".equals(type)) {
        // Delete a file
        if (mDS.getFile(id) == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("File %s does not exist", id));
            return;
        }
        mDS.deleteFile(id);
        return;
    }

    DBCollection collection = mDS.getCollection(type);
    if (collection == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown collection %s", type));
        return;
    }

    // Delete a document
    DBObject obj = collection.findOne(new ObjectId(id));
    if (obj == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Document %s does not exist", id));
        return;
    }
    sendJSON(collection.remove(obj), response);
}

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

License:Apache License

/**
 * Return the MongoDB database object corresponding to a surrogate.
 * When <code>mustExist</code> is false the method returns null if the object cannot be found,
 * else an exception is thrown./*from   www  .  j  ava2 s .  c o m*/
 * 
 * @param s a surrogate
 * @param mustExist if true throw an exception when the object cannot be found
 * @return a DBObject object or null
 * @throws T2DBException
 */
public com.mongodb.DBObject getObject(Surrogate s, boolean mustExist) throws T2DBException {
    DBCollection coll = getMongoDB(s).getCollection(s);
    Throwable cause = null;
    com.mongodb.DBObject obj = null;
    try {
        obj = coll.findOne(asQuery(s.getId()));
    } catch (Exception e) {
        cause = e;
    }
    if (cause != null || (obj == null && mustExist))
        throw T2DBMMsg.exception(cause, J.J80020, s.toString());
    return obj;
}

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

License:Apache License

/**
 * Find a property by its name in a database.
 * //  w  ww  .  j a  va 2s. c o  m
 * @param database a database 
 * @param name a string 
 * @return a property or null
 * @throws T2DBException
 */
public <T> Property<T> getProperty(Database database, String name) throws T2DBException {
    try {
        DBCollection coll = getMongoDB(database).getProperties();
        DBObject obj = coll.findOne(mongoObject(MongoDatabase.FLD_PROP_NAME, name));
        if (obj != null)
            return unpack(database, (BasicDBObject) obj);
        else
            return null;
    } catch (Exception e) {
        throw T2DBMsg.exception(e, E.E20104, name);
    }
}

From source file:ch.windmobile.server.mongo.MongoDataSource.java

License:Open Source License

private BasicDBObject findStationJson(String stationId) throws DataSourceException {
    DBCollection stationsCollection = database.getCollection(getStationsCollectionName());
    BasicDBObject stationJson = (BasicDBObject) stationsCollection
            .findOne(BasicDBObjectBuilder.start("_id", stationId).get());
    if (stationJson != null) {
        return stationJson;
    } else {/* w  w w.j  av  a  2  s  .  c  o  m*/
        throw new DataSourceException(DataSourceException.Error.INVALID_DATA,
                "Unable to find station with id '" + stationId + "'");
    }
}

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

License:Open Source License

@Override
public String authenticate(final String email, final Object password) throws AuthenticationServiceException {
    if (password == null) {
        throw new IllegalArgumentException("Password cannot be null");
    }//from  w  ww . ja  v  a2 s. co m
    DBCollection col = db.getCollection(MongoDBConstants.COLLECTION_USERS);
    // Search user by email
    DBObject user = col.findOne(new BasicDBObject(MongoDBConstants.USER_PROP_EMAIL, email));
    if (user != null) {
        String b64 = (String) user.get(MongoDBConstants.USER_PROP_SHA1);
        try {
            boolean ok = AuthenticationServiceUtil.validateSHA1(email, password.toString(), b64);
            if (ok) {
                return (String) user.get(MongoDBConstants.USER_PROP_ROLE);
            } else {
                throw new AuthenticationService.AuthenticationServiceException("Invalid password");
            }
        } catch (NoSuchAlgorithmException e) {
            throw new AuthenticationService.AuthenticationServiceException(
                    "Unexcepted error : " + e.getMessage());
        }
    }
    throw new AuthenticationService.AuthenticationServiceException("User not found");
}

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

License:Open Source License

@Override
public User findByEmail(String email) throws UserNotFound {
    if (email == null) {
        throw new IllegalArgumentException("Email cannot be null");
    }//from   ww w .j  ava  2  s. co 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 + "'");
    }
    return createUser(userDb);
}

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

License:Open Source License

@Override
public User findByPseudo(String pseudo) throws UserNotFound {
    if (pseudo == null) {
        throw new IllegalArgumentException("Pseudo cannot be null");
    }/* w  w w. j a  v  a2  s .c o  m*/
    DBCollection col = db.getCollection(MongoDBConstants.COLLECTION_USERS);
    // Search user by pseudo
    DBObject userDb = col.findOne(new BasicDBObject(MongoDBConstants.USER_PROP_PSEUDO, pseudo));
    if (userDb == null) {
        throw new UserNotFound("Unable to find user with pseudo '" + pseudo + "'");
    }
    return createUser(userDb);
}

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");
    }//from w w  w  . j  ava 2s .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 .  ja  va 2s  .  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;
}