Example usage for com.mongodb MongoClient getDB

List of usage examples for com.mongodb MongoClient getDB

Introduction

In this page you can find the example usage for com.mongodb MongoClient getDB.

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:com.effektif.mongo.MongoGridFSSupplier.java

License:Apache License

@Override
public Object supply(Brewery brewery) {
    MongoConfiguration mongoConfiguration = brewery.get(MongoConfiguration.class);
    MongoClient mongoClient = brewery.get(MongoClient.class);
    String filedatabaseName = mongoConfiguration.getFileDatabaseName();
    DB db = mongoClient.getDB(filedatabaseName);
    return new GridFS(db);
}

From source file:com.ejbmongoembeddedtomcat.service.MongoService.java

public MongoService(MongoClient mongo) {
    this.col = mongo.getDB("eshopper").getCollection("Customers");
}

From source file:com.eventshero.api.dao.impl.PMF.java

License:Apache License

public static DB getDB() {
    if (dbInstance == null) {
        MongoClient mongo;
        try {/*from  www  . j  a  v  a2s .  c o  m*/
            mongo = new MongoClient("localhost", 27017);

            //Get database. If the database doesnt exist, MongoDB will create it
            dbInstance = mongo.getDB("eventshero");
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return dbInstance;
}

From source file:com.foodtruckdata.mongodb.UsersInput.java

public UsersInput(String host, int port, String db, String userName, String passwd)
        throws UnknownHostException {
    MongoCredential credential = MongoCredential.createMongoCRCredential(userName, db, passwd.toCharArray());
    MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential));
    mongoDB = mongoClient.getDB(db);
}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

public void init() {
    if (args == null || args.length == 0) {
        throw new AssertionError("No arguments passed to the MongoDBTestDataProvider");
    }/*from  w w w .  j  av a 2s .c om*/

    if (args.length < 3) {
        throw new AssertionError("The arguments, namely mongodb-host, mongodb-port, mongodb-database are "
                + " mandatory for MongoDBTestDataProvider");
    }

    Assert.assertNotNull("mongodb-host cannot be empty", args[0]);
    Assert.assertNotNull("mongodb-port cannot be empty", args[1]);
    Assert.assertNotNull("mongodb-database cannot be empty", args[2]);

    String host = args[0].trim();
    String port = args[1].trim();
    String dbName = args[2].trim();

    Assert.assertFalse("mongodb-host cannot be empty", host.isEmpty());
    Assert.assertFalse("mongodb-port cannot be empty", port.isEmpty());
    Assert.assertFalse("mongodb-database cannot be empty", dbName.isEmpty());

    String username = null, password = "";
    if (args.length > 3) {
        Assert.assertNotNull("mongodb-user cannot be empty", args[3]);
        Assert.assertFalse("mongodb-user cannot be empty", args[3].isEmpty());

        username = args[3].trim();
        if (args.length > 4 && args[4] != null)
            password = args[4].trim();
    }

    StringBuilder build = new StringBuilder();
    build.append("MongoDBTestDataSource configuration [\n");
    build.append(String.format("mongodb-host is %s\n", host));
    build.append(String.format("mongodb-port is %s\n", port));
    build.append(String.format("mongodb-database is %s\n", dbName));
    if (username != null) {
        build.append(String.format("mongodb-user is %s\n", username));
        build.append(String.format("mongodb-password is %s\n", password));
    }
    logger.info(build.toString());

    try {
        String[] hosts = host.split(",");
        String[] ports = port.split(",");

        if (hosts.length > ports.length) {
            Assert.assertEquals(String.format("Port missing for host %s", hosts[ports.length - 1]),
                    hosts.length, ports.length);
        } else {
            Assert.assertEquals(String.format("Host missing for port %s", ports[hosts.length - 1]),
                    hosts.length, ports.length);
        }

        for (String portVal : ports) {
            try {
                Integer.valueOf(portVal);
            } catch (Exception e) {
                throw new AssertionError(String.format("Port value invalid - %s", portVal));
            }
        }

        for (int i = 0; i < hosts.length; i++) {
            ServerAddress address = new ServerAddress(hosts[i], Integer.valueOf(ports[i]));
            addresses.add(address);
        }

        for (int i = 0; i < poolSize; i++) {
            MongoClient mongoClient = null;
            //Now try connecting to the Database
            try {
                mongoClient = new MongoClient(addresses);
            } catch (Exception e) {
                throw new AssertionError(String.format("Connection to MongoDB failed with the error %s",
                        ExceptionUtils.getStackTrace(e)));
            }

            DB db = null;
            try {
                db = mongoClient.getDB(dbName);
                if (username != null && password != null) {
                    Assert.assertTrue(String.format("Authentication to the Mongo database %s failed with %s/%s",
                            dbName, username, password), db.authenticate(username, password.toCharArray()));
                }
            } catch (Exception e) {
                throw new AssertionError(String.format("Error during initialization of MongoDB connection %s",
                        ExceptionUtils.getStackTrace(e)));
            }

            addToPool(mongoClient, false);
        }
    } catch (Exception e) {
        throw new AssertionError(String.format("Error during initialization of MongoDB connection %s",
                ExceptionUtils.getStackTrace(e)));
    } finally {
    }

}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

public List<Map<String, String>> provide(GatfTestDataProvider provider, AcceptanceTestContext context) {

    List<Map<String, String>> result = new ArrayList<Map<String, String>>();

    Assert.assertNotNull("provider cannot be null", provider);
    Assert.assertTrue("provider cannot be null", provider.getArgs() != null && provider.getArgs().length > 0);
    Assert.assertNotNull("mongodb-collection cannot be empty", provider.getArgs()[0]);
    Assert.assertNotNull("queryString cannot be empty", provider.getQueryStr());
    Assert.assertNotNull("variableNames cannot be empty", provider.getSourceProperties());
    Assert.assertNotNull("propertyNames cannot be empty", provider.getProviderProperties());

    String dbName = args[2].trim();
    String collName = provider.getArgs()[0].trim();
    String queryString = provider.getQueryStr().trim();
    String variableNames = provider.getProviderProperties();
    String propertyNames = provider.getSourceProperties();

    Assert.assertNotNull("mongodb-collection cannot be empty", collName.isEmpty());
    Assert.assertFalse("queryString cannot be empty", queryString.isEmpty());

    List<String> variableNamesArr = new ArrayList<String>();
    for (String varName : variableNames.split(",")) {
        if (!varName.trim().isEmpty()) {
            variableNamesArr.add(varName);
        }/*from w w  w  . j a va 2s  .  c  o  m*/
    }
    Assert.assertTrue("need to define at-least a single variable name",
            !variableNames.isEmpty() && variableNames.split(",").length > 0 && variableNamesArr.size() > 0);

    List<String> propertyNamesArr = new ArrayList<String>();
    for (String varName : propertyNames.split(",")) {
        if (!varName.trim().isEmpty()) {
            propertyNamesArr.add(varName);
        }
    }
    Assert.assertTrue("need to define at-least a single property name",
            !propertyNames.isEmpty() && propertyNames.split(",").length > 0 && propertyNamesArr.size() > 0);

    Assert.assertTrue("property name and variable name sizes don't match",
            propertyNamesArr.size() == variableNamesArr.size());

    StringBuilder build = new StringBuilder();
    build.append("Provider configuration [\n");
    build.append(String.format("dataSource name is %s\n", getDataSourceName()));
    build.append(String.format("mongodb-collection is %s\n", collName));
    build.append(String.format("queryString is %s\n", queryString));
    build.append(String.format("propertyNames is %s\n", propertyNames));
    build.append(String.format("variableNames is %s]", variableNames));
    logger.info(build.toString());

    Resource res = null;
    try {

        res = getResource();
        MongoClient mongoClient = (MongoClient) res.object;

        DB db = null;
        try {
            db = mongoClient.getDB(dbName);

            DBCollection coll = db.getCollection(collName);
            Assert.assertNotNull(String.format("Mongodb collection %s not found", collName), coll);

            DBObject queryObject = null;
            try {
                queryObject = (DBObject) JSON.parse(queryString);
            } catch (Exception e) {
                Assert.assertNotNull("queryString passed is invalid");
            }

            DBCursor cursor = null;
            try {
                cursor = coll.find(queryObject);
                while (cursor.hasNext()) {
                    DBObject object = cursor.next();
                    Map<String, String> row = new HashMap<String, String>();
                    for (int i = 0; i < variableNamesArr.size(); i++) {
                        Assert.assertTrue(
                                String.format("Could not find %s field in the result document returned",
                                        propertyNamesArr.get(i)),
                                object.containsField(propertyNamesArr.get(i)));
                        row.put(variableNamesArr.get(i), object.get(propertyNamesArr.get(i)).toString());
                    }
                    result.add(row);
                }
            } catch (Exception e) {
                throw new AssertionError(e);
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        } catch (Exception e) {
            throw new AssertionError(
                    String.format("Fetching Test Data failed while executing query %s with the error %s",
                            queryString, ExceptionUtils.getStackTrace(e)));
        } finally {
            if (mongoClient != null)
                mongoClient.close();
        }
    } catch (Exception e) {
        throw new AssertionError(
                String.format("Fetching Test Data failed while executing query %s with the error %s",
                        queryString, ExceptionUtils.getStackTrace(e)));
    } finally {
        if (res != null)
            releaseToPool(res);
    }
    return result;
}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

public boolean execute(String queryStr) {

    boolean result = false;

    Assert.assertNotNull("queryString cannot be empty", queryStr);

    String dbName = args[2].trim();
    String queryString = queryStr.trim();

    Assert.assertFalse("queryString cannot be empty", queryString.isEmpty());

    StringBuilder build = new StringBuilder();
    build.append("DataSourceHook configuration [\n");
    build.append(String.format("dataSource name is %s\n", getDataSourceName()));
    build.append(String.format("queryString is %s]", queryString));
    logger.info(build.toString());/*w w w .  j  a  v  a  2  s .  c om*/

    Resource res = null;
    try {

        res = getResource();
        MongoClient mongoClient = (MongoClient) res.object;

        DB db = null;
        try {
            db = mongoClient.getDB(dbName);

            try {
                Object resp = db.eval(queryStr, "");
                result = resp != null;
            } catch (Exception e) {
                throw new AssertionError(e);
            }
        } catch (Exception e) {
            throw new AssertionError(String.format("Error occurred while executing query %s with the error %s",
                    queryString, ExceptionUtils.getStackTrace(e)));
        }
    } catch (Exception e) {
        throw new AssertionError(String.format("Error occurred while executing query %s with the error %s",
                queryString, ExceptionUtils.getStackTrace(e)));
    } finally {
        if (res != null)
            releaseToPool(res);
    }
    return result;
}

From source file:com.gdn.x.ui.function.Permute.java

static void permute(java.util.List<Integer> arr, int k) {
    for (int i = k; i < arr.size(); i++) {
        java.util.Collections.swap(arr, i, k);
        permute(arr, k + 1);//from w w w  .  java2s . c  o  m
        java.util.Collections.swap(arr, k, i);
    }
    if (k == arr.size() - 1) {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("tool_data");
        DBCollection coll = db.getCollection("combination");
        BasicDBObject doc = new BasicDBObject();
        doc.put("weight", java.util.Arrays.toString(arr.toArray()));
        coll.insert(doc);
        System.out.println(java.util.Arrays.toString(arr.toArray()));
    }
}

From source file:com.geeksanon.AppController.java

License:Open Source License

/**
 * Method to make a connection to the database, with the URI.
 * /*from   ww  w  . ja va  2 s. com*/
 * @param URIString
 *            URI passed other than the localhost
 * @throws IOException
 *             when the page is not found.
 */
public AppController(String URIString) throws IOException {
    MongoClient mongoClient = new MongoClient(new MongoClientURI(URIString));
    DB database = mongoClient.getDB("askme");
    questionDAO = new QuestionDAO(database);
    userDAO = new UserDAO(database);
    sessionDAO = new SessionDAO(database);

    configuration = loadTemplateConfiguration();
    Spark.setPort(5115);
    intialiseRoutes();
}

From source file:com.github.joelittlejohn.embedmongo.MongoScriptsMojo.java

License:Apache License

DB connectToMongoAndGetDatabase() throws MojoExecutionException {
    if (databaseName == null || databaseName.trim().length() == 0) {
        throw new MojoExecutionException("Database name is missing");
    }//from  w  ww  .  j a v a2 s .  co  m

    MongoClient mongoClient;
    try {
        mongoClient = new MongoClient("localhost", getPort());
    } catch (UnknownHostException e) {
        throw new MojoExecutionException("Unable to connect to mongo instance", e);
    }
    getLog().info("Connected to MongoDB");
    return mongoClient.getDB(databaseName);
}