001/*
002 * (C) Copyright 2014-2017 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 *     Kevin Leturc
019 *     Funsho David
020 */
021package org.nuxeo.mongodb.core;
022
023import java.util.stream.StreamSupport;
024
025import org.apache.commons.lang.StringUtils;
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.bson.Document;
029import org.nuxeo.ecm.core.api.NuxeoException;
030
031import com.mongodb.MongoClient;
032import com.mongodb.MongoClientOptions;
033import com.mongodb.MongoClientURI;
034import com.mongodb.ServerAddress;
035import com.mongodb.client.MongoCollection;
036import com.mongodb.client.MongoDatabase;
037import com.mongodb.client.MongoIterable;
038
039/**
040 * Helper for connection to the MongoDB server
041 *
042 * @since 9.1
043 */
044public class MongoDBConnectionHelper {
045
046    private static final Log log = LogFactory.getLog(MongoDBConnectionHelper.class);
047
048    private static final String DB_DEFAULT = "nuxeo";
049
050    private static final int MONGODB_OPTION_CONNECTION_TIMEOUT_MS = 30000;
051
052    private static final int MONGODB_OPTION_SOCKET_TIMEOUT_MS = 60000;
053
054    private MongoDBConnectionHelper() {
055        // Empty
056    }
057
058    /**
059     * Initialize a connection to the MongoDB server
060     *
061     * @param server the server url
062     * @return the MongoDB client
063     */
064    public static MongoClient newMongoClient(String server) {
065        if (StringUtils.isBlank(server)) {
066            throw new NuxeoException("Missing <server> in MongoDB repository descriptor");
067        }
068        MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
069                  // Can help to prevent firewall disconnects
070                  // inactive connection, option not available from URI
071                  .socketKeepAlive(true)
072                  // don't wait for ever by default,
073                  // can be overridden using URI options
074                  .connectTimeout(MONGODB_OPTION_CONNECTION_TIMEOUT_MS)
075                  .socketTimeout(MONGODB_OPTION_SOCKET_TIMEOUT_MS)
076                  .description("Nuxeo");
077        MongoClient client;
078        if (server.startsWith("mongodb://")) {
079            // allow mongodb:// URI syntax for the server, to pass everything in one string
080            client = new MongoClient(new MongoClientURI(server, optionsBuilder));
081        } else {
082            client = new MongoClient(new ServerAddress(server), optionsBuilder.build());
083        }
084        if (log.isDebugEnabled()) {
085            log.debug("MongoClient initialized with options: " + client.getMongoClientOptions().toString());
086        }
087        return client;
088    }
089
090    /**
091     * @return a database representing the specified database
092     */
093    public static MongoDatabase getDatabase(MongoClient mongoClient, String dbname) {
094        if (StringUtils.isBlank(dbname)) {
095            dbname = DB_DEFAULT;
096        }
097        return mongoClient.getDatabase(dbname);
098    }
099
100    /**
101     * Retrieve a collection from the MongoDB server
102     */
103    public static MongoCollection<Document> getCollection(MongoClient mongoClient, String dbname, String collection) {
104        MongoDatabase db = getDatabase(mongoClient, dbname);
105        return db.getCollection(collection);
106    }
107
108    /**
109     * Check if the collection exists and if it is not empty
110     *
111     * @param mongoClient the Mongo client
112     * @param dbname the database name
113     * @param collection the collection name
114     * @return true if the collection exists and not empty, false otherwise
115     */
116    public static boolean hasCollection(MongoClient mongoClient, String dbname, String collection) {
117        MongoIterable<String> collections = getDatabase(mongoClient, dbname).listCollectionNames();
118        boolean found = StreamSupport.stream(collections.spliterator(), false).anyMatch(collection::equals);
119        return found && getCollection(mongoClient, dbname, collection).count() > 0;
120    }
121}