Example usage for com.mongodb DBCollection setReadPreference

List of usage examples for com.mongodb DBCollection setReadPreference

Introduction

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

Prototype

public void setReadPreference(final ReadPreference preference) 

Source Link

Document

Sets the ReadPreference for this collection.

Usage

From source file:com.ebay.cloud.cms.config.CMSProperties.java

License:Apache License

private void loadProperties(Mongo mongo) {
    Map<String, Object> m = new ConcurrentHashMap<String, Object>();
    DBCollection collection = getPropertiesCollection(mongo);
    collection.setReadPreference(ReadPreference.primary());
    DBCursor cursor = collection.find();
    while (cursor.hasNext()) {
        BasicDBObject object = (BasicDBObject) cursor.next();
        String key = getKey(object);
        if (key != null) {
            m.put(key, object.get(key));
        }//from  w w  w .ja v  a 2s  .  c o  m
    }

    cachedConfigurations = m;
}

From source file:com.ebay.cloud.cms.dal.persistence.PersistenceContext.java

License:Apache License

public DBCollection getDBCollection(MetaClass metadata) {
    DB db = getDB();// w w  w .j  a va 2  s . co m
    String collectionName = getDBCollectionName(metadata);
    DBCollection dbCol = db.getCollection(collectionName);
    dbCol.setReadPreference(consistentPolicy.getReadPreference());
    dbCol.setWriteConcern(consistentPolicy.getWriteConcern());
    return dbCol;
}

From source file:com.ebay.cloud.cms.metadata.mongo.MongoMetadataServiceImpl.java

License:Apache License

@Override
public int getCollectionCount(String dbCollectionName) {
    CheckConditions.checkNotNull(dbCollectionName, "Collection name can't be null!");
    Integer count = cacheManager.getCountFromCache(dbCollectionName);
    if (count == null) {
        DBCollection col = this.mongo.getDB(repo.getRepositoryName()).getCollection(dbCollectionName);
        // read from primary only
        col.setReadPreference(ReadPreference.primary());
        col.setWriteConcern(WriteConcern.SAFE);

        count = (Integer) col.getStats().get("count");
        if (count == null) {
            count = 0;/* w  w  w .  ja  v  a  2s . c om*/
        } else {
            cacheManager.putCountToCache(dbCollectionName, count);
        }
    }
    return count;
}

From source file:com.ebay.cloud.cms.metadata.mongo.MongoRepositoryServiceImpl.java

License:Apache License

@Override
public Repository createRepository(Repository repo, WriteConcern writeConcern) {
    CheckConditions.checkNotNull(repo, "repository can not be null");
    CheckConditions.checkNotNull(repo.getRepositoryName(), "repository name can not be null");
    String repositoryName = repo.getRepositoryName();

    try {//from  w w  w  . j  ava  2s . c om
        metadataLock.lock();

        try {
            repoCollection.insert(repositoryConverter.toBson(repo));
        } catch (MongoException.DuplicateKey e) {
            throw new RepositoryExistsException(repositoryName);
        }

        // build index
        try {
            DBCollection metaCollection = mongo.getDB(repo.getRepositoryName())
                    .getCollection(CMSConsts.METACLASS_COLL);
            metaCollection.setReadPreference(ReadPreference.primary());
            MongoUtils.ensureIndex(metaCollection, MetaClass.NAME, true, false);
            MongoUtils.ensureIndex(metaCollection, MetaClass.PLURAL_NAME, true, true);

            createServiceForRepository(repo);
            // init created system meta class
            HistoryMetaClass.createHistoryMetaClass(repo);
            BranchMetaClass.createBranchMetaClass(repo);
        } catch (Throwable e) {
            logger.warn("create repo db failed, remove the repo entry in repository coll", e);
            try {
                repoCollection.remove(repositoryConverter.toBson(repo));
            } catch (Exception ee) {
                logger.error("remove repo db failed", ee);
            }
            throw new MetaDataException(MetaErrCodeEnum.CREATE_REPOSITORY_ERROR,
                    "create repository " + repositoryName + " failed", e);
        }

        refreshRepositoryCache();
        return repo;
    } catch (InterruptedException e) {
        logger.info("lock interrupted for createRepository " + repositoryName);
        throw new MetaDataException(MetaErrCodeEnum.LOCK_INTERRUPTED,
                "lock interrupted for createRepository " + repositoryName, e);
    } finally {
        metadataLock.unlock();
    }
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

public void readWriteOptions(ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    OptionDialog od = UMongo.instance.getGlobalStore().getOptionDialog();
    od.update(col.getOptions(), col.getWriteConcern(), col.getReadPreference());
    if (!od.show()) {
        return;//from  ww w  . j av  a2  s  . c  o  m
    }
    col.setOptions(od.getQueryOptions());
    col.setWriteConcern(od.getWriteConcern());
    col.setReadPreference(od.getReadPreference());
    refresh();
}

From source file:org.datanucleus.store.mongodb.MongoDBUtils.java

License:Open Source License

/**
 * Convenience method to return all objects of the candidate type (optionally allowing subclasses).
 * @param q Query//from w  w w  . java  2  s.c om
 * @param db Mongo DB
 * @param filterObject Optional filter object
 * @param orderingObject Optional ordering object
 * @param options Set of options for controlling this query
 * @param skip Number of records to skip
 * @param limit Max number of records to return
 * @return List of all candidate objects (implements QueryResult)
 */
public static List getObjectsOfCandidateType(Query q, DB db, BasicDBObject filterObject,
        BasicDBObject orderingObject, Map<String, Object> options, Integer skip, Integer limit) {
    LazyLoadQueryResult qr = new LazyLoadQueryResult(q);

    // Find the DBCollections we need to query
    ExecutionContext ec = q.getExecutionContext();
    StoreManager storeMgr = ec.getStoreManager();
    ClassLoaderResolver clr = ec.getClassLoaderResolver();
    List<AbstractClassMetaData> cmds = MetaDataUtils.getMetaDataForCandidates(q.getCandidateClass(),
            q.isSubclasses(), ec);

    Map<String, List<AbstractClassMetaData>> classesByCollectionName = new HashMap();
    for (AbstractClassMetaData cmd : cmds) {
        if (cmd instanceof ClassMetaData && ((ClassMetaData) cmd).isAbstract()) {
            // Omit any classes that are not instantiable (e.g abstract)
        } else {
            String collectionName = storeMgr.getNamingFactory().getTableName(cmd);
            List<AbstractClassMetaData> cmdsForCollection = classesByCollectionName.get(collectionName);
            if (cmdsForCollection == null) {
                cmdsForCollection = new ArrayList();
                classesByCollectionName.put(collectionName, cmdsForCollection);
            }
            cmdsForCollection.add(cmd);
        }
    }

    // Add a query for each DBCollection we need
    Iterator<Map.Entry<String, List<AbstractClassMetaData>>> iter = classesByCollectionName.entrySet()
            .iterator();
    while (iter.hasNext()) {
        Map.Entry<String, List<AbstractClassMetaData>> entry = iter.next();
        String collectionName = entry.getKey();
        List<AbstractClassMetaData> cmdsForCollection = entry.getValue();

        AbstractClassMetaData rootCmd = cmdsForCollection.get(0);
        int[] fpMembers = q.getFetchPlan().getFetchPlanForClass(rootCmd).getMemberNumbers();
        BasicDBObject fieldsSelection = new BasicDBObject();
        if (fpMembers != null && fpMembers.length > 0) {
            fieldsSelection = new BasicDBObject();
            for (int i = 0; i < fpMembers.length; i++) {
                AbstractMemberMetaData mmd = rootCmd
                        .getMetaDataForManagedMemberAtAbsolutePosition(fpMembers[i]);
                RelationType relationType = mmd.getRelationType(clr);
                if (mmd.isEmbedded() && RelationType.isRelationSingleValued(relationType)) {
                    boolean nested = true;
                    String nestedStr = mmd.getValueForExtension("nested");
                    if (nestedStr != null && nestedStr.equalsIgnoreCase("false")) {
                        nested = false;
                    }

                    if (nested) {
                        // Nested Embedded field, so include field
                        String fieldName = storeMgr.getNamingFactory().getColumnName(mmd, ColumnType.COLUMN);
                        fieldsSelection.append(fieldName, 1);
                    } else {
                        // Flat Embedded field, so add all fields of sub-objects
                        selectAllFieldsOfEmbeddedObject(mmd, fieldsSelection, ec, clr);
                    }
                } else {
                    String fieldName = storeMgr.getNamingFactory().getColumnName(mmd, ColumnType.COLUMN);
                    fieldsSelection.append(fieldName, 1);
                }
            }
        }
        if (rootCmd.getIdentityType() == IdentityType.DATASTORE) {
            fieldsSelection.append(
                    storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DATASTOREID_COLUMN), 1);
        }
        if (rootCmd.isVersioned()) {
            VersionMetaData vermd = rootCmd.getVersionMetaDataForClass();
            if (vermd.getFieldName() != null) {
                AbstractMemberMetaData verMmd = rootCmd.getMetaDataForMember(vermd.getFieldName());
                String fieldName = storeMgr.getNamingFactory().getColumnName(verMmd, ColumnType.COLUMN);
                fieldsSelection.append(fieldName, 1);
            } else {
                fieldsSelection.append(
                        storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.VERSION_COLUMN), 1);
            }
        }
        if (rootCmd.hasDiscriminatorStrategy()) {
            fieldsSelection.append(
                    storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DISCRIMINATOR_COLUMN), 1);
        }

        BasicDBObject query = new BasicDBObject();
        if (filterObject != null) {
            Iterator<Map.Entry<String, Object>> filterEntryIter = filterObject.entrySet().iterator();
            while (filterEntryIter.hasNext()) {
                Map.Entry<String, Object> filterEntry = filterEntryIter.next();
                query.put(filterEntry.getKey(), filterEntry.getValue());
            }
        }

        if (rootCmd.hasDiscriminatorStrategy() && cmdsForCollection.size() == 1) {
            // TODO Add this restriction on *all* possible cmds for this DBCollection
            // Discriminator present : Add restriction on the discriminator value for this class
            query.put(storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DISCRIMINATOR_COLUMN),
                    rootCmd.getDiscriminatorValue());
        }

        if (storeMgr.getStringProperty(PropertyNames.PROPERTY_TENANT_ID) != null) {
            // Multitenancy discriminator present : Add restriction for this tenant
            if ("true".equalsIgnoreCase(rootCmd.getValueForExtension("multitenancy-disable"))) {
                // Don't bother with multitenancy for this class
            } else {
                String fieldName = storeMgr.getNamingFactory().getColumnName(rootCmd,
                        ColumnType.MULTITENANCY_COLUMN);
                String value = storeMgr.getStringProperty(PropertyNames.PROPERTY_TENANT_ID);
                query.put(fieldName, value);
            }
        }

        DBCollection dbColl = db.getCollection(collectionName);
        Object val = (options != null ? options.get("slave-ok") : Boolean.FALSE);
        if (val == Boolean.TRUE) {
            dbColl.setReadPreference(ReadPreference.secondaryPreferred());
        }

        if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) {
            NucleusLogger.DATASTORE_NATIVE
                    .debug("Performing find() using query on collection " + collectionName + " for fields="
                            + fieldsSelection + " with filter=" + query + " and ordering=" + orderingObject);
        }
        DBCursor curs = dbColl.find(query, fieldsSelection);
        if (ec.getStatistics() != null) {
            // Add to statistics
            ec.getStatistics().incrementNumReads();
        }

        if (classesByCollectionName.size() == 1) {
            if (orderingObject != null) {
                curs = curs.sort(orderingObject);
                qr.setOrderProcessed(true);
            }

            // We have a single DBCursor so apply the range specification directly to this DBCursor
            if (skip != null && skip > 0) {
                curs = curs.skip(skip);
                qr.setRangeProcessed(true);
            }
            if (limit != null && limit > 0) {
                curs = curs.limit(limit);
                qr.setRangeProcessed(true);
            }
        }

        qr.addCandidateResult(rootCmd, curs, fpMembers);
    }

    return qr;
}

From source file:org.eclipselabs.mongoemf.handlers.MongoURIHandlerImpl.java

License:Open Source License

/**
 * This function locates the MongoDB collection instance corresponding to the collection
 * identifier extracted from the URI. The URI path must have exactly 3 segments and be of the form
 * mongodb://host:[port]/database/collection/{id} where id is optional.
 * /*from  ww  w.  j ava 2  s .  com*/
 * @param uri the MongoDB collection identifier
 * @param options the load or save options as appropriate
 * @return the MongoDB collection corresponding to the URI
 * @throws IOException if the URI is malformed or the collection could not otherwise be resolved
 */
private DBCollection getCollection(URI uri, Map<?, ?> options) throws IOException {
    // We assume that the URI path has the form /database/collection/{id} making the
    // collection segment # 1.

    if (uri.segmentCount() != 3)
        throw new IOException("The URI is not of the form 'mongodb:/database/collection/{id}");

    MongoDatabaseProvider mongoDatabaseProvider = mongoDatabaseProviders
            .get(uri.trimQuery().trimFragment().trimSegments(2).toString());

    if (mongoDatabaseProvider == null)
        throw new IOException("Database is not available");

    DB database = mongoDatabaseProvider.getDB();

    if (database == null)
        throw new IOException("Database is not available");

    DBCollection dbCollection = database.getCollection(uri.segment(1));

    ReadPreference readPreference = (ReadPreference) options.get(Options.OPTION_READ_PREFERENCE);

    if (readPreference != null)
        dbCollection.setReadPreference(readPreference);

    return dbCollection;
}

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

License:Apache License

/**
 * Prepare the collection before any processing is done using it. This allows a convenient way to apply settings like
 * slaveOk() etc. Can be overridden in sub-classes.
 * //from  www.  ja  v a2  s  .  c o m
 * @param collection
 */
protected void prepareCollection(DBCollection collection) {
    if (this.readPreference != null) {
        collection.setReadPreference(readPreference);
    }
}