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.runtime.mongodb;
022
023import java.util.stream.StreamSupport;
024
025import org.apache.commons.lang3.StringUtils;
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028
029import com.mongodb.MongoClient;
030import com.mongodb.MongoClientOptions;
031import com.mongodb.MongoClientURI;
032import com.mongodb.ServerAddress;
033import com.mongodb.client.MongoDatabase;
034import com.mongodb.client.MongoIterable;
035
036/**
037 * Helper for connection to the MongoDB server
038 *
039 * @since 9.1
040 */
041public class MongoDBConnectionHelper {
042
043    private static final Log log = LogFactory.getLog(MongoDBConnectionHelper.class);
044
045    private static final String DB_DEFAULT = "nuxeo";
046
047    private static final int MONGODB_OPTION_CONNECTION_TIMEOUT_MS = 30000;
048
049    private static final int MONGODB_OPTION_SOCKET_TIMEOUT_MS = 60000;
050
051    private MongoDBConnectionHelper() {
052        // Empty
053    }
054
055    /**
056     * Initialize a connection to the MongoDB server
057     *
058     * @param server the server url
059     * @return the MongoDB client
060     */
061    public static MongoClient newMongoClient(String server) {
062        if (StringUtils.isBlank(server)) {
063            throw new RuntimeException("Missing <server> in MongoDB descriptor");
064        }
065        MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
066                  // can help to prevent firewall disconnecting inactive connection, option not available from URI
067                  .socketKeepAlive(true)
068                  // don't wait forever by default, can be overridden using URI options
069                  .connectTimeout(MONGODB_OPTION_CONNECTION_TIMEOUT_MS)
070                  .socketTimeout(MONGODB_OPTION_SOCKET_TIMEOUT_MS)
071                  .description("Nuxeo");
072        MongoClient client;
073        if (server.startsWith("mongodb://")) {
074            // allow mongodb:// URI syntax for the server, to pass everything in one string
075            client = new MongoClient(new MongoClientURI(server, optionsBuilder));
076        } else {
077            client = new MongoClient(new ServerAddress(server), optionsBuilder.build());
078        }
079        if (log.isDebugEnabled()) {
080            log.debug("MongoClient initialized with options: " + client.getMongoClientOptions().toString());
081        }
082        return client;
083    }
084
085    /**
086     * @return a database representing the specified database
087     */
088    public static MongoDatabase getDatabase(MongoClient mongoClient, String dbname) {
089        if (StringUtils.isBlank(dbname)) {
090            dbname = DB_DEFAULT;
091        }
092        return mongoClient.getDatabase(dbname);
093    }
094
095    /**
096     * Check if the collection exists and if it is not empty
097     *
098     * @param mongoDatabase the Mongo database
099     * @param collection the collection name
100     * @return true if the collection exists and not empty, false otherwise
101     */
102    public static boolean hasCollection(MongoDatabase mongoDatabase, String collection) {
103        MongoIterable<String> collections = mongoDatabase.listCollectionNames();
104        boolean found = StreamSupport.stream(collections.spliterator(), false).anyMatch(collection::equals);
105        return found && mongoDatabase.getCollection(collection).count() > 0;
106    }
107}