net.ymate.platform.persistence.mongodb.support.MongoDBHelper.java Source code

Java tutorial

Introduction

Here is the source code for net.ymate.platform.persistence.mongodb.support.MongoDBHelper.java

Source

/*
 * Copyright 2007-2107 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.ymate.platform.persistence.mongodb.support;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import net.ymate.platform.persistence.base.ConnectionException;
import net.ymate.platform.persistence.base.OperatorException;
import net.ymate.platform.persistence.mongodb.IMongoClientHolder;
import net.ymate.platform.persistence.mongodb.MongoDB;
import net.ymate.platform.persistence.mongodb.MongoDB.OrderBy;

import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MapReduceCommand.OutputType;
import com.mongodb.MapReduceOutput;

/**
 * <p>
 * IMongoDBHelper
 * </p>
 * <p>
 * MongoDB
 * </p>
 * 
 * @author (suninformation@163.com)
 * @version 0.0.0
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">?</th><th width="100px"></th><th
 *          width="100px"></th><th width="100px"></th>
 *          </tr>
 *          <!--  Table ?? -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td></td>
 *          <td></td>
 *          <td>2014227?8:40:54</td>
 *          </tr>
 *          </table>
 */
public class MongoDBHelper {

    private IMongoClientHolder __holder;

    protected Map<String, DBCollection> __collectionCaches = new ConcurrentHashMap<String, DBCollection>();

    /**
     * 
     * 
     * @param holder DB?
     */
    private MongoDBHelper(IMongoClientHolder holder) {
        this.__holder = holder;
    }

    /**
     * @param holder DB?
     * @return DB
     */
    public static MongoDBHelper bind(IMongoClientHolder holder) {
        return new MongoDBHelper(holder);
    }

    /**
     * @param dsName ????
     * @param dbName ???
     * @return ??
     * @throws ConnectionException
     */
    public static MongoDBHelper bind(String dsName, String dbName) throws ConnectionException {
        return new MongoDBHelper(MongoDB.getMongoClientHolder(dsName, dbName));
    }

    /**
     * @param dbName ???
     * @return ??
     * @throws ConnectionException
     */
    public static MongoDBHelper bind(String dbName) throws ConnectionException {
        return new MongoDBHelper(MongoDB.getMongoClientHolder(dbName));
    }

    /**
     * @return ??
     */
    public IMongoClientHolder getClientHolder() {
        return __holder;
    }

    /**
     * ??
     */
    public void begin() {
        __holder.requestStart();
    }

    /**
     * ???
     */
    public void keep() {
        __holder.requestEnsureConnection();
    }

    /**
     * ??
     */
    public void end() {
        __holder.requestDone();
    }

    /**
     * ??
     */
    public void release() {
        __holder.release();
        __holder = null;
        //
        __collectionCaches.clear();
        __collectionCaches = null;
    }

    /**
     * ???
     * 
     * @param dbName ???
     */
    public static void drapDatabase(String dbName) {
        MongoDB.getCachedMongoClient(MongoDB.DATASOURCE_DEFAULT_NAME).dropDatabase(dbName);
    }

    /**
     * ???
     * 
     * @param dsName ????
     * @param dbName ???
     */
    public static void drapDatabase(String dsName, String dbName) {
        MongoDB.getCachedMongoClient(dsName).dropDatabase(dbName);
    }

    /**
     * ?
     * 
     * @param name ???
     * @return ?
     */
    public DBCollection createCollection(String name) {
        return __holder.getDB().createCollection(name, new BasicDBObject());
    }

    /**
     * copped?
     * 
     * @param name ???
     * @param size
     * @param max
     * @return ?
     */
    public DBCollection createCollection(String name, long size, long max) {
        DBObject _options = new BasicDBObject();
        _options.put("copped", true);
        if (size > 0) {
            _options.put("size", size);
        }
        if (max > 0) {
            _options.put("max", max);
        }
        return __holder.getDB().createCollection(name, _options);
    }

    public DBCollection getCollection(String name) {
        DBCollection _collection = __collectionCaches.get(name);
        if (_collection == null) {
            _collection = __holder.getDB().getCollection(name);
            if (_collection != null) {
                __collectionCaches.put(name, _collection);
            }
        }
        return _collection;
    }

    public boolean isCollectionExists(String name) {
        return __collectionCaches.containsKey(name) || __holder.getDB().collectionExists(name);
    }

    /**
     * ??
     * 
     * @param name ???
     */
    public void clearCollection(String name) {
        __holder.getDB().getCollection(name).remove(new BasicDBObject(), __holder.getWriteConcern());
    }

    /**
     * ?
     * 
     * @param name ???
     */
    public void dropCollection(String name) {
        getCollection(name).drop();
        getCollection(name).dropIndexes();
    }

    public Iterable<DBObject> mapReduce(String collectionName, String map, String reduce, DBObject query)
            throws OperatorException {
        MapReduceOutput _output = getCollection(collectionName).mapReduce(map, reduce, null, OutputType.INLINE,
                query);
        CommandResult _result = _output.getCommandResult();
        if (!_result.ok()) {
            throw new OperatorException(_result.getErrorMessage());
        }
        return _output.results();
    }

    public Iterable<DBObject> mapReduce(String collectionName, String map, String reduce, String outputTarget,
            OutputType type, OrderBy order, DBObject query) throws OperatorException {
        return mapReduce(collectionName, map, reduce, outputTarget, type, order, 0, 0, query);
    }

    public Iterable<DBObject> mapReduce(String collectionName, String map, String reduce, String outputTarget,
            OutputType type, OrderBy order, int pageNumber, int pageSize, DBObject query) throws OperatorException {
        MapReduceOutput _output = getCollection(collectionName).mapReduce(map, reduce, outputTarget, type, query);
        CommandResult _result = _output.getCommandResult();
        if (!_result.ok()) {
            throw new OperatorException(_result.getErrorMessage());
        }
        DBCollection _collection = _output.getOutputCollection();
        DBCursor _cursor = null;
        if (order != null) {
            _cursor = _collection.find().sort(order.toDBObject());
        } else {
            _cursor = _collection.find();
        }
        if (pageNumber > 0 && pageSize > 0) {
            _cursor.skip((pageNumber - 1) * pageSize).limit(pageSize);
        }
        List<DBObject> _results = new ArrayList<DBObject>();
        for (Iterator<DBObject> _it = _cursor.iterator(); _it.hasNext();) {
            _results.add(_it.next());
        }
        return _results;
    }

}