001/* 002 * (C) Copyright 2017 Nuxeo (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 * dmetzler 018 */ 019package org.nuxeo.ecm.core.storage.mongodb; 020 021import java.util.concurrent.TimeUnit; 022 023import org.bson.Document; 024import org.nuxeo.launcher.config.ConfigurationException; 025import org.nuxeo.launcher.config.ConfigurationGenerator; 026import org.nuxeo.launcher.config.backingservices.BackingChecker; 027 028import com.mongodb.MongoClient; 029import com.mongodb.MongoClientOptions; 030import com.mongodb.MongoClientURI; 031import com.mongodb.MongoTimeoutException; 032import com.mongodb.ServerAddress; 033 034public class MongoDBChecker implements BackingChecker { 035 036 public static final String TEMPLATE_NAME = "mongodb"; 037 038 @Override 039 public boolean accepts(ConfigurationGenerator cg) { 040 return cg.getTemplateList().contains(TEMPLATE_NAME); 041 } 042 043 @Override 044 public void check(ConfigurationGenerator cg) throws ConfigurationException { 045 MongoClient ret = null; 046 String serverName = cg.getUserConfig().getProperty(ConfigurationGenerator.PARAM_MONGODB_SERVER); 047 String dbName = cg.getUserConfig().getProperty(ConfigurationGenerator.PARAM_MONGODB_NAME); 048 049 MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder() 050 .serverSelectionTimeout( 051 (int) TimeUnit.SECONDS.toMillis(1)) 052 .description("Nuxeo DB Check"); 053 if (serverName.startsWith("mongodb://")) { 054 // allow mongodb:// URI syntax for the server, to pass everything in one string 055 ret = new MongoClient(new MongoClientURI(serverName, optionsBuilder)); 056 } else { 057 ret = new MongoClient(new ServerAddress(serverName), optionsBuilder.build()); 058 } 059 try { 060 Document ping = new Document("ping", "1"); 061 ret.getDatabase(dbName).runCommand(ping); 062 } catch (MongoTimeoutException e) { 063 throw new ConfigurationException( 064 String.format("Unable to connect to MongoDB at %s, please check your connection", serverName)); 065 } finally { 066 ret.close(); 067 } 068 } 069}