Example usage for com.mongodb DBCollection setObjectClass

List of usage examples for com.mongodb DBCollection setObjectClass

Introduction

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

Prototype

public void setObjectClass(final Class<? extends DBObject> aClass) 

Source Link

Document

Sets a default class for objects in this collection; null resets the class to nothing.

Usage

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

License:Open Source License

/**
 * Updates the selected process' metadata object if exists, otherwise creates a new one.
 *
 * @param id      the Id of the selected process' metadata object to be updated.
 * @param process the process' metadata object with the modifications.
 * @return the updated process' metadata.
 *//*from ww w .  jav a  2  s .c  o m*/
public Process upsertProcess(String id, Process process) {
    log.debug(MSG_DAO_UPSERT + id);

    // Initial checks
    if (!ObjectId.isValid(id)) { // check id string
        log.error(MSG_ERR_NOT_VALID_ID);
        throw new BadRequestException(MSG_ERR_NOT_VALID_ID);
    }
    if (process == null) { // check if process param exists
        log.error(MSG_ERR_NOT_VALID_OBJ);
        throw new BadRequestException(MSG_ERR_NOT_VALID_OBJ);
    }
    if (process.containsField("_id")) { // intercept the possibility to change the Id
        process.removeField("_id");
    }

    // Set collections
    DBCollection usersCollection = INSTANCE.getDatasource().getDbCollection(USERS_COLLECTION_NAME);
    DBCollection departmentsCollection = INSTANCE.getDatasource().getDbCollection(DEPARTMENTS_COLLECTION_NAME);
    DBCollection companiesCollection = INSTANCE.getDatasource().getDbCollection(COMPANIES_COLLECTION_NAME);
    usersCollection.setObjectClass(User.class);
    departmentsCollection.setObjectClass(Department.class);
    companiesCollection.setObjectClass(Company.class);

    // Check if the owner field is ok and retrieve the objectId
    ObjectId ownerId = checkOwner(process, usersCollection, departmentsCollection, companiesCollection);
    if (ownerId != null) {
        process.setOwnerId(ownerId);
    } else {
        log.error(MSG_ERR_NOT_VALID_OWNER_ID);
        throw new BadRequestException(MSG_ERR_NOT_VALID_OWNER_ID);
    }

    // Check if the users field is ok and retrieve the objectIds list
    List<Permission> permissionsList = checkPermissions(process, usersCollection, departmentsCollection,
            companiesCollection);
    if (permissionsList != null) {
        process.setPermissions(permissionsList);
    } else {
        log.error(MSG_ERR_NOT_VALID_PERMISSION);
        throw new BadRequestException(MSG_ERR_NOT_VALID_PERMISSION);
    }

    // Perform the update
    processesCollection = INSTANCE.getDatasource().getDbCollection(PROCESSES_COLLECTION_NAME);
    processesCollection.setObjectClass(Process.class);
    BasicDBObject query = new BasicDBObject();
    query.put("_id", new ObjectId(id));
    WriteResult wRes = processesCollection.update(query, process, true, false); // selection criteria, modifications to apply, upsert, multi-document

    // Output production
    String numUpdates = String.valueOf(wRes.getN()); // wRes.getN returns the number of updated objects
    String jsonMsg;
    try {
        jsonMsg = INSTANCE.getObjectMapper().writeValueAsString(process);
        log.debug(numUpdates + " processes updated: " + process);
    } catch (JsonProcessingException e) {
        log.error(e, e);
    }

    return process;
}

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.
 *//*ww w. j  a  v a  2  s  .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.
 *///from  w w w.j a  v  a 2s.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:org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore.java

License:Apache License

private DBCollection getBlobCollection() {
    DBCollection collection = db.getCollection(COLLECTION_BLOBS);
    collection.setObjectClass(MongoBlob.class);
    return collection;
}

From source file:org.broad.igv.plugin.mongocollab.MongoFeatureSource.java

License:Open Source License

public static FeatureTrack loadFeatureTrack(MongoCollabPlugin.Locator locator, List<Track> newTracks) {

    DBCollection collection = MongoCollabPlugin.getCollection(locator);
    //TODO Make this more flexible
    collection.setObjectClass(DBFeature.class);
    MongoFeatureSource source = new MongoFeatureSource(collection, locator.buildLocusIndex);
    FeatureTrack track = new MongoFeatureTrack(collection.getFullName(), collection.getName(), source);
    SearchCommand.registerNamedFeatureSearcher(source);
    newTracks.add(track);// w ww  .  ja  v  a  2s.  c  o m
    track.setMargin(0);
    return track;
}

From source file:org.datavyu.models.db.MongoDatastore.java

License:Open Source License

/**
 * Spin up the mongo instance so that we can query and do stuff with it.
 *//*from ww  w . ja  v a  2s .  c o m*/
public static void startMongo() {
    // Unpack the mongo executable.
    try {
        String mongoDir;
        switch (Datavyu.getPlatform()) {
        case MAC:
            mongoDir = NativeLoader.unpackNativeApp(mongoOSXLocation);
            break;
        case WINDOWS:
            mongoDir = NativeLoader.unpackNativeApp(mongoWindowsLocation);
            break;
        default:
            mongoDir = NativeLoader.unpackNativeApp(mongoOSXLocation);
        }

        // When files are unjared - they loose their executable status.
        // So find the mongod executable and set it to exe
        Collection<File> files = FileUtils.listFiles(new File(mongoDir), new RegexFileFilter(".*mongod.*"),
                TrueFileFilter.INSTANCE);

        File f;
        if (files.iterator().hasNext()) {
            f = files.iterator().next();
            f.setExecutable(true);
        } else {
            f = new File("");
            System.out.println("ERROR: Could not find mongod");
        }

        //            File f = new File(mongoDir + "/mongodb-osx-x86_64-2.0.2/bin/mongod");
        //            f.setExecutable(true);

        // Spin up a new mongo instance.
        File mongoD = new File(mongoDir);
        //            int port = findFreePort(27019);
        int port = 27019;

        // Try to shut down the server if it is already running
        try {
            mongoDriver = new Mongo("127.0.0.1", port);
            DB db = mongoDriver.getDB("admin");
            db.command(new BasicDBObject("shutdownServer", 1));
        } catch (Exception e) {
            e.printStackTrace();
        }

        mongoProcess = new ProcessBuilder(f.getAbsolutePath(), "--dbpath", mongoD.getAbsolutePath(),
                "--bind_ip", "127.0.0.1", "--port", String.valueOf(port), "--directoryperdb").start();
        //            InputStream in = mongoProcess.getInputStream();
        //            InputStreamReader isr = new InputStreamReader(in);

        System.out.println("Starting mongo driver.");
        mongoDriver = new Mongo("127.0.0.1", port);

        System.out.println("Getting DB");

        // Start with a clean DB
        mongoDB = mongoDriver.getDB("datavyu");

        DBCollection varCollection = mongoDB.getCollection("variables");
        varCollection.setObjectClass(MongoVariable.class);

        DBCollection cellCollection = mongoDB.getCollection("cells");
        cellCollection.setObjectClass(MongoCell.class);

        DBCollection matrixCollection = mongoDB.getCollection("matrix_values");
        matrixCollection.setObjectClass(MongoMatrixValue.class);

        DBCollection nominalCollection = mongoDB.getCollection("nominal_values");
        nominalCollection.setObjectClass(MongoNominalValue.class);

        DBCollection textCollection = mongoDB.getCollection("text_values");
        textCollection.setObjectClass(MongoTextValue.class);

        System.out.println("Got DB");
        running = true;

    } catch (Exception e) {
        System.err.println("Unable to fire up the mongo datastore.");
        e.printStackTrace();
    }
}

From source file:org.iternine.jeppetto.dao.mongodb.MongoDBQueryModelDAO.java

License:Apache License

@SuppressWarnings({ "unchecked" })
protected MongoDBQueryModelDAO(Class<T> entityClass, Map<String, Object> daoProperties,
        AccessControlContextProvider accessControlContextProvider) {
    this.dbCollection = ((DB) daoProperties.get("db")).getCollection(entityClass.getSimpleName());
    this.enhancer = EnhancerHelper.getDirtyableDBObjectEnhancer(entityClass);

    dbCollection.setObjectClass(enhancer.getEnhancedClass());

    DBCallback.FACTORY = new DBCallback.Factory() {
        @Override//from   w  ww . j a  va  2 s  .  c  om
        public DBCallback create(DBCollection dbCollection) {
            return new MongoDBCallback(dbCollection);
        }
    };

    this.accessControlContextProvider = accessControlContextProvider;
    this.uniqueIndexes = ensureIndexes((List<String>) daoProperties.get("uniqueIndexes"), true);
    ensureIndexes((List<String>) daoProperties.get("nonUniqueIndexes"), false);
    this.optimisticLockEnabled = Boolean.parseBoolean((String) daoProperties.get("optimisticLockEnabled"));
    this.shardKeys = extractShardKeys((String) daoProperties.get("shardKeyPattern"));
    this.saveNulls = Boolean.parseBoolean((String) daoProperties.get("saveNulls"));

    if (daoProperties.containsKey("writeConcern")) {
        this.defaultWriteConcern = WriteConcern.valueOf((String) daoProperties.get("writeConcern"));
    } else {
        this.defaultWriteConcern = WriteConcern.SAFE;
    }

    if (Boolean.parseBoolean((String) daoProperties.get("showQueries"))) {
        queryLogger = LoggerFactory.getLogger(getClass());
    }
}