com.ovea.mongodb.EmbeddedMongoDBMain.java Source code

Java tutorial

Introduction

Here is the source code for com.ovea.mongodb.EmbeddedMongoDBMain.java

Source

/**
 * Copyright (C) 2011 Ovea <dev@ovea.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ovea.mongodb;

import com.mongodb.DB;
import com.mongodb.Mongo;

import java.io.IOException;

/**
 * @author Mathieu Carbou (mathieu.carbou@gmail.com)
 */
final class EmbeddedMongoDBMain {
    public static void main(String[] args) throws InterruptedException, IOException {
        String path = System.getProperty("os.name").toLowerCase().contains("windows") ? "mongod.exe" : "mongod";

        EmbeddedMongoDB embeddedMongoDB = EmbeddedMongoDB.getOrCreate(path, "--nohttpinterface");
        // add users
        try {
            Mongo mongo = new Mongo("localhost", embeddedMongoDB.port());
            DB smt = mongo.getDB("smt");
            smt.addUser("smt", "ilovesmt".toCharArray());
            DB admin = mongo.getDB("admin");
            admin.addUser("admin", "admin".toCharArray());
            mongo.close();
        } catch (Exception e) {
        }
        System.out.println("terminate");
        // restart DB with auth option
        embeddedMongoDB.terminate();

        System.out.println("getOrCreate");
        embeddedMongoDB = EmbeddedMongoDB.getOrCreate(path, "--nohttpinterface", "--auth", "--dbpath",
                embeddedMongoDB.dbPath().getAbsolutePath());

        System.out.println("waitFor");
        System.out.println(embeddedMongoDB.port());
        System.out.println(embeddedMongoDB.pid());
        System.out.println(embeddedMongoDB.dbPath());

        System.in.read();

        embeddedMongoDB.terminate();
    }
}