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:com.tilab.fiware.metaware.dao.impls.mongodb.DepartmentDao.java

License:Open Source License

/**
 * Create a new department./* w  ww  .j  a va  2 s .  com*/
 *
 * @param department the new department to be saved
 * @return the Id of the new department.
 */
public String createDepartment(Department department) {
    log.debug(MSG_DAO_CREATE);

    if (department == null) {
        log.error(MSG_ERR_NOT_VALID_OBJ);
        throw new BadRequestException(MSG_ERR_NOT_VALID_OBJ);
    }

    BasicDBObject query = new BasicDBObject();

    if (department.getCompany() instanceof String) {
        String company_id = department.getCompany().toString();

        if (!ObjectId.isValid(company_id)) {
            log.error(MSG_ERR_NOT_VALID_COMPANY_ID);
            throw new BadRequestException(MSG_ERR_NOT_VALID_COMPANY_ID);
        }

        log.debug("Inserted company Id: " + company_id);

        query.put("_id", new ObjectId(company_id));
    } else if (department.getCompany() instanceof ObjectId) {
        ObjectId company_id = department.getCompanyId();

        log.debug("Inserted company Id: " + company_id.toString());

        query.put("_id", company_id);
    } else {
        log.error(MSG_ERR_NOT_VALID_COMPANY_ID);
        throw new BadRequestException(MSG_ERR_NOT_VALID_COMPANY_ID);
    }

    DBCollection companyCollection = INSTANCE.getDatasource().getDbCollection(COMPANIES_COLLECTION_NAME);
    companyCollection.setObjectClass(Company.class);

    // Check if the company exists
    Company resCompany = (Company) companyCollection.findOne(query);

    if (resCompany == null) { // selected company doesn't exist
        log.error(MSG_ERR_NOT_VALID_COMPANY_ID);
        throw new BadRequestException(MSG_ERR_NOT_VALID_COMPANY_ID);
    } else {
        String debugMsg;
        try {
            debugMsg = INSTANCE.getObjectMapper().writeValueAsString(resCompany);
            log.debug("Related company: " + debugMsg); // print res in json format
        } catch (JsonProcessingException e) {
            log.error(e, e);
        }
    }

    department.setCompanyId(new ObjectId(resCompany.getId()));

    departmentsCollection = INSTANCE.getDatasource().getDbCollection(DEPARTMENTS_COLLECTION_NAME);
    departmentsCollection.setObjectClass(Department.class);
    try {
        departmentsCollection.insert(department);
    } catch (DuplicateKeyException e) {
        log.error(MSG_ERR_DUPLICATE_KEY, e);
        throw new BadRequestException(MSG_ERR_DUPLICATE_KEY);
    }

    String jsonMsg;

    try {
        jsonMsg = INSTANCE.getObjectMapper().writeValueAsString(department);
        log.debug("New department: " + jsonMsg);
    } catch (JsonProcessingException e) {
        log.error(e, e);
    }

    return department.getId();
}

From source file:com.tilab.fiware.metaware.dao.impls.mongodb.DepartmentDao.java

License:Open Source License

/**
 * Update the selected department if exists, otherwise create a new one.
 *
 * @param id         the Id of the selected department to be updated.
 * @param department the department object with the modifications (or the department to be
 *                   saved)./*from   ww w .  ja  v  a2s.c o  m*/
 * @return the updated department object.
 */
public Department upsertDepartment(String id, Department department) {
    log.debug(MSG_DAO_UPSERT + id + ".");

    // Intercept the possibility to change the Id
    if (department.containsField("_id")) {
        department.removeField("_id");
    }

    // Check if a department object is sent
    if (department == null) {
        log.error(MSG_ERR_NOT_VALID_OBJ);
        throw new BadRequestException(MSG_ERR_NOT_VALID_OBJ);
    }

    // Setup MongoDB objects
    DBCollection companyCollection = INSTANCE.getDatasource().getDbCollection(COMPANIES_COLLECTION_NAME);
    companyCollection.setObjectClass(Company.class);
    BasicDBObject query = new BasicDBObject();

    // Check if the inserted company Id is valid
    if (department.getCompany() instanceof ObjectId) { // type is already ObjectId
        ObjectId company_id = department.getCompanyId();

        log.debug("Inserted company Id: " + company_id.toString());

        query.put("_id", company_id); // setup query object
    } else if (department.getCompany() instanceof String) { // type is String
        String company_id = department.getCompany().toString();

        // Check if no Id is specified (empty string)
        if (company_id != null && company_id.isEmpty()) {
            log.error(MSG_ERR_NOT_VALID_COMPANY_ID);
            throw new BadRequestException(MSG_ERR_NOT_VALID_COMPANY_ID);
        } else {
            if (!ObjectId.isValid(company_id)) { // check if Id string is valid
                log.error(MSG_ERR_NOT_VALID_COMPANY_ID);
                throw new BadRequestException(MSG_ERR_NOT_VALID_COMPANY_ID);
            }

            log.debug("Inserted company Id: " + company_id);

            query.put("_id", new ObjectId(company_id)); // setup query object
        }
    } else {
        log.error(MSG_ERR_NOT_VALID_COMPANY_ID);
        throw new BadRequestException(MSG_ERR_NOT_VALID_COMPANY_ID);
    }

    Company resCompany = (Company) companyCollection.findOne(query);

    if (resCompany == null) { // selected company doesn't exist
        log.error(MSG_ERR_NOT_VALID_COMPANY_ID);
        throw new BadRequestException(MSG_ERR_NOT_VALID_COMPANY_ID);
    } else {
        String debugMsg;
        try {
            debugMsg = INSTANCE.getObjectMapper().writeValueAsString(resCompany);
            log.debug("Related company: " + debugMsg); // print res in json format
        } catch (JsonProcessingException e) {
            log.error(e, e);
        }
    }

    // Associate companyId to department
    department.setCompanyId(new ObjectId(resCompany.getId()));

    departmentsCollection = INSTANCE.getDatasource().getDbCollection(DEPARTMENTS_COLLECTION_NAME);
    departmentsCollection.setObjectClass(Department.class);

    query.put("_id", new ObjectId(id)); // associate the Id
    WriteResult wRes = departmentsCollection.update(query, department, true, false); // upsert

    String numUpdates;
    String jsonMsg;

    try {
        numUpdates = String.valueOf(wRes.getN());
        jsonMsg = INSTANCE.getObjectMapper().writeValueAsString(department);
        log.debug(numUpdates + " department updated: " + jsonMsg);
    } catch (JsonProcessingException e) {
        log.error(e, e);
    }

    return department;
}

From source file:com.tilab.fiware.metaware.dao.impls.mongodb.DiscoverObjDao.java

License:Open Source License

/**
 * Discover the objects that can be used.
 *
 * The algorithm is the following: first check that requestorId is either a user, a department,
 * or a company, then build the query by following this assumptions: 1) if requestedId is user,
 * then extract from the user the department and the company; so build a query that includes
 * also objects usable by this department and this company. 2) if requestedId is department,
 * then extract from the department the company and so build a query that includes also object
 * usable by this company. 3) if requestedId is a company, than maintain the basic query with
 * this company./*from  w w  w. j  a va  2s  .  c  o m*/
 *
 * The query is built in this way: find the objects in which the field "permissions" contains an
 * object that has the field "referenceId" that is equal at least to one element from the array
 * of Ids.
 *
 * @param requestedId the Id of the user, department, or company that can use the objects.
 * @return the result of the query.
 */
public List discoverUsable(String requestedId) {
    log.debug(MSG_DAO_DISCV_USABLE + requestedId);

    if (!ObjectId.isValid(requestedId)) {
        log.error(MSG_ERR_NOT_VALID_ID);
        throw new BadRequestException(MSG_ERR_NOT_VALID_ID);
    }

    User reqUser;
    DBCollection usersCollection;
    Department reqDepartment;
    DBCollection departmentsCollection;
    Company reqCompany;
    DBCollection companiesCollection;

    // Query for user, department, or company entities
    BasicDBObject query;

    // Query for objects (algorithms, datasets), containts field "status" specification ("public")
    List<BasicDBObject> queryObjects = new ArrayList<>();
    queryObjects.add(new BasicDBObject("status", "public")); // include public objects

    query = new BasicDBObject();
    query.put("_id", new ObjectId(requestedId));

    usersCollection = INSTANCE.getDatasource().getDbCollection(USERS_COLLECTION_NAME);
    usersCollection.setObjectClass(User.class);
    reqUser = (User) usersCollection.findOne(query);
    if (reqUser != null) {
        // requestedId represents a User
        log.debug(MSG_DBG_IS_USER);
        List<ObjectId> iDs = new ArrayList<>();
        iDs.add(new ObjectId(reqUser.getId())); // search for user
        iDs.add(reqUser.getDepartmentId()); // search for user's department
        iDs.add(reqUser.getCompanyId()); // search for user's company
        // Build the query
        BasicDBObject innerQuery = new BasicDBObject("permissions", new BasicDBObject("$elemMatch",
                new BasicDBObject("referenceId", new BasicDBObject("$in", iDs))));
        // ...meaning: find in feald "permissions" if there is an object that has the field
        // "referenceId" that contains at least one element from the array "iDs"
        queryObjects.add(innerQuery); // include the inner query in objects query
    } else {
        departmentsCollection = INSTANCE.getDatasource().getDbCollection(DEPARTMENTS_COLLECTION_NAME);
        departmentsCollection.setObjectClass(Department.class);
        reqDepartment = (Department) departmentsCollection.findOne(query);
        if (reqDepartment != null) {
            // requestedId represents a Department
            log.debug(MSG_DBG_IS_DEPARTMENT);
            List<ObjectId> iDs = new ArrayList();
            iDs.add(new ObjectId(reqDepartment.getId())); // search for department
            iDs.add(reqDepartment.getCompanyId()); // search for department's company
            // Build the query
            BasicDBObject innerQuery = new BasicDBObject("permissions", new BasicDBObject("$elemMatch",
                    new BasicDBObject("referenceId", new BasicDBObject("$in", iDs))));
            queryObjects.add(innerQuery); // include the inner query in objects query
        } else {
            companiesCollection = INSTANCE.getDatasource().getDbCollection(COMPANIES_COLLECTION_NAME);
            companiesCollection.setObjectClass(Company.class);
            reqCompany = (Company) companiesCollection.findOne(query);
            if (reqCompany != null) {
                // requestedId represents a Company
                log.debug(MSG_DBG_IS_COMPANY);
                // Build the query
                BasicDBObject innerQuery = new BasicDBObject("permissions", new BasicDBObject("$elemMatch",
                        new BasicDBObject("referenceId", new ObjectId(requestedId)))); // search for company
                queryObjects.add(innerQuery); // include the inner query in objects query
            } else {
                // unrecognized Id
                log.error(MSG_ERR_NOT_VALID_ID);
                //throw new BadRequestException(MSG_ERR_NOT_VALID_ID);
                // unrecognized Id - return only public objects
            }
        }
    }

    log.debug("Final query: " + queryObjects.toString());

    return makeQuery(queryObjects);
}

From source file:com.tilab.fiware.metaware.dao.impls.mongodb.ProcessDao.java

License:Open Source License

/**
 * Checks if the selected owner exists in users, departments, or companies collection; if so,
 * returns the related ObjectId.// w w w.j  av a 2 s. co  m
 *
 * @param process               the selected process.
 * @param usersCollection       the collection of registered users.
 * @param departmentsCollection the collection of registered departments.
 * @param companiesCollection   the collection of registered companies.
 * @return the Id of the owner of the process if exists, null otherwise.
 */
private ObjectId checkOwner(Process process, DBCollection usersCollection, DBCollection departmentsCollection,
        DBCollection companiesCollection) {
    BasicDBObject query = new BasicDBObject();

    if (process.getOwner() instanceof ObjectId) { // already stored as ObjectId
        ObjectId ownerId = process.getOwnerId();

        log.debug("Inserted owner Id: " + ownerId.toHexString());

        query.put("_id", ownerId);
    } else if (process.getOwner() instanceof String) { // stored as a String
        String ownerId = process.getOwner().toString();

        if (!ObjectId.isValid(ownerId)) {
            log.error(MSG_ERR_NOT_VALID_OWNER_ID);
            throw new BadRequestException(MSG_ERR_NOT_VALID_OWNER_ID);
        }

        log.debug("Inserted owner Id: " + ownerId);

        query.put("_id", new ObjectId(ownerId));
    } else { // unknown type
        log.error(MSG_ERR_NOT_VALID_OWNER_ID);
        return null;
    }

    ObjectId res;

    // Check if the owner exists in users
    User ownerUser = (User) usersCollection.findOne(query);
    if (ownerUser == null) { // owner is not a user
        // Check if the owner exists in department
        Department ownerDepartment = (Department) departmentsCollection.findOne(query);
        if (ownerDepartment == null) { // owner is not a department
            // Check if the owner exists in company
            Company ownerCompany = (Company) companiesCollection.findOne(query);
            if (ownerCompany == null) { // owner is not a company
                res = null;
            } else { // the owner is a company
                res = new ObjectId(ownerCompany.getId());
            }
        } else { // the owner is a department
            res = new ObjectId(ownerDepartment.getId());
        }
    } else { // the owner is a user
        res = new ObjectId(ownerUser.getId());
    }

    // Send back the Id of the owner (can be null)
    return res;
}

From source file:com.tilab.fiware.metaware.dao.impls.mongodb.UserDao.java

License:Open Source License

/**
 * Use the passed query to retrieve the selected Company from the companies collection.
 *
 * @param query the BasicDBObject containing the query to be executed.
 * @return the selected Company, null if not found.
 *//*  w w w . j  ava  2s  .  c o  m*/
private Company retrieveCompany(BasicDBObject query) {
    // Setup MongoDB objects
    DBCollection companyCollection = INSTANCE.getDatasource().getDbCollection(COMPANIES_COLLECTION_NAME);
    companyCollection.setObjectClass(Company.class);

    // Execute the query
    Company resCompany = (Company) companyCollection.findOne(query);

    if (resCompany == null) { // selected company doesn't exist
        log.error(MSG_ERR_NOT_VALID_COMPANY_ID);
        throw new BadRequestException(MSG_ERR_NOT_VALID_COMPANY_ID);
    } else {
        String debugMsg;

        try {
            debugMsg = INSTANCE.getObjectMapper().writeValueAsString(resCompany);
            log.debug("Related company: " + debugMsg); // print res in json format
        } catch (JsonProcessingException e) {
            log.error(e, e);
        }
    }

    return resCompany;
}

From source file:com.tilab.fiware.metaware.dao.impls.mongodb.UserDao.java

License:Open Source License

/**
 * Use the passed query to retrieve the selected Department from the departments collection.
 *
 * @param query the BasicDBObject containing the query to be executed.
 * @return the selected Department, null if not found.
 *//*w ww  . j ava2 s.  c  o m*/
private Department retrieveDepartment(BasicDBObject query) {
    // Initialize MongoDB objects
    DBCollection departmentsCollection = INSTANCE.getDatasource().getDbCollection(DEPARTMENTS_COLLECTION_NAME);
    departmentsCollection.setObjectClass(Department.class);

    // Execute the query
    Department resDepartment = (Department) departmentsCollection.findOne(query);

    if (resDepartment == null) { // selected department doesn't exist
        log.error(MSG_ERR_NOT_VALID_DEPARTMENT_ID);
        throw new BadRequestException(MSG_ERR_NOT_VALID_DEPARTMENT_ID);
    } else {
        String debugMsg;

        try {
            debugMsg = INSTANCE.getObjectMapper().writeValueAsString(resDepartment);
            log.debug("Related department: " + debugMsg); // print res in json format
        } catch (JsonProcessingException e) {
            log.error(e, e);
        }
    }

    return resDepartment;
}

From source file:com.timboudreau.trackerapi.support.UserFromUrl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public TTUser get() {
    HttpEvent evt = event.get();/*from  w w w  .jav a2  s .co m*/
    DBCollection users = usersCollection.get();
    String userName = evt.getPath().getElement(position).toString();
    DBObject u = users.findOne(new BasicDBObject("name", userName));
    if (u == null) {
        return null;
    }
    List<ObjectId> authorizes = (List<ObjectId>) u.get(Properties.authorizes);
    Number ver = (Number) u.get(Properties.version);
    int version = ver == null ? 0 : ver.intValue();
    return new TTUser(userName, (ObjectId) u.get("_id"), version, authorizes);
}

From source file:com.tomtom.speedtools.mongodb.DaoUtils.java

License:Apache License

/**
 * Finds a single entity that satisfies a specified query filter.
 *
 * @param collection Collection to get the entity from.
 * @param mapper     Mapper to be used to reconstitute the object stored in the collection.
 * @param query      The query to select the entity.
 * @param <T>        The type of the reconstituted object.
 * @return The object in the collection for the given query.
 * @throws EntityNotFoundException Thrown if no object if found with the given id. This will NOT log an error.
 * @throws InternalDaoException    Thrown when an unknown error has occurred. The error will have been logged.
 *///w w  w  .  ja  v  a 2 s  .c om
@Nonnull
public static <T> T findOne(@Nonnull final DBCollection collection, @Nonnull final EntityMapper<T> mapper,
        @Nonnull final MongoDBQuery query) throws EntityNotFoundException, InternalDaoException {
    assert collection != null;
    assert mapper != null;
    assert query != null;

    DBObject dbObject = null;
    try {
        dbObject = collection.findOne(query.toDBObject());
        if (dbObject != null) {
            final T entity = mapper.fromDb(dbObject);
            // Cannot be null because dbObject was not null.
            assert entity != null;
            return entity;
        } else {
            final String message = "Entity not found: " + query + ", collection=" + collection.getName() + '.';
            LOG.debug("findOne: {}", message);
            throw new EntityNotFoundException(message);
        }
    } catch (final MapperException | MongoException e) {
        final String message = "Entity could not be mapped: " + query + ", collection=" + collection.getName()
                + ", object=" + Json.toStringJson(dbObject) + '.';
        LOG.error("findOne: " + message, e);
        throw new InternalDaoException(message, e);
    }
}

From source file:com.tomtom.speedtools.mongodb.migratedb.MongoDBMigrator.java

License:Apache License

/**
 * Migrate the database to the requested toVersion.
 *
 * @param db     Database to migrate./*from  w  ww. j a v a 2s  . c  o  m*/
 * @param dryRun In dry-run mode, no modifications will be made to the database.
 * @return True if the database was modified (other than updating the schema version).
 * @throws MigrationException If an error was encountered during migration.
 */
public boolean migrate(@Nonnull final MongoDB db, final boolean dryRun) throws MigrationException {
    assert db != null;
    LOG.info("MigrateDB starting..." + (dryRun ? " (dryRun mode)" : ""));

    final Map<String, MongoDBMigration> migrationMap = new HashMap<>();
    for (final MongoDBMigration migration : migrations) {
        if (migrationMap.put(migration.getFromVersion(), migration) != null) {
            throw new MigrationException(
                    "Multiple migrations found with 'from'-version: " + migration.getFromVersion());
        }
    }

    // Read the current version from the database.
    final DBCollection collection = db.getCollection(MIGRATOR_COLLECTION_NAME);
    DBObject info = collection.findOne(new BasicDBObject("_id", INFO_ID));
    if (info == null) {
        info = new BasicDBObject("_id", INFO_ID);
    }
    Object currentVersionObj = info.get(CURRENT_VERSION);
    if (currentVersionObj == null) {
        currentVersionObj = getFirstVersion();
        info.put(CURRENT_VERSION, currentVersionObj);
    }
    final String currentVersion = currentVersionObj.toString().trim();

    // Check whether a previous migration was in progress.
    if (info.get(BUSY) != null) {
        throw new MigrationException("Previous migration was unsuccesful. Please restore database.");
    }

    // Indicate that migration is in progress.
    info.put(BUSY, "true");
    if (!dryRun) {
        info.put(CURRENT_VERSION, getTargetVersion());
        collection.save(info);
    }

    // Create migration path to toVersion.
    final List<MongoDBMigration> migrationPath = new ArrayList<>();
    String version = currentVersion;

    // Create a migration path.
    while (!version.equals(getTargetVersion())) {
        final MongoDBMigration migration = migrationMap.get(version);
        if (migration == null) {
            throw new MigrationException(
                    "No migration possible from version: " + version + " to version " + getTargetVersion());
        }
        migrationPath.add(migration);
        version = migration.getToVersion();
    }

    // Start migrating.
    boolean databaseChanged = false;
    List<MongoDBMigrationProblem> problems = Collections.emptyList();
    for (final MongoDBMigration migration : migrationPath) {
        LOG.info("Migrating database from version " + migration.getFromVersion() + " to version "
                + migration.getToVersion());
        try {
            migration.setDryRun(dryRun); // Do not change order:
            databaseChanged = migration.migrateChangedDatabase(db) || databaseChanged; // Always execute migrate!
            problems = migration.flush();
            if (!problems.isEmpty()) {
                break;
            }
        } catch (final MigrationException e) {
            LOG.error("Migration failed, please restore database from backup: " + e.getMessage());
            throw e;
        } catch (final RuntimeException e) {
            LOG.error("Migration failed, please restore database from backup: " + e.getMessage());
            if (e.getCause() instanceof MigrationException) {
                throw (MigrationException) e.getCause();
            }
            throw new MigrationException(e);
        }
    }

    // Close migration.
    info.put(CURRENT_VERSION, getTargetVersion());
    info.removeField(BUSY);
    if (!dryRun) {
        collection.save(info);
    }

    // Show problems.
    if (!problems.isEmpty()) {
        final StringBuilder problemString = new StringBuilder();
        problemString.append("Migration problems encountered:");
        for (final MongoDBMigrationProblem problem : problems) {
            problemString.append("\n  ").append(problem.getPath()).append(" - ").append(problem.getProblem());
        }
        final String str = problemString.toString();
        LOG.error(str);
    } else {
        LOG.info("Migration OK");
    }

    // Dry-run info.
    if (dryRun) {
        LOG.info("Migration was run in dry-run mode. No modifications were made to the database.");
        return false;
    }

    // Real mode.
    if (databaseChanged) {
        LOG.info("Database records have been modified (and schema version was updated).");
    } else {
        LOG.info("No database records have been modified (but schema version was updated).");
    }

    // Now, throw an exception is something was wrong.
    if (!problems.isEmpty()) {
        throw new MigrationException("Migration was not successful. Please restore database.");
    }
    return databaseChanged;
}

From source file:com.tomtom.speedtools.mongodb.migratedb.MongoDBMigrator.java

License:Apache License

public boolean checkCurrentVersion(@Nonnull final MongoDB db) {
    assert db != null;
    final DBCollection collection = db.getCollection(MIGRATOR_COLLECTION_NAME);
    DBObject info = collection.findOne(new BasicDBObject("_id", INFO_ID));
    if (info == null) {
        info = new BasicDBObject("_id", INFO_ID);
    }//from ww  w.  ja  va  2  s.  co  m
    Object currentVersionObj = info.get(CURRENT_VERSION);
    if (currentVersionObj == null) {
        currentVersionObj = getFirstVersion();
        info.put(CURRENT_VERSION, getFirstVersion());
    }
    final String currentVersion = currentVersionObj.toString().trim();
    LOG.debug("checkCurrentVersion: Database version: {}, expecting: {} {}", currentVersion, getTargetVersion(),
            ((currentVersion.equals(getTargetVersion())) ? "(OK)" : "(ERROR)"));
    if (!currentVersion.equals(getTargetVersion())) {
        LOG.error("checkCurrentVersion: Database has wrong version"
                + (currentVersion.equals(getFirstVersion()) ? " (or may be empty)" : "") + ": {}, expected: {}",
                currentVersion, getTargetVersion());
        return false;
    }
    return true;
}