Example usage for com.mongodb MongoClient getDatabase

List of usage examples for com.mongodb MongoClient getDatabase

Introduction

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

Prototype

public MongoDatabase getDatabase(final String databaseName) 

Source Link

Usage

From source file:com.sitewhere.mongodb.MongoDbClient.java

License:Open Source License

/**
 * Detects whether a replica set is configured and creates one if not.
 * /*from w  ww. jav  a 2 s .  c  o m*/
 * @param addresses
 */
protected void doAutoConfigureReplication(List<ServerAddress> addresses) throws SiteWhereException {
    // Only connect to primary for sending commands.
    MongoClient primary = getPrimaryConnection(addresses);

    // Check for existing replica set configuration.
    getLogger().info("Checking for existing replica set...");
    try {
        Document result = primary.getDatabase("admin").runCommand(new BasicDBObject("replSetGetStatus", 1));
        if (result.getDouble("ok") == 1) {
            getLogger().warn("Replica set already configured. Skipping auto-configuration.");
            return;
        }
    } catch (MongoCommandException e) {
        getLogger().info("Replica set was not configured.");
    }

    // Create configuration for new replica set.
    try {
        getLogger().info("Configuring new replica set '" + getConfiguration().getReplicaSetName() + "'.");
        BasicDBObject config = new BasicDBObject("_id", getConfiguration().getReplicaSetName());
        List<BasicDBObject> servers = new ArrayList<BasicDBObject>();

        // Create list of members in replica set.
        int index = 0;
        for (final ServerAddress address : addresses) {
            BasicDBObject server = new BasicDBObject("_id", index);
            server.put("host", (address.getHost() + ":" + address.getPort()));

            // First server in list is preferred primary.
            if (index == 0) {
                server.put("priority", 10);
            }

            servers.add(server);
            index++;
        }
        config.put("members", servers);

        // Send command.
        Document result = primary.getDatabase("admin").runCommand(new BasicDBObject("replSetInitiate", config));
        if (result.getDouble("ok") != 1) {
            throw new SiteWhereException("Unable to auto-configure replica set.\n" + result.toJson());
        }
        getLogger().info(
                "Replica set '" + getConfiguration().getReplicaSetName() + "' creation command successful.");
    } finally {
        primary.close();
    }
}

From source file:com.snapit.solutions.slantfree.db.DatabaseConnector.java

/**
 * Simple Database Connector - Connects to MongoDB
 * @return /*  w  w w.  j  a va 2 s  . c  o m*/
 */
public static MongoDatabase getDbConnection() {
    try {

        MongoClient mongoClient = getMongoClient();

        // Now connect to your databases
        MongoDatabase db;
        db = mongoClient.getDatabase(DB_NAME);
        LOG.info("Connect to database successfully");
        return db;
    } catch (Exception e) {
        LOG.error(e.getClass().getName() + ": " + e.getMessage());
    }
    return null;
}

From source file:com.sparkjava.MongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(MongoDBSparkFreemarkerStyle.class, "/freemarker");

    MongoClient client = new MongoClient();

    MongoDatabase database = client.getDatabase("m101");
    final MongoCollection<Document> collection = database.getCollection("funnynumbers");

    //        Spark.get("/", new Route() {
    //            
    //            public Object handle(final Request request,
    //                                 final Response response) {
    //                StringWriter writer = new StringWriter();
    //                try {
    //                    Template template = configuration.getTemplate("answer.ftl");
    ///*  ww  w.j  a v  a  2s .  c om*/
    //                    // Not necessary yet to understand this.  It's just to prove that you
    //                    // are able to run a command on a mongod server
    //                    List<Document> results =
    //                    collection.aggregate(asList(new Document("$group", new Document("_id", "$value")
    //                                                                       .append("count", new Document("$sum", 1))),
    //                                                new Document("$match", new Document("count", new Document("$lte", 2))),
    //                                                new Document("$sort", new Document("_id", 1))))
    //                              .into(new ArrayList<Document>());
    //
    //                    int answer = 0;
    //                    for (Document cur : results) {
    //                        answer += (Double) cur.get("_id");
    //                    }
    //
    //                    Map<String, String> answerMap = new HashMap<String, String>();
    //                    answerMap.put("answer", Integer.toString(answer));
    //
    //                    template.process(answerMap, writer);
    //                } catch (Exception e) {
    //                    e.printStackTrace();
    ////                    halt(500);
    //                }
    //                return writer;
    //            }
    //        });
}

From source file:com.techngage.smartbin.Controller.java

License:Apache License

public Controller(String mongoURIString) throws IOException {
    final MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoURIString));
    final MongoDatabase smartbinDatabase = mongoClient.getDatabase("smartbin");

    userDAO = new UserDAO(smartbinDatabase);
    sessionDAO = new SessionDAO(smartbinDatabase);
    routeDAO = new RouteDAO(smartbinDatabase);
    truckDAO = new TruckDAO(smartbinDatabase);
    locationDAO = new LocationDAO(smartbinDatabase);

    cfg = createFreemarkerConfiguration();
    setPort(8082);//from  www . j a  v a 2 s.c om
    Spark.staticFileLocation("/public");
    initializeRoutes();
}

From source file:com.tengu.io.MongoBolt.java

@Override
public void prepare(Map stormConf, TopologyContext context) {
    String mongo_ip = stormConf.get("mongo.ip").toString();
    int mongo_port = Integer.parseInt(stormConf.get("mongo.port").toString());
    System.out.format("Mongo connect: %s:%d", mongo_ip, mongo_port);
    MongoClient mongoClient = new MongoClient(mongo_ip, mongo_port);
    db = mongoClient.getDatabase("amica-results");
    System.out.println("Database found");
}

From source file:com.thaonedroid.mongodbexercise.MongoDB.java

public static void main(String[] args) {
    try {// www.j a  v  a  2 s .c o  m
        MongoClientURI connStr = new MongoClientURI("mongodb://localhost:27017");
        MongoClient mongoClient = new MongoClient(connStr);

        MongoDatabase db = mongoClient.getDatabase("twitter");
        MongoCollection<Document> collection = db.getCollection("tweets");

        Scanner scanner = new Scanner(System.in);
        int input;
        OUTER: do {
            start();
            input = scanner.nextInt();
            switch (input) {
            case 1:
                //System.out.println("Distinct Twitter users : " + query.totalUsers());
                System.out.println("Question : " + q1);
                execute(query.totalUsers());
                break;
            case 2:
                //execute(query.linkOthers());
                System.out.println("Question : " + q2);
                System.out.println("Answer : Query hasn't been properly figured out yet");
                break;
            case 3:
                //execute(query.mostMentioned());
                System.out.println("Question : " + q3);
                System.out.println("Answer : Query hasn't been properly figured out yet");
                break;
            case 4:
                System.out.println("Question : " + q4);
                execute(query.mostActive());
                //System.out.println("Most active users : " + query.mostActive());
                break;
            case 5:
                System.out.println("Question : " + q5);
                execute(query.mostGrumpy());
                //System.out.println("Most grumpy users : " + query.mostGrumpy());
                break;
            case 6:
                System.out.println("Question : " + q6);
                execute(query.mostHappy());
                //System.out.println("Most happy users : " + query.mostHappy());
                break;
            case 7:
                break OUTER;
            default:
                break;
            }
        } while (true);
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ":" + e.getMessage());
    }
}

From source file:com.threecrickets.prudence.cache.HazelcastMongoDbMapStore.java

License:LGPL

/**
 * The MongoDB collection used for the store.
 * /* w  w w. ja  v  a  2  s.co  m*/
 * @return The MongoDB collection
 */
public MongoCollection<Document> getCollection() {
    if (collection == null) {
        Component component = InstanceUtil.getComponent();
        if (component != null) {
            MongoClient client = (MongoClient) component.getContext().getAttributes()
                    .get(MONGODB_CLIENT_ATTRIBUTE);
            if (client != null) {
                MongoDatabase database = client.getDatabase("prudence");
                if (database != null)
                    collection = database.getCollection(collectionName);
            }
        }
    }

    if (collection == null)
        throw new RuntimeException(
                "MongoDB client must be configured in order to use HazelcastMongoDbMapStore");

    return collection;
}

From source file:com.threecrickets.prudence.cache.MongoDbCache.java

License:LGPL

/**
 * Constructor.//from   w  w  w  .  j  ava2 s . c  om
 * 
 * @param client
 *        The MongoDB client
 * @param databaseName
 *        The MongoDB database name
 * @param collectionName
 *        The name of the collection to use for the cache
 */
public MongoDbCache(MongoClient client, String databaseName, String collectionName) {
    this.client = client;
    MongoDatabase database = client.getDatabase(databaseName);
    cacheCollection = database.getCollection(collectionName);
    try {
        cacheCollection.createIndex(TAG_INDEX);
        cacheCollection.createIndex(EXPIRATION_DATE_INDEX);
        up();
    } catch (com.mongodb.MongoSocketException x) {
        down();
    }
}

From source file:com.tremolosecurity.mongodb.unison.CreateMongoGroups.java

License:Apache License

private void checkGroups(User user, MongoClient client, Iterable<String> toCheck) {

    HashSet<String> groupsThatDontExist = new HashSet<String>();

    for (String collectionName : client.getDatabase(this.target.getDatabaseName()).listCollectionNames()) {
        for (String groupName : toCheck) {
            if (client.getDatabase(this.target.getDatabaseName()).getCollection(collectionName)
                    .find(and(eq("objectClass", this.target.getGroupObjectClassName()),
                            eq(this.target.getGroupNameAttribute(), groupName)))
                    .first() == null) {/* www .  ja v  a 2 s  .c  o  m*/
                groupsThatDontExist.add(groupName);
            }
        }
    }

    for (String groupName : groupsThatDontExist) {
        Document doc = new Document();
        doc.append("unisonRdnAttributeName", target.getGroupNameAttribute());
        doc.append("objectClass", target.getGroupObjectClassName());
        doc.append(target.getGroupNameAttribute(), groupName);
        client.getDatabase(target.getDatabaseName()).getCollection(collectionName).insertOne(doc);
        logger.warn("Group created : '" + groupName + "'");
    }
}

From source file:com.u2apple.rt.db.dao.DeviceLogDao.java

private MongoCollection<Document> getDeviceLog() {
    MongoClient mongoClient = new MongoClient("localhost");
    MongoDatabase db = mongoClient.getDatabase("recognition");
    return db.getCollection("log");
}