Example usage for com.mongodb Mongo getDatabaseNames

List of usage examples for com.mongodb Mongo getDatabaseNames

Introduction

In this page you can find the example usage for com.mongodb Mongo getDatabaseNames.

Prototype

@Deprecated
public List<String> getDatabaseNames() 

Source Link

Document

Gets a list of the names of all databases on the connected server.

Usage

From source file:com.arquivolivre.mongocom.management.CollectionManager.java

License:Apache License

protected CollectionManager(Mongo client, String dataBase) {
    this.client = client;
    if (dataBase != null && !dataBase.equals("")) {
        this.db = client.getDB(dataBase);
    } else {/*w w w  . j  a v  a 2s  .c  o  m*/
        this.db = client.getDB(client.getDatabaseNames().get(0));
    }
}

From source file:com.github.camellabs.iot.cloudlet.document.driver.DriverDocumentCloudlet.java

License:Apache License

@Bean
@ConditionalOnProperty(value = "camel.labs.iot.cloudlet.document.driver.mongodb.springbootconfig", matchIfMissing = true, havingValue = "false")
Mongo mongo() throws UnknownHostException {
    String mongodbKubernetesHost = System.getenv("MONGODB_SERVICE_HOST");
    String mongodbKubernetesPort = System.getenv("MONGODB_SERVICE_PORT");
    if (mongodbKubernetesHost != null && mongodbKubernetesPort != null) {
        LOG.info("Kubernetes MongoDB service detected - {}:{}. Connecting...", mongodbKubernetesHost,
                mongodbKubernetesPort);//w ww  .j a  va 2 s .  c  o m
        return new MongoClient(mongodbKubernetesHost, parseInt(mongodbKubernetesPort));
    } else {
        LOG.info("Can't find MongoDB Kubernetes service.");
        LOG.debug("Environment variables: {}", getenv());
    }

    try {
        LOG.info("Attempting to connect to the MongoDB server at mongodb:27017.");
        Mongo mongo = new MongoClient("mongodb");
        mongo.getDatabaseNames();
        return mongo;
    } catch (MongoTimeoutException e) {
        LOG.info("Can't connect to the MongoDB server at mongodb:27017. Falling back to the localhost:27017.");
        return new MongoClient();
    }
}

From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {/*ww w .j  av a  2 s . c  om*/
        getLog().info("Skipping mongodb: mongodb.skip==true");
        return;
    }
    if (installation == null) {
        getLog().info("Using mongod from PATH");
    } else {
        getLog().info("Using mongod installed in " + installation);
    }
    getLog().info("Using database root of " + databaseRoot);
    final Logger mongoLogger = Logger.getLogger("com.mongodb");
    Level mongoLevel = mongoLogger.getLevel();
    try {
        mongoLogger.setLevel(Level.SEVERE);
        MongoOptions opts = new MongoOptions();
        opts.autoConnectRetry = false;
        opts.connectionsPerHost = 1;
        opts.connectTimeout = 50;
        opts.socketTimeout = 50;
        Mongo instance;
        try {
            instance = new Mongo(new ServerAddress("localhost", port), opts);
            List<String> databaseNames = instance.getDatabaseNames();
            throw new MojoExecutionException("Port " + port
                    + " is already running a MongoDb instance with the following databases " + databaseNames);
        } catch (MongoException.Network e) {
            // fine... no instance running
        } catch (MongoException e) {
            throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance");
        } catch (UnknownHostException e) {
            // ignore... localhost is always known!
        }
    } finally {
        mongoLogger.setLevel(mongoLevel);
    }

    CommandLine commandLine = null;
    if (installation != null && installation.isDirectory()) {
        File bin = new File(installation, "bin");
        File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
        if (exe.isFile()) {
            commandLine = new CommandLine(exe);
        } else {
            throw new MojoExecutionException("Could not find mongo executables in specified installation: "
                    + installation + " expected to find " + exe + " but it does not exist.");
        }
    }
    if (commandLine == null) {
        commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
    }
    if (databaseRoot.isFile()) {
        throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory");
    }
    if (databaseRoot.isDirectory() && cleanDatabaseRoot) {
        getLog().info("Cleaning database root directory: " + databaseRoot);
        try {
            FileUtils.deleteDirectory(databaseRoot);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e);
        }
    }
    if (!databaseRoot.isDirectory()) {
        getLog().debug("Creating database root directory: " + databaseRoot);
        if (!databaseRoot.mkdirs()) {
            throw new MojoExecutionException("Could not create database root directory " + databaseRoot);
        }
    }

    if (!verbose) {
        commandLine.addArgument("--quiet");
    }

    commandLine.addArgument("--logpath");
    commandLine.addArgument(logPath.getAbsolutePath());
    if (logAppend) {
        commandLine.addArgument("--logappend");
    }

    commandLine.addArgument(auth ? "--auth" : "--noauth");

    commandLine.addArgument("--port");
    try {
        // this is a hack to force mongo to use a project property
        // that we are randomly setting at run-time (reserve-network-port)
        port = Integer.parseInt(project.getProperties().getProperty("mongodb.port"));
    } catch (NumberFormatException e) {
        // no or bad project property
    }
    commandLine.addArgument(Integer.toString(port));

    commandLine.addArgument("--dbpath");
    commandLine.addArgument(databaseRoot.getAbsolutePath());

    if (additionalArguments != null) {
        for (String aa : additionalArguments) {
            commandLine.addArgument(aa);
        }
    }

    Executor exec = new DefaultExecutor();
    DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler();
    exec.setWorkingDirectory(databaseRoot);
    ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer());
    exec.setProcessDestroyer(processObserver);

    LogOutputStream stdout = new MavenLogOutputStream(getLog());
    LogOutputStream stderr = new MavenLogOutputStream(getLog());

    getLog().info("Executing command line: " + commandLine);
    exec.setStreamHandler(new PumpStreamHandler(stdout, stderr));
    try {
        exec.execute(commandLine, execHandler);
        getLog().info("Waiting for MongoDB to start...");
        long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120);
        mongoLevel = mongoLogger.getLevel();
        try {
            mongoLogger.setLevel(Level.SEVERE);
            while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) {
                MongoOptions opts = new MongoOptions();
                opts.autoConnectRetry = false;
                opts.connectionsPerHost = 1;
                opts.connectTimeout = 250;
                opts.socketTimeout = 250;
                Mongo instance;
                try {
                    instance = new Mongo(new ServerAddress("localhost", port), opts);
                    List<String> databaseNames = instance.getDatabaseNames();
                    getLog().info("MongoDb started.");
                    getLog().info("Databases: " + databaseNames);
                } catch (MongoException.Network e) {
                    // ignore, wait and try again
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e1) {
                        // ignore
                    }
                    continue;
                } catch (MongoException e) {
                    getLog().info("MongoDb started.");
                    getLog().info("Unable to list databases due to " + e.getMessage());
                }
                break;
            }
        } finally {
            mongoLogger.setLevel(mongoLevel);
        }
        if (execHandler.hasResult()) {
            ExecuteException exception = execHandler.getException();
            if (exception != null) {
                throw new MojoFailureException(exception.getMessage(), exception);
            }
            throw new MojoFailureException(
                    "Command " + commandLine + " exited with exit code " + execHandler.getExitValue());
        }
        Map pluginContext = session.getPluginContext(getPluginDescriptor(), project);
        pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:com.hangum.tadpole.mongodb.core.test.ConAndAuthentication.java

License:Open Source License

/**
 * mongo db ./* ww  w  .jav a 2 s .  c  om*/
 * 
 * @return
 */
public Mongo connection(String uri, int port) {
    Mongo m = null;
    try {
        m = new Mongo(uri, port);
        List<String> listDB = m.getDatabaseNames();
        for (String dbName : listDB) {
            System.out.println(dbName);
        }

        // authentication(optional)
        // boolean auth = db.authenticate(myUserName, myPassword);

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    }

    return m;
}

From source file:com.mebigfatguy.mongobrowser.dialogs.MongoControlPanel.java

License:Apache License

@Override
public void init() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Mongo db = context.getServer();
            List<String> databases = db.getDatabaseNames();
            DefaultComboBoxModel model = (DefaultComboBoxModel) dbComboBox.getModel();
            for (String database : databases) {
                model.addElement(database);
            }/*  w w  w.  j a  v  a2 s . c o  m*/
            model.addElement(new Object() {
                @Override
                public String toString() {
                    return "New Database...";
                }
            });
            dbComboBox.setEnabled(true);
            context.setSelectedNode(null);
        }
    });

}

From source file:doge.Application.java

License:Apache License

@Bean
public HealthIndicator<Object> mongoHealthIndicator(Mongo mongo) {
    return () -> {
        try {/*from ww w. j av  a  2s. co m*/
            mongo.getDatabaseNames();
            return "ok";
        } catch (MongoException ex) {
            return "error";
        }
    };
}

From source file:es.devcircus.mongodb_examples.hello_world.Main.java

License:Open Source License

/**
 * Mtodo en el que se muestran algunas funciones de administracin.
 *///  w w w.jav  a 2  s  .  c om
public static void quickTourOfTheAdministrativeFunctions() {
    try {
        System.out.println();
        System.out.println("---------------------------------------------------------------");
        System.out.println(" Quick Tour of the Administrative Functions                    ");
        System.out.println("---------------------------------------------------------------");
        System.out.println();

        /*Quick Tour of the Administrative Functions
         Getting A List of Databases
         You can get a list of the available databases:*/

        Mongo m = new Mongo();

        for (String s : m.getDatabaseNames()) {
            System.out.println(" - " + s);
        }

        /*Dropping A Database
         You can drop a database by name using the Mongo object:*/

        m.dropDatabase(DB_NAME);
    } catch (UnknownHostException | MongoException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:examples.QuickTourAdmin.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server 
    Mongo m = new Mongo();

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // get db names
    for (String s : m.getDatabaseNames()) {
        System.out.println(s);/*from  w w w  .  j  a  va2  s  .c om*/
    }

    // get a db
    DB db = m.getDB("com_mongodb_MongoAdmin");

    // do an insert so that the db will really be created.  Calling getDB() doesn't really take any
    // action with the server 
    db.getCollection("testcollection").insert(new BasicDBObject("i", 1));
    for (String s : m.getDatabaseNames()) {
        System.out.println(s);
    }

    // drop a database
    m.dropDatabase("com_mongodb_MongoAdmin");

    for (String s : m.getDatabaseNames()) {
        System.out.println(s);
    }
}

From source file:mongodb.Movies_import.java

public static void main(String[] args)
        throws UnknownHostException, MongoException, FileNotFoundException, IOException {

    Mongo mongo = new Mongo(); //creating an instance of mongodb called mongo

    //using mongo object to get the database name
    List<String> databases = mongo.getDatabaseNames();
    for (String string : databases) {
        System.out.println(string);
    }//from  w  w w. java 2  s .  c  o  m

    //assigning db variable to mongoDB directory 'db' created in the terminal
    DB db = mongo.getDB("db");

    DBCollection Collection = db.getCollection("movies_import");

    FileReader filereader = null;
    BufferedReader bufferreader = null;

    try {
        filereader = new FileReader("/Users/cheryldsouza/Documents/UPITT/Data Analytics/ml-10M100K/movies.dat");
        bufferreader = new BufferedReader(filereader);
        System.out.println("Mongodb Files");

        String read = bufferreader.readLine();

        while (read != null) {
            System.out.println(read);

            String[] reads = read.split("::");

            BasicDBObject object = new BasicDBObject();

            object.append("MovieID", reads[0]);

            object.append("Title", reads[1]);

            object.append("Genres", reads[2]);

            Collection.insert(object);
            read = bufferreader.readLine();
        }

    } catch (FileNotFoundException e) {
        System.out.println("Documents not found");
        System.exit(-1);
    }

    catch (IOException e) {
        System.out.println("FAILED");
        System.exit(-1);
    }
}

From source file:mongodb.tagsimport.java

public static void main(String[] args) throws UnknownHostException, MongoException {

    Mongo mongo = new Mongo();

    List<String> databases = mongo.getDatabaseNames();
    for (String str : databases) {
        System.out.println(str);//  ww  w .  ja  v a 2 s. c om
    }

    DB db = mongo.getDB("db");

    DBCollection dbCollection = db.getCollection("tags_import");

    FileReader filereader = null;
    BufferedReader bufferreader = null;

    try {
        filereader = new FileReader("/Users/cheryldsouza/Documents/UPITT/Data Analytics/ml-10M100K/tags.dat");
        bufferreader = new BufferedReader(filereader);
        System.out.println("Mongodb Tags File");

        String read = bufferreader.readLine();

        while (read != null) {
            System.out.println(read);

            String[] reads = read.split("::");

            //inserting keys

            BasicDBObject object = new BasicDBObject();

            //UserID::MovieID::Tag::Timestamp

            object.append("UserID", reads[0]);

            object.append("MovieID", reads[1]);

            object.append("Tag", reads[2]);

            object.append("Timestamp", reads[3]);

            dbCollection.insert(object);
            read = bufferreader.readLine();
        }

    } catch (FileNotFoundException e) {
        System.out.println("No documents found. Please try again");
        System.exit(-1);
    }

    catch (IOException e) {
        System.out.println("FAILED");
        System.exit(-1);
    }
}