Browse Source

清理esb-admin中的mongo封装

Airhead 8 years ago
parent
commit
f30c65fdbe

+ 0 - 98
src/main/java/com/yihu/hos/common/mongo/IMongoDBAdminer.java

@ -1,98 +0,0 @@
package com.yihu.hos.common.mongo;
import java.util.List;
/**
 * @created Airhead 2016/2/17.
 */
public interface IMongoDBAdminer {
    /**
     * Drops this collection from the Database.
     *
     * @mongodb.driver.manual reference/command/drop/ Drop Collection
     */
    void drop(String collectionName);
    /**
     * Create an index with the given keys.
     *
     * @param keys an object describing the index key(s), which may not be null.
     * @return the index name
     * @mongodb.driver.manual reference/command/createIndexes Create indexes
     */
    String createIndex(String collectionName, String keys);
    /**
     * Create an index with the given keys and options.
     *
     * @param keys         an object describing the index key(s), which may not be null.
     * @param indexOptions the options for the index
     * @return the index name
     * @mongodb.driver.manual reference/command/createIndexes Create indexes
     */
    String createIndex(String collectionName, String keys, String indexOptions);
    /**
     * Create multiple indexes.
     *
     * @param indexes the list of indexes
     * @return the list of index names
     * @mongodb.driver.manual reference/command/createIndexes Create indexes
     * @mongodb.server.release 2.6
     */
//    List<String> createIndexes(List<IndexModel> indexes);
    /**
     * Get all the indexes in this collection.
     *
     * @return the list indexes iterable interface
     * @mongodb.driver.manual reference/command/listIndexes/ List indexes
     */
    List<String> listIndexes(String collectionName);
    /**
     * Get all the indexes in this collection.
     *
     * @param resultClass the class to decode each document into
     * @param <TResult>   the target document type of the iterable.
     * @return the list indexes iterable interface
     * @mongodb.driver.manual reference/command/listIndexes/ List indexes
     */
//    <TResult> ListIndexesIterable<TResult> listIndexes(Class<TResult> resultClass);
    /**
     * Drops the index given its name.
     *
     * @param indexName the name of the index to remove
     * @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes
     */
    void dropIndex(String collectionName, String indexName);
    /**
     * Drop all the indexes on this collection, except for the default on _id.
     *
     * @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes
     */
    void dropIndexes(String collectionName);
    /**
     * Rename the collection with oldCollectionName to the newCollectionName.
     *
     * @param newCollectionName the namespace the collection will be renamed to
     * @throws com.mongodb.MongoServerException if you provide a newCollectionName that is the name of an existing collection, or if the
     *                                          oldCollectionName is the name of a collection that doesn't exist
     * @mongodb.driver.manual reference/commands/renameCollection Rename collection
     */
    void renameCollection(String collectionName, String newCollectionName);
    /**
     * Rename the collection with oldCollectionName to the newCollectionName.
     *
     * @param newCollectionName       the name the collection will be renamed to
     * @param renameCollectionOptions the options for renaming a collection
     * @throws com.mongodb.MongoServerException if you provide a newCollectionName that is the name of an existing collection and dropTarget
     *                                          is false, or if the oldCollectionName is the name of a collection that doesn't exist
     * @mongodb.driver.manual reference/commands/renameCollection Rename collection
     */
    void renameCollection(String collectionName, String newCollectionName, String renameCollectionOptions);
}

+ 0 - 376
src/main/java/com/yihu/hos/common/mongo/IMongoDBRunner.java

@ -1,376 +0,0 @@
package com.yihu.hos.common.mongo;
import java.util.List;
/**
 * MongoDB的CURD接口,此部分内容从MongoCollection中来
 *
 * @created Airhead 2016/2/17.
 */
public interface IMongoDBRunner {
    long count(String collectionName);
    /**
     * Counts the number of documents in the collection according to the given options.
     *
     * @param filter the query filter
     * @return the number of documents in the collection
     */
    long count(String collectionName, String filter);
    /**
     * Counts the number of documents in the collection according to the given options.
     *
     * @param filter  the query filter
     * @param options the options describing the count
     * @return the number of documents in the collection
     */
    long count(String collectionName, String filter, String options);
    /**
     * Gets the distinct values of the specified field name.
     *
     * @param fieldName   the field name
     * @param resultClass the class to cast any distinct items into.
     * @param <TResult>   the target type of the iterable.
     * @return an iterable of distinct values
     * @mongodb.driver.manual reference/command/distinct/ Distinct
     */
//    <TResult> DistinctIterable<TResult> distinct(String fieldName, Class<TResult> resultClass);
    /**
     * Gets the distinct values of the specified field name.
     *
     * @param fieldName   the field name
     * @param filter      the query filter
     * @param resultClass the class to cast any distinct items into.
     * @param <TResult>   the target type of the iterable.
     * @return an iterable of distinct values
     * @mongodb.driver.manual reference/command/distinct/ Distinct
     */
//    <TResult> DistinctIterable<TResult> distinct(String fieldName, Bson filter, Class<TResult> resultClass);
    /**
     * Finds all documents in the collection.
     *
     * @return the find iterable interface
     * @mongodb.driver.manual tutorial/query-documents/ Find
     */
    List<String> find(String collectionName);
    /**
     * Finds all documents in the collection.
     *
     * @param resultClass the class to decode each document into
     * @param <TResult>   the target document type of the iterable.
     * @return the find iterable interface
     * @mongodb.driver.manual tutorial/query-documents/ Find
     */
//    <TResult> FindIterable<TResult> find(Class<TResult> resultClass);
    /**
     * Finds all documents in the collection.
     *
     * @param filter the query filter
     * @return the find iterable interface
     * @mongodb.driver.manual tutorial/query-documents/ Find
     */
    List<String> find(String collectionName, String filter);
    /**
     * Finds all documents in the collection.
     *
     * @param filter the query filter
     * @return the find iterable interface
     * @mongodb.driver.manual tutorial/query-documents/ Find
     */
    List<String> find(String collectionName, String filter, String projection);
    /**
     * Finds all documents in the collection.
     *
     * @param filter the query filter
     * @return the find iterable interface
     * @mongodb.driver.manual tutorial/query-documents/ Find
     */
    List<String> find(String collectionName, String filter, String projection, String options);
    /**
     * Finds all documents in the collection.
     *
     * @param filter      the query filter
     * @param resultClass the class to decode each document into
     * @param <TResult>   the target document type of the iterable.
     * @return the find iterable interface
     * @mongodb.driver.manual tutorial/query-documents/ Find
     */
//    <TResult> FindIterable<TResult> find(Bson filter, Class<TResult> resultClass);
    /**
     * Aggregates documents according to the specified aggregation pipeline.
     *
     * @param pipeline the aggregate pipeline
     * @return an iterable containing the result of the aggregation operation
     * @mongodb.driver.manual aggregation/ Aggregation
     * @mongodb.server.release 2.2
     */
//    List<String> aggregate(String collectionName, List<? extends String> pipeline);
    /**
     * Aggregates documents according to the specified aggregation pipeline.
     *
     * @param pipeline    the aggregate pipeline
     * @param resultClass the class to decode each document into
     * @param <TResult>   the target document type of the iterable.
     * @return an iterable containing the result of the aggregation operation
     * @mongodb.driver.manual aggregation/ Aggregation
     * @mongodb.server.release 2.2
     */
//    <TResult> AggregateIterable<TResult> aggregate(List<? extends Bson> pipeline, Class<TResult> resultClass);
    /**
     * Aggregates documents according to the specified map-reduce function.
     *
     * @param mapFunction    A JavaScript function that associates or "maps" a value with a key and emits the key and value pair.
     * @param reduceFunction A JavaScript function that "reduces" to a single object all the values associated with a particular key.
     * @return an iterable containing the result of the map-reduce operation
     * @mongodb.driver.manual reference/command/mapReduce/ map-reduce
     */
//    List<String> mapReduce(String collectionName, String mapFunction, String reduceFunction);
    /**
     * Aggregates documents according to the specified map-reduce function.
     *
     * @param mapFunction    A JavaScript function that associates or "maps" a value with a key and emits the key and value pair.
     * @param reduceFunction A JavaScript function that "reduces" to a single object all the values associated with a particular key.
     * @param resultClass    the class to decode each resulting document into.
     * @param <TResult>      the target document type of the iterable.
     * @return an iterable containing the result of the map-reduce operation
     * @mongodb.driver.manual reference/command/mapReduce/ map-reduce
     */
//    <TResult> MapReduceIterable<TResult> mapReduce(String mapFunction, String reduceFunction, Class<TResult> resultClass);
    /**
     * Executes a mix of inserts, updates, replaces, and deletes.
     *
     * @param requests the writes to execute
     * @return the result of the bulk write
     * @throws com.mongodb.MongoBulkWriteException if there's an exception in the bulk write operation
     * @throws com.mongodb.MongoException          if there's an exception running the operation
     */
//    BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDocument>> requests);
    /**
     * Executes a mix of inserts, updates, replaces, and deletes.
     *
     * @param requests the writes to execute
     * @param options  the options to apply to the bulk write operation
     * @return the result of the bulk write
     * @throws com.mongodb.MongoBulkWriteException if there's an exception in the bulk write operation
     * @throws com.mongodb.MongoException          if there's an exception running the operation
     */
//    BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDocument>> requests, BulkWriteOptions options);
    /**
     * Inserts the provided document. If the document is missing an identifier, the driver should generate one.
     *
     * @param document the document to insert
     * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the insert command
     * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException             if the write failed due some other failure
     */
    void insertOne(String collectionName, String document);
    /**
     * Inserts one or more documents.  A call to this method is equivalent to a call to the {@code bulkWrite} method
     *
     * @param documents the documents to insert
     * @throws com.mongodb.MongoBulkWriteException if there's an exception in the bulk write operation
     * @throws com.mongodb.MongoException          if the write failed due some other failure
     * @see com.mongodb.client.MongoCollection#bulkWrite
     */
    void insertMany(String collectionName, List<String> documents);
    /**
     * Inserts one or more documents.  A call to this method is equivalent to a call to the {@code bulkWrite} method
     *
     * @param documents the documents to insert
     * @param options   the options to apply to the operation
     * @throws com.mongodb.DuplicateKeyException if the write failed to a duplicate unique key
     * @throws com.mongodb.WriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException        if the write failed due some other failure
     */
    void insertMany(String collectionName, List<String> documents, String options);
    /**
     * Removes at most one document from the collection that matches the given filter.  If no documents match, the collection is not
     * modified.
     *
     * @param filter the query filter to apply the the delete operation
     * @return the result of the remove one operation
     * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the delete command
     * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException             if the write failed due some other failure
     */
    long deleteOne(String collectionName, String filter);
    /**
     * Removes all documents from the collection that match the given query filter.  If no documents match, the collection is not modified.
     *
     * @param filter the query filter to apply the the delete operation
     * @return the result of the remove many operation
     * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the delete command
     * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException             if the write failed due some other failure
     */
    long deleteMany(String collectionName, String filter);
    /**
     * Replace a document in the collection according to the specified arguments.
     *
     * @param filter      the query filter to apply the the replace operation
     * @param replacement the replacement document
     * @return the result of the replace one operation
     * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the replace command
     * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException             if the write failed due some other failure
     * @mongodb.driver.manual tutorial/modify-documents/#replace-the-document Replace
     */
    long replaceOne(String collectionName, String filter, String replacement);
    /**
     * Replace a document in the collection according to the specified arguments.
     *
     * @param filter        the query filter to apply the the replace operation
     * @param replacement   the replacement document
     * @param updateOptions the options to apply to the replace operation
     * @return the result of the replace one operation
     * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the replace command
     * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException             if the write failed due some other failure
     * @mongodb.driver.manual tutorial/modify-documents/#replace-the-document Replace
     */
    long replaceOne(String collectionName, String filter, String replacement, String updateOptions);
    /**
     * Update a single document in the collection according to the specified arguments.
     *
     * @param filter a document describing the query filter, which may not be null.
     * @param update a document describing the update, which may not be null. The update to apply must include only update operators.
     * @return the result of the update one operation
     * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the update command
     * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException             if the write failed due some other failure
     * @mongodb.driver.manual tutorial/modify-documents/ Updates
     * @mongodb.driver.manual reference/operator/update/ Update Operators
     */
    long updateOne(String collectionName, String filter, String update);
    /**
     * Update a single document in the collection according to the specified arguments.
     *
     * @param filter        a document describing the query filter, which may not be null.
     * @param update        a document describing the update, which may not be null. The update to apply must include only update operators.
     * @param updateOptions the options to apply to the update operation
     * @return the result of the update one operation
     * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the update command
     * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException             if the write failed due some other failure
     * @mongodb.driver.manual tutorial/modify-documents/ Updates
     * @mongodb.driver.manual reference/operator/update/ Update Operators
     */
    long updateOne(String collectionName, String filter, String update, String updateOptions);
    /**
     * Update all documents in the collection according to the specified arguments.
     *
     * @param filter a document describing the query filter, which may not be null.
     * @param update a document describing the update, which may not be null. The update to apply must include only update operators.
     * @return the result of the update one operation
     * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the update command
     * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException             if the write failed due some other failure
     * @mongodb.driver.manual tutorial/modify-documents/ Updates
     * @mongodb.driver.manual reference/operator/update/ Update Operators
     */
    long updateMany(String collectionName, String filter, String update);
    /**
     * Update all documents in the collection according to the specified arguments.
     *
     * @param filter        a document describing the query filter, which may not be null.
     * @param update        a document describing the update, which may not be null. The update to apply must include only update operators.
     * @param updateOptions the options to apply to the update operation
     * @return the result of the update one operation
     * @throws com.mongodb.MongoWriteException        if the write failed due some other failure specific to the update command
     * @throws com.mongodb.MongoWriteConcernException if the write failed due being unable to fulfil the write concern
     * @throws com.mongodb.MongoException             if the write failed due some other failure
     * @mongodb.driver.manual tutorial/modify-documents/ Updates
     * @mongodb.driver.manual reference/operator/update/ Update Operators
     */
    long updateMany(String collectionName, String filter, String update, String updateOptions);
    /**
     * Atomically find a document and remove it.
     *
     * @param filter the query filter to find the document with
     * @return the document that was removed.  If no documents matched the query filter, then null will be returned
     */
    String findOneAndDelete(String collectionName, String filter);
    /**
     * Atomically find a document and remove it.
     *
     * @param filter  the query filter to find the document with
     * @param options the options to apply to the operation
     * @return the document that was removed.  If no documents matched the query filter, then null will be returned
     */
    String findOneAndDelete(String collectionName, String filter, String options);
    /**
     * Atomically find a document and replace it.
     *
     * @param filter      the query filter to apply the the replace operation
     * @param replacement the replacement document
     * @return the document that was replaced.  Depending on the value of the {@code returnOriginal} property, this will either be the
     * document as it was before the update or as it is after the update.  If no documents matched the query filter, then null will be
     * returned
     */
    String findOneAndReplace(String collectionName, String filter, String replacement);
    /**
     * Atomically find a document and replace it.
     *
     * @param filter      the query filter to apply the the replace operation
     * @param replacement the replacement document
     * @param options     the options to apply to the operation
     * @return the document that was replaced.  Depending on the value of the {@code returnOriginal} property, this will either be the
     * document as it was before the update or as it is after the update.  If no documents matched the query filter, then null will be
     * returned
     */
    String findOneAndReplace(String collectionName, String filter, String replacement, String options);
    /**
     * Atomically find a document and update it.
     *
     * @param filter a document describing the query filter, which may not be null.
     * @param update a document describing the update, which may not be null. The update to apply must include only update operators.
     * @return the document that was updated before the update was applied.  If no documents matched the query filter, then null will be
     * returned
     */
    String findOneAndUpdate(String collectionName, String filter, String update);
    /**
     * Atomically find a document and update it.
     *
     * @param filter  a document describing the query filter, which may not be null.
     * @param update  a document describing the update, which may not be null. The update to apply must include only update operators.
     * @param options the options to apply to the operation
     * @return the document that was updated.  Depending on the value of the {@code returnOriginal} property, this will either be the
     * document as it was before the update or as it is after the update.  If no documents matched the query filter, then null will be
     * returned
     */
    String findOneAndUpdate(String collectionName, String filter, String update, String options);
}

+ 0 - 172
src/main/java/com/yihu/hos/common/mongo/MongoDB.java

@ -1,172 +0,0 @@
package com.yihu.hos.common.mongo;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import java.util.List;
/**
 * 提供对MongoDB的封装,减化对Mongo使用.
 * 主要就是减少层级关系,过滤掉资源释放等处理。
 * 注意:
 * 部分接口为了保持高效的情况,建议还是使用原生驱动。
 * 可以用getCollection取到原生MongoCollection<Document>
 * usage:
 * 1.使用MongoDBKit.addConfig()
 * 2.使用MongoDBKit.start();
 * 3.使用MongoDB做查询
 * 4.使用use()切换连接查询
 *
 * @created Airhead 2016/2/17.
 */
public class MongoDB {
    private static MongoDBPro mongoDBPro;
    static void init() {
        mongoDBPro = MongoDBPro.use();
    }
    public static MongoDBPro use(String configName) {
        return MongoDBPro.use(configName);
    }
    public static MongoDBPro db(String databaseName) {
        return mongoDBPro.db(databaseName);
    }
    public static long count(String collectionName) {
        return mongoDBPro.count(collectionName);
    }
    public static long count(String collectionName, String filter) {
        return mongoDBPro.count(collectionName, filter);
    }
    public static long count(String collectionName, String filter, String options) {
        return mongoDBPro.count(collectionName, filter, options);
    }
    public static List<String> find(String collectionName) {
        return mongoDBPro.find(collectionName);
    }
    public static List<String> find(String collectionName, String filter) {
        return mongoDBPro.find(collectionName, filter);
    }
    public static List<String> find(String collectionName, String filter, String projection) {
        return mongoDBPro.find(collectionName, filter, projection);
    }
    public static List<String> find(String collectionName, String filter, String projection, String options) {
        return mongoDBPro.find(collectionName, filter, projection, options);
    }
    public static void insertOne(String collectionName, String document) {
        mongoDBPro.insertOne(collectionName, document);
    }
    public static void insertMany(String collectionName, List<String> documents) {
        mongoDBPro.insertMany(collectionName, documents);
    }
    public static void insertMany(String collectionName, List<String> documents, String options) {
        mongoDBPro.insertMany(collectionName, documents, options);
    }
    public static long deleteOne(String collectionName, String filter) {
        return mongoDBPro.deleteOne(collectionName, filter);
    }
    public static long deleteMany(String collectionName, String filter) {
        return mongoDBPro.deleteMany(collectionName, filter);
    }
    public static long replaceOne(String collectionName, String filter, String replacement) {
        return mongoDBPro.replaceOne(collectionName, filter, replacement);
    }
    public static long replaceOne(String collectionName, String filter, String replacement, String updateOptions) {
        return mongoDBPro.replaceOne(collectionName, filter, replacement, updateOptions);
    }
    public static long updateOne(String collectionName, String filter, String update) {
        return mongoDBPro.replaceOne(collectionName, filter, update);
    }
    public static long updateOne(String collectionName, String filter, String update, String updateOptions) {
        return mongoDBPro.replaceOne(collectionName, filter, update, updateOptions);
    }
    public static long updateMany(String collectionName, String filter, String update) {
        return mongoDBPro.updateMany(collectionName, filter, update);
    }
    public static long updateMany(String collectionName, String filter, String update, String updateOptions) {
        return mongoDBPro.updateMany(collectionName, filter, update, updateOptions);
    }
    public static String findOneAndDelete(String collectionName, String filter) {
        return mongoDBPro.findOneAndDelete(collectionName, filter);
    }
    public static String findOneAndDelete(String collectionName, String filter, String options) {
        return mongoDBPro.findOneAndDelete(collectionName, filter, options);
    }
    public static String findOneAndReplace(String collectionName, String filter, String replacement) {
        return mongoDBPro.findOneAndReplace(collectionName, filter, replacement);
    }
    public static String findOneAndReplace(String collectionName, String filter, String replacement, String options) {
        return mongoDBPro.findOneAndReplace(collectionName, filter, replacement, options);
    }
    public static String findOneAndUpdate(String collectionName, String filter, String update, String options) {
        return mongoDBPro.findOneAndUpdate(collectionName, filter, update, options);
    }
    public static String findOneAndUpdate(String collectionName, String filter, String update) {
        return mongoDBPro.findOneAndUpdate(collectionName, filter, update);
    }
    public static void drop(String collectionName) {
        mongoDBPro.drop(collectionName);
    }
    public static String createIndex(String collectionName, String keys) {
        return mongoDBPro.createIndex(collectionName, keys);
    }
    public static String createIndex(String collectionName, String keys, String indexOptions) {
        return mongoDBPro.createIndex(collectionName, keys, indexOptions);
    }
    public static List<String> listIndexes(String collectionName) {
        return mongoDBPro.listIndexes(collectionName);
    }
    public static void dropIndex(String collectionName, String indexName) {
        mongoDBPro.dropIndex(collectionName, indexName);
    }
    public static void dropIndexes(String collectionName) {
        mongoDBPro.dropIndexes(collectionName);
    }
    public static void renameCollection(String collectionName, String newCollectionName) {
        mongoDBPro.renameCollection(collectionName, newCollectionName);
    }
    public static void renameCollection(String collectionName, String newCollectionName, String renameCollectionOptions) {
        mongoDBPro.renameCollection(collectionName, newCollectionName, renameCollectionOptions);
    }
    public static MongoCollection<Document> getCollection(String collectionName) {
        return mongoDBPro.getCollection(collectionName);
    }
    public static List<String> listCollectionNames(){
        return mongoDBPro.listCollectionNames();
    }
}

+ 0 - 65
src/main/java/com/yihu/hos/common/mongo/MongoDBConfig.java

@ -1,65 +0,0 @@
package com.yihu.hos.common.mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
/**
 * @created Airhead 2016/2/17.
 */
public class MongoDBConfig {
    String name;
    String uri;
    String defaultDatabaseName;
    static MongoClient mongoClient;
    MongoClientOptions mongoClientOptions;      //暂未使用,Mongo默认配置
    MongoDatabase mongoDatabase;
    public MongoDBConfig(String uri) {
        this.name = MongoDBKit.MAIN_CONFIG_NAME;
        this.uri = uri;
        this.defaultDatabaseName = MongoDBKit.DEFAULT_DB_NAME;
    }
    public MongoDBConfig(String name, String uri) {
        this.name = name;
        this.uri = uri;
        this.defaultDatabaseName = MongoDBKit.DEFAULT_DB_NAME;
    }
    public MongoDBConfig(String name, String uri, String databaseName) {
        this.name = name;
        this.uri = uri;
        this.defaultDatabaseName = databaseName;
    }
    public String getName() {
        return name;
    }
    public MongoDatabase getDatabase(String databaseName) {
        if (mongoClient == null) {
            MongoClientURI mongoClientURI = new MongoClientURI(uri);
            mongoClient = new MongoClient(mongoClientURI);
        }
        if (mongoDatabase != null) {
            if (mongoDatabase.getName().equals(databaseName)) {
                return mongoDatabase;
            }
        }
        mongoDatabase = mongoClient.getDatabase(databaseName);
        return mongoDatabase;
    }
    public MongoDatabase getDatabase() {
        if (mongoDatabase != null) {
            return mongoDatabase;
        }
        return getDatabase(defaultDatabaseName);
    }
}

+ 0 - 57
src/main/java/com/yihu/hos/common/mongo/MongoDBKit.java

@ -1,57 +0,0 @@
package com.yihu.hos.common.mongo;
import java.util.HashMap;
import java.util.Map;
/**
 * @created Airhead 2016/2/17.
 */
public class MongoDBKit {
    public static final String MAIN_CONFIG_NAME = "main";
    public static final String DEFAULT_DB_NAME = "test";
    static MongoDBConfig config = null;
    private static Map<String, MongoDBConfig> configNameToConfig = new HashMap<>();
    public static void start() {
        MongoDB.init();
    }
    public static MongoDBConfig getConfig() {
        return config;
    }
    public static MongoDBConfig getConfig(String configName) {
        return configNameToConfig.get(configName);
    }
    /**
     * Add Config object
     *
     * @param config the Config contains Mongodb uri and MongoClientOptions etc.
     */
    public static void addConfig(MongoDBConfig config) {
        if (config == null) {
            throw new IllegalArgumentException("Config can not be null");
        }
        if (configNameToConfig.containsKey(config.getName())) {
            throw new IllegalArgumentException("Config already exists: " + config.getName());
        }
        configNameToConfig.put(config.getName(), config);
        /**
         * Replace the main config if current config name is MAIN_CONFIG_NAME
         */
        if (MAIN_CONFIG_NAME.equals(config.getName())) {
            MongoDBKit.config = config;
        }
        /**
         * The configName may not be MAIN_CONFIG_NAME,
         * the main config have to set the first comming Config if it is null
         */
        if (MongoDBKit.config == null) {
            MongoDBKit.config = config;
        }
    }
}

+ 0 - 92
src/main/java/com/yihu/hos/common/mongo/MongoDBOperator.java

@ -1,92 +0,0 @@
package com.yihu.hos.common.mongo;
/**
 * Query Selectors
 * $eq	Matches values that are equal to a specified value.
 * $gt	Matches values that are greater than a specified value.
 * $gte	Matches values that are greater than or equal to a specified value.
 * $lt	Matches values that are less than a specified value.
 * $lte	Matches values that are less than or equal to a specified value.
 * $ne	Matches all values that are not equal to a specified value.
 * $in	Matches any of the values specified in an array.
 * $nin	Matches none of the values specified in an array.
 *
 * Logical
 * $or	Joins query clauses with a logical OR returns all documents that match the conditions of either clause.
 * $and	Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
 * $not	Inverts the effect of a query expression and returns documents that do not match the query expression.
 * $nor	Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
 *
 * Element
 * $exists	Matches documents that have the specified field.
 * $type	Selects documents if a field is of the specified type.
 *
 * Evaluation
 * $mod	Performs a modulo operation on the value of a field and selects documents with a specified result.
 * $regex	Selects documents where values match a specified regular expression.
 * $text	Performs text search.
 * $where	Matches documents that satisfy a JavaScript expression.
 *
 * Geospatial
 * $geoWithin	Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support $geoWithin.
 * $geoIntersects	Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index supports $geoIntersects.
 * $near	Returns geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphere and 2d indexes support $near.
 * $nearSphere	Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The 2dsphere and 2d indexes support $nearSphere.
 *
 * Array
 * $all	Matches arrays that contain all elements specified in the query.
 * $elemMatch	Selects documents if element in the array field matches all the specified $elemMatch conditions.
 * $size	Selects documents if the array field is a specified size.
 *
 * Bitwise
 * $bitsAllSet	Matches numeric or binary values in which a set of bit positions all have a value of 1.
 * $bitsAnySet	Matches numeric or binary values in which any bit from a set of bit positions has a value of 1.
 * $bitsAllClear	Matches numeric or binary values in which a set of bit positions all have a value of 0.
 * $bitsAnyClear	Matches numeric or binary values in which any bit from a set of bit positions has a value of 0.
 *
 * Comments
 * $comment	Adds a comment to a query predicate.
 *
 * Projection Operators
 * $	Projects the first element in an array that matches the query condition.
 * $elemMatch	Projects the first element in an array that matches the specified $elemMatch condition.
 * $meta	Projects the document’s score assigned during $text operation.
 * $slice	Limits the number of elements projected from an array. Supports skip and limit slices.
 *
 * Update Operators
 * $inc	Increments the value of the field by the specified amount.
 * $mul	Multiplies the value of the field by the specified amount.
 * $rename	Renames a field.
 * $setOnInsert	Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents.
 * $set	Sets the value of a field in a document.
 * $unset	Removes the specified field from a document.
 * $min	Only updates the field if the specified value is less than the existing field value.
 * $max	Only updates the field if the specified value is greater than the existing field value.
 * $currentDate	Sets the value of a field to current date, either as a Date or a Timestamp.
 *
 * Array
 * $	Acts as a placeholder to update the first element that matches the query condition in an update.
 * $addToSet	Adds elements to an array only if they do not already exist in the set.
 * $pop	Removes the first or last item of an array.
 * $pullAll	Removes all matching values from an array.
 * $pull	Removes all array elements that match a specified query.
 * $pushAll	Deprecated. Adds several items to an array.
 * $push	Adds an item to an array.
 *
 * Modifiers
 * $each	Modifies the $push and $addToSet operators to append multiple items for array updates.
 * $slice	Modifies the $push operator to limit the size of updated arrays.
 * $sort	Modifies the $push operator to reorder documents stored in an array.
 * $position	Modifies the $push operator to specify the position in the array to add elements.
 *
 * Bitwise
 * $bit	Performs bitwise AND, OR, and XOR updates of integer values.
 *
 * Isolation
 * $isolated	Modifies the behavior of a write operation to increase the isolation of the operation.
 * @created Airhead 2016/2/17.
 */
public class MongoDBOperator {
}

+ 0 - 566
src/main/java/com/yihu/hos/common/mongo/MongoDBPro.java

@ -1,566 +0,0 @@
package com.yihu.hos.common.mongo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.MongoNamespace;
import com.mongodb.client.*;
import com.mongodb.client.model.*;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * MongoDBPro. Professional database CURD and Manager tool.
 *
 * @created Airhead 2016/2/17.
 */
public class MongoDBPro implements IMongoDBRunner, IMongoDBAdminer {
    private static final Map<String, MongoDBPro> map = new HashMap<String, MongoDBPro>();
    private final MongoDBConfig config;
    public MongoDBPro() {
        if (MongoDBKit.config == null) {
            throw new RuntimeException("The main config is null, initialize MonogDBKit first");
        }
        this.config = MongoDBKit.config;
    }
    public MongoDBPro(String configName) {
        this.config = MongoDBKit.getConfig(configName);
        if (this.config == null) {
            throw new IllegalArgumentException("Config not found by configName: " + configName);
        }
    }
    public static MongoDBPro use() {
        return use(MongoDBKit.config.name);
    }
    public static MongoDBPro use(String configName) {
        MongoDBPro result = map.get(configName);
        if (result == null) {
            result = new MongoDBPro(configName);
            map.put(configName, result);
        }
        return result;
    }
    public MongoDBPro db(String databaseName) {
        config.getDatabase(databaseName);
        return this;
    }
    @Override
    public long count(String collectionName) {
        return count(collectionName, null);
    }
    @Override
    public long count(String collectionName, String filter) {
        return count(collectionName, filter, null);
    }
    /**
     * @param collectionName
     * @param filter         the query filter
     * @param options        the options describing the count
     *                       <p>
     *                       {
     *                       limit: <integer>,
     *                       skip: <integer>,
     *                       hint: <hint>
     *                       }
     * @return
     */
    @Override
    public long count(String collectionName, String filter, String options) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = new Document();
        if (filter != null) {
            filterDocument = Document.parse(filter);
        }
        CountOptions countOptions = new CountOptions();
        if (options != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readValue(options, JsonNode.class);
                String hintString = rootNode.path("hint").toString();
                if (!StringUtils.isEmpty(hintString)) {
                    Document hint = Document.parse(hintString);
                    countOptions.hint(hint);
                } else {
                    countOptions.hint(new Document());
                }
                countOptions.limit(rootNode.path("limit").asInt());
                countOptions.skip(rootNode.path("skip").asInt());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return collection.count(filterDocument, countOptions);
    }
    @Override
    public List<String> find(String collectionName) {
        return find(collectionName, null);
    }
    @Override
    public List<String> find(String collectionName, String filter) {
        return find(collectionName, filter, null);
    }
    @Override
    public List<String> find(String collectionName, String filter, String projection) {
        return find(collectionName, filter, projection, null);
    }
    @Override
    public List<String> find(String collectionName, String filter, String projection, String options) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = new Document();
        if (filter != null) {
            filterDocument = Document.parse(filter);
        }
        Document projectionDocument = new Document();
        if (projection != null) {
            projectionDocument = Document.parse(projection);
        }
        FindIterable<Document> documents = collection.find(filterDocument).projection(projectionDocument);
        List<String> list = new ArrayList<>();
        try (MongoCursor<Document> cursor = documents.iterator()) {
            while (cursor.hasNext()) {
                Document doc = cursor.next();
                list.add(doc.toJson());
            }
        }
        return list;
    }
//    @Override
//    public List<String> aggregate(String collectionName, List<? extends String> pipeline) {
//        return null;
//    }
//    @Override
//    public List<String> mapReduce(String collectionName, String mapFunction, String reduceFunction) {
//        return null;
//    }
    @Override
    public void insertOne(String collectionName, String document) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document doc = Document.parse(document);
        collection.insertOne(doc);
    }
    @Override
    public void insertMany(String collectionName, List<String> documents) {
        insertMany(collectionName, documents, null);
    }
    /**
     * @param collectionName
     * @param documents      the documents to insert
     * @param options        the options to apply to the operation
     *                       {
     *                       orderd:<orderd>
     *                       }
     */
    @Override
    public void insertMany(String collectionName, List<String> documents, String options) {
        MongoCollection<Document> collection = getCollection(collectionName);
        List<Document> list = new ArrayList<>();
        for (String document : documents) {
            Document doc = Document.parse(document);
            list.add(doc);
        }
        InsertManyOptions insertManyOptions = new InsertManyOptions();
        if (options != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readValue(options, JsonNode.class);
                insertManyOptions.ordered(rootNode.path("ordered").asBoolean());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        collection.insertMany(list, insertManyOptions);
    }
    @Override
    public long deleteOne(String collectionName, String filter) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = Document.parse(filter);
        DeleteResult deleteResult = collection.deleteOne(filterDocument);
        return deleteResult.getDeletedCount();
    }
    @Override
    public long deleteMany(String collectionName, String filter) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = Document.parse(filter);
        DeleteResult deleteResult = collection.deleteMany(filterDocument);
        return deleteResult.getDeletedCount();
    }
    @Override
    public long replaceOne(String collectionName, String filter, String replacement) {
        return replaceOne(collectionName, filter, replacement, null);
    }
    /**
     * @param collectionName
     * @param filter         the query filter to apply the the replace operation
     * @param replacement    the replacement document
     * @param updateOptions  the options to apply to the replace operation
     *                       {
     *                       upsert:<upsert>
     *                       }
     * @return
     */
    @Override
    public long replaceOne(String collectionName, String filter, String replacement, String updateOptions) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = Document.parse(filter);
        Document document = Document.parse(replacement);
        UpdateOptions options = new UpdateOptions();
        if (updateOptions != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readValue(updateOptions, JsonNode.class);
                options.upsert(rootNode.path("upsert").asBoolean());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        UpdateResult updateResult = collection.replaceOne(filterDocument, document, options);
        return updateResult.getModifiedCount();
    }
    @Override
    public long updateOne(String collectionName, String filter, String update) {
        return updateOne(collectionName, filter, update, null);
    }
    /**
     * @param collectionName
     * @param filter         a document describing the query filter, which may not be null.
     * @param update         a document describing the update, which may not be null. The update to apply must include only update operators.
     * @param updateOptions  the options to apply to the update operation
     *                       {
     *                       upsert:<upsert>
     *                       }
     * @return
     */
    @Override
    public long updateOne(String collectionName, String filter, String update, String updateOptions) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = Document.parse(filter);
        Document document = Document.parse(update);
        UpdateOptions options = new UpdateOptions();
        if (updateOptions != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readValue(updateOptions, JsonNode.class);
                options.upsert(rootNode.path("upsert").asBoolean());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        UpdateResult updateResult = collection.updateOne(filterDocument, document, options);
        return updateResult.getModifiedCount();
    }
    @Override
    public long updateMany(String collectionName, String filter, String update) {
        return updateMany(collectionName, filter, update, null);
    }
    /**
     * @param collectionName
     * @param filter         a document describing the query filter, which may not be null.
     * @param update         a document describing the update, which may not be null. The update to apply must include only update operators.
     * @param updateOptions  the options to apply to the update operation
     *                       {
     *                       upsert:<upsert>
     *                       }
     * @return
     */
    @Override
    public long updateMany(String collectionName, String filter, String update, String updateOptions) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = Document.parse(filter);
        Document document = Document.parse(update);
        UpdateOptions options = new UpdateOptions();
        if (updateOptions != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readValue(updateOptions, JsonNode.class);
                options.upsert(rootNode.path("upsert").asBoolean());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        UpdateResult updateResult = collection.updateMany(filterDocument, document, options);
        return updateResult.getModifiedCount();
    }
    @Override
    public String findOneAndDelete(String collectionName, String filter) {
        return findOneAndDelete(collectionName, filter, null);
    }
    /**
     * @param collectionName
     * @param filter         the query filter to find the document with
     * @param options        the options to apply to the operation
     *                       {
     *                       projection:<document>,
     *                       sort:<document>
     *                       }
     * @return
     */
    @Override
    public String findOneAndDelete(String collectionName, String filter, String options) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = Document.parse(filter);
        FindOneAndDeleteOptions findOneAndDeleteOptions = new FindOneAndDeleteOptions();
        if (options != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readValue(options, JsonNode.class);
                String projection = rootNode.path("projection").toString();
                Document projectionDoc = new Document();
                if (!StringUtils.isEmpty(projection)) {
                    Document.parse(projection);
                }
                String sort = rootNode.path("sort").toString();
                Document sortDoc = new Document();
                if (!StringUtils.isEmpty(sort)) {
                    Document.parse(sort);
                }
                findOneAndDeleteOptions.projection(projectionDoc);
                findOneAndDeleteOptions.sort(sortDoc);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Document document = collection.findOneAndDelete(filterDocument, findOneAndDeleteOptions);
        return document == null ? "{}" : document.toJson();
    }
    @Override
    public String findOneAndReplace(String collectionName, String filter, String replacement) {
        return findOneAndReplace(collectionName, filter, replacement, null);
    }
    /**
     * @param collectionName
     * @param filter         the query filter to apply the the replace operation
     * @param replacement    the replacement document
     * @param options        the options to apply to the operation
     *                       {
     *                       projection:<document>,
     *                       sort:<document>,
     *                       upsert:<upsert>
     *                       }
     * @return
     */
    @Override
    public String findOneAndReplace(String collectionName, String filter, String replacement, String options) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = Document.parse(filter);
        Document replacementDocument = Document.parse(replacement);
        FindOneAndReplaceOptions findOneAndReplaceOptions = new FindOneAndReplaceOptions();
        if (options != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readValue(options, JsonNode.class);
                String projection = rootNode.path("projection").toString();
                Document projectionDoc = new Document();
                if (!StringUtils.isEmpty(projection)) {
                    Document.parse(projection);
                }
                String sort = rootNode.path("sort").toString();
                Document sortDoc = new Document();
                if (!StringUtils.isEmpty(sort)) {
                    Document.parse(sort);
                }
                findOneAndReplaceOptions.projection(projectionDoc);
                findOneAndReplaceOptions.sort(sortDoc);
                findOneAndReplaceOptions.upsert(rootNode.path("upsert").asBoolean());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Document document = collection.findOneAndReplace(filterDocument, replacementDocument, findOneAndReplaceOptions);
        return document == null ? "{}" : document.toJson();
    }
    @Override
    public String findOneAndUpdate(String collectionName, String filter, String update) {
        return findOneAndUpdate(collectionName, filter, update, null);
    }
    /**
     * @param collectionName
     * @param filter         a document describing the query filter, which may not be null.
     * @param update         a document describing the update, which may not be null. The update to apply must include only update operators.
     * @param options        the options to apply to the operation
     *                       {
     *                       projection:<document>,
     *                       sort:<document>,
     *                       upsert:<upsert>
     *                       }
     * @return
     */
    @Override
    public String findOneAndUpdate(String collectionName, String filter, String update, String options) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document filterDocument = Document.parse(filter);
        Document updateDocument = Document.parse(update);
        FindOneAndUpdateOptions findOneAndUpdateOptions = new FindOneAndUpdateOptions();
        if (options != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode rootNode = mapper.readValue(options, JsonNode.class);
                String projection = rootNode.path("projection").asText();
                Document projectionDoc = Document.parse(projection);
                String sort = rootNode.path("sort").asText();
                Document sortDoc = Document.parse(sort);
                findOneAndUpdateOptions.projection(projectionDoc);
                findOneAndUpdateOptions.sort(sortDoc);
                findOneAndUpdateOptions.upsert(rootNode.path("upsert").asBoolean());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Document document = collection.findOneAndUpdate(filterDocument, updateDocument, findOneAndUpdateOptions);
        return document.toJson();
    }
    @Override
    public void drop(String collectionName) {
        getCollection(collectionName).drop();
    }
    @Override
    public String createIndex(String collectionName, String keys) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document keysDocument = Document.parse(keys);
        return collection.createIndex(keysDocument);
    }
    @Override
    public String createIndex(String collectionName, String keys, String indexOptions) {
        MongoCollection<Document> collection = getCollection(collectionName);
        Document keysDocument = Document.parse(keys);
        IndexOptions options = new IndexOptions();
//TODO:解析indexOptions
//        try {
//            ObjectMapper mapper = new ObjectMapper();
//            JsonNode rootNode = mapper.readValue(indexOptions, JsonNode.class);
//
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return collection.createIndex(keysDocument, options);
    }
    @Override
    public List<String> listIndexes(String collectionName) {
        MongoCollection<Document> collection = getCollection(collectionName);
        ListIndexesIterable<Document> indexes = collection.listIndexes();
        List<String> list = new ArrayList<>();
        try (MongoCursor<Document> cursor = indexes.iterator()) {
            while (cursor.hasNext()) {
                Document doc = cursor.next();
                list.add(doc.toJson());
            }
        }
        return list;
    }
    @Override
    public void dropIndex(String collectionName, String indexName) {
        getCollection(collectionName).dropIndex(indexName);
    }
    @Override
    public void dropIndexes(String collectionName) {
        getCollection(collectionName).dropIndexes();
    }
    @Override
    public void renameCollection(String collectionName, String newCollectionName) {
        MongoCollection<Document> collection = getCollection(collectionName);
        MongoNamespace namespace = collection.getNamespace();
        collection.renameCollection(new MongoNamespace(namespace.getDatabaseName(), newCollectionName));
    }
    @Override
    public void renameCollection(String collectionName, String newCollectionName, String renameCollectionOptions) {
        MongoCollection<Document> collection = getCollection(collectionName);
        MongoNamespace namespace = collection.getNamespace();
        RenameCollectionOptions options = new RenameCollectionOptions();
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readValue(renameCollectionOptions, JsonNode.class);
            options.dropTarget(rootNode.path("dropTarget").asBoolean());
        } catch (IOException e) {
            e.printStackTrace();
        }
        collection.renameCollection(new MongoNamespace(namespace.getDatabaseName(), newCollectionName), options);
    }
    public MongoCollection<Document> getCollection(String collectionName) {
        MongoDatabase database = config.getDatabase();
        return database.getCollection(collectionName);
    }
    public List<String> listCollectionNames() {
        MongoDatabase database = config.getDatabase();
        MongoIterable<String> listCollectionNames = database.listCollectionNames();
        List<String> list = new ArrayList<>();
        for (String collectionName : listCollectionNames) {
            list.add(collectionName);
        }
        return list;
    }
}