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:DataAccess.DAO.LoginDAO.java

public String validate(String username, String password) {

    String returnText = LOGIN_FAILURE;

    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("Restaurant");

    try {//ww  w .j av  a 2  s . c o m

        //boolean auth = db.authenticate(username, password.toCharArray());
        MongoCredential credential2 = MongoCredential.createCredential(username, "Restaurant",
                password.toCharArray());
        MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential2));

        DB db2 = mongoClient.getDB("Restaurant");
        System.out.println("Connect to database successfully");

        DBCollection coll = db2.getCollection("Users");
        System.out.println("Collection users selected successfully");
        BasicDBObject document2 = new BasicDBObject();
        document2.put("UserName", username);
        document2.put("Password", password);
        //coll.insert(document2);
        DBCursor cur2 = coll.find(document2);

        System.out.println(cur2.toString());

        while (cur2.hasNext()) {
            System.out.println(cur2.next());
        }

        System.out.println("Login is successful!");

        if (credential2 != null) {

            DBCollection table = db.getCollection("Users");

            BasicDBObject document = new BasicDBObject();
            document.put("UserName", username);
            table.insert(document);
            DBCursor cur = table.find(document);

            while (cur.hasNext()) {
                System.out.println(cur.next());
            }

            HttpSession session = SessionBean.getSession();
            session.setAttribute("UserName", user);

            System.out.println("Login is successful!");
            returnText = LOGIN_SUCCESS;

            return "admins";
        } else {

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Incorrect Username and Passowrd", "Please enter correct username and Password"));

            System.out.println("Login is failed!");
            return "login";
        }
        //System.out.println("Done");

        //return returnText;

    } catch (MongoException e) {
        e.printStackTrace();
    } finally {
        mongo.close();
    }
    return returnText;
}

From source file:DataAccess.DAO.OrderDAO.java

public Boolean connectDB() {
    try {//from  www .j ava  2s . co m
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient(Constants.HOST_BD_MONGO, Constants.PORT_BD_MONGO);
        // Now connect to your databases
        DB db = mongoClient.getDB("recuerdos");
        System.out.println("Connect to database successfully");
        coll = db.getCollection("orders");
        System.out.println("Collection orders selected successfully");
        return true;
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        return false;
    }
}

From source file:DataAccess.DAO.ShopDAO.java

public Boolean connectDB() {
    try {//from  www.  jav  a 2  s  . c om
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient(Constants.HOST_BD_MONGO, Constants.PORT_BD_MONGO);
        // Now connect to your databases
        DB db = mongoClient.getDB("recuerdos");
        System.out.println("Connect to database successfully");
        coll = db.getCollection("shops");
        System.out.println("Collection account selected successfully");
        return true;
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        return false;
    }
}

From source file:DataAccess.DAO.UserDAO.java

public Boolean connectDB() {
    try {//  ww  w .  j  a va2 s. c  o m
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient(Constants.HOST_BD_MONGO, Constants.PORT_BD_MONGO);
        // Now connect to your databases
        DB db = mongoClient.getDB("recuerdos");
        System.out.println("Connect to database successfully");
        coll = db.getCollection("users");
        System.out.println("Collection account selected successfully");
        return true;
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        return false;
    }
}

From source file:datapreparation.MongoStatistics.java

public void usersOfUrl(String URL) {
    // TODO code application logic here

    // TODO code application logic here
    int limit = 0;
    String filename = "Users_Of_Url_" + URL + ".txt";

    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    MongoClient mongoClient;

    try {/*from  w w  w.  j av  a 2s  .c o m*/
        mongoClient = new MongoClient("localhost");

        //use database
        DB db = mongoClient.getDB("users");

        //get collection
        DBCollection coll = db.getCollection("urls");

        // build the $projection operation
        //            DBObject fields = new BasicDBObject("user", 1);
        //            fields.put("_id", 0);
        //            BasicDBObject project = new BasicDBObject("$project", fields);

        //build the match operation
        DBObject matchFields = new BasicDBObject("url", URL);
        DBObject match = new BasicDBObject("$match", matchFields);

        // Now the $group operation
        DBObject groupFields = new BasicDBObject("_id", "$user");
        groupFields.put("count", new BasicDBObject("$sum", 1));
        DBObject group = new BasicDBObject("$group", groupFields);

        // Finally the $sort operation
        BasicDBObject sort = new BasicDBObject("$sort", new BasicDBObject("count", -1));

        // run aggregation
        List<DBObject> pipeline;
        if (limit == 0) {// without limits!
            pipeline = Arrays.asList(match, group, sort);
        } else {
            // create new BasicDBObject that limit query result in only 100 rows
            DBObject limitRes = new BasicDBObject("$limit", limit);
            pipeline = Arrays.asList(match, group, sort, limitRes);
        }
        AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
                .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

        Cursor cursor = coll.aggregate(pipeline, aggregationOptions);

        writeToFile(cursor, filename, "User\t Count");

        cursor.close();
        mongoClient.close();

    } catch (IOException ex) {
        System.out.println("Something's Wrong! " + ex);
    }
}

From source file:datapreparation.MongoStatistics.java

public void topUrls() {
    // TODO code application logic here
    int limit = 0;
    String filename = "Top_Urls_More.txt";
    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    MongoClient mongoClient;

    try {//ww w.j a  va 2s.  co  m
        mongoClient = new MongoClient("localhost");

        //use database
        DB db = mongoClient.getDB("users");

        //get collection
        DBCollection coll = db.getCollection("urls");

        // build the $projection operation
        DBObject fields = new BasicDBObject("url", 1);
        fields.put("_id", 0);
        BasicDBObject project = new BasicDBObject("$project", fields);

        // Now the $group operation
        DBObject groupFields = new BasicDBObject("_id", "$url");
        groupFields.put("count", new BasicDBObject("$sum", 1));
        DBObject group = new BasicDBObject("$group", groupFields);

        // Finally the $sort operation
        BasicDBObject sort = new BasicDBObject("$sort", new BasicDBObject("count", -1));

        // run aggregation
        List<DBObject> pipeline;
        if (limit == 0) {// without limits!
            pipeline = Arrays.asList(project, group, sort);
        } else {
            // create new BasicDBObject that limit query result in only 100 rows
            DBObject limitRes = new BasicDBObject("$limit", limit);
            pipeline = Arrays.asList(project, group, sort, limitRes);
        }
        AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
                .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

        Cursor cursor = coll.aggregate(pipeline, aggregationOptions);

        writeToFile2(cursor, filename, "URL\t Count");

        cursor.close();
        mongoClient.close();

    } catch (IOException ex) {
        System.out.println("Something's Wrong! " + ex);
    }
}

From source file:datapreparation.MongoStatistics.java

public void timeIntervals() {
    // TODO code application logic here
    int limit = 0;
    String filename = "Times.txt";
    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    MongoClient mongoClient;

    try {// w w w  . j a  v  a  2  s.c o  m
        mongoClient = new MongoClient("localhost");

        //use database
        DB db = mongoClient.getDB("users");

        //get collection
        DBCollection coll = db.getCollection("urls");

        // build the $projection operation
        DBObject fields = new BasicDBObject("time", 1);
        fields.put("_id", 0);
        BasicDBObject project = new BasicDBObject("$project", fields);

        // Now the $group operation
        DBObject groupFields = new BasicDBObject("_id", "$time");
        //groupFields.put("count", new BasicDBObject("$sum", 1));
        DBObject group = new BasicDBObject("$group", groupFields);

        // Finally the $sort operation
        //BasicDBObject sort = new BasicDBObject("$sort", new BasicDBObject("count", -1));

        // run aggregation
        List<DBObject> pipeline;
        if (limit == 0) {// without limits!
            pipeline = Arrays.asList(project, group);
        } else {
            // create new BasicDBObject that limit query result in only 100 rows
            DBObject limitRes = new BasicDBObject("$limit", limit);
            pipeline = Arrays.asList(project, group, limitRes);
        }
        AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
                .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

        Cursor cursor = coll.aggregate(pipeline, aggregationOptions);

        writeToFile3(cursor, filename, "Times");

        cursor.close();
        mongoClient.close();

    } catch (IOException ex) {
        System.out.println("Something's Wrong! " + ex);
    }
}

From source file:datapreparation.MongoStatistics.java

public void usersToUrls() {
    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    MongoClient mongoClient;

    try {//from   ww w .ja  va  2 s.c  om
        mongoClient = new MongoClient("localhost");

        //use database
        DB db = mongoClient.getDB("users");

        //get collection
        DBCollection coll = db.getCollection("urls");

        //iterate with a cursor
        BasicDBObject query = new BasicDBObject("source", new BasicDBObject("$exists", true));

        DBCursor cursor = coll.find(query);

        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter("Users_To_Urls.txt"));
            writer.write("url,user,time\n");

            while (cursor.hasNext()) {
                BasicDBObject tweet = (BasicDBObject) cursor.next();

                String time = tweet.get("created_at").toString();
                String user = tweet.get("from_user").toString();
                String urls[] = tweet.get("source").toString().replaceAll("&quot", "").split(";");

                for (String url : urls) {
                    if (url.matches("http.*")) {
                        //The user posted one link, write it in the file!
                        writer.write(url + "," + user + "," + time + "\n");
                    }
                }
            }
        } finally {
            cursor.close();
            mongoClient.close();
            writer.close();
        }
    } catch (IOException ex) {
        System.out.println("Something's Wrong! " + ex);
    }
}

From source file:de.iew.imageread.Main.java

License:Apache License

public void run() {
    try {//from   w w w .  j  a  v  a2 s . c o  m
        this.imageOutputDir = System.getProperty("java.io.tmpdir");

        File outputBase = new File(this.imageOutputDir);
        testAndCreateDirectory(outputBase);

        MongoClient mongoClient = new MongoClient(this.mongohost, this.mongoport);

        DB db = mongoClient.getDB(this.mongodb);

        GridFS gridFS = new GridFS(db);

        DBCursor cursor = gridFS.getFileList(this.queryFromOptions()).sort(new BasicDBObject("uploadDate", -1));

        int imageNumber = 0;
        while (cursor.hasNext()) {
            DBObject fileObject = cursor.next();

            GridFSDBFile file = gridFS.find((ObjectId) fileObject.get("_id"));
            printGridFSDBFile(file);

            if (writeImageFile(outputBase, imageNumber, file)) {
                imageNumber++;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.steilerdev.myVerein.server.controller.init.InitController.java

License:Open Source License

/**
 * This function is establishing a connection to the new database and storing the new super user as well as the new root division. To correctly execute this function the {@link #mongoIsAvailable} function should be called first.
 * @param user The new super admin.//from w w  w.  ja  v a 2s.c  o  m
 * @param division The new root division.
 * @return True if the operation was successfully, false otherwise.
 */
private boolean savingInitialSetup(User user, Division division, Settings settings) {
    if (mongoAddress != null && databaseName != null && !databaseName.isEmpty()) {
        logger.trace("Saving user and division using new MongoDB connection");

        MongoClient mongoClient = new MongoClient(mongoAddress, mongoCredential);

        DB mongoDB = mongoClient.getDB(databaseName);
        if (mongoClient.getDatabaseNames().contains(databaseName)) {
            logger.warn("The database already contains the defined collection, dropping content.");
            mongoDB.dropDatabase();
        }

        try {
            if (user != null) {
                logger.debug("Storing user");
                DBObject userObject = (DBObject) mappingMongoConverter.convertToMongoType(user);
                userObject.put("_class", user.getClass().getCanonicalName());
                mongoDB.getCollection(user.getClass().getSimpleName().toLowerCase()).insert(userObject);
            }

            if (division != null) {
                logger.debug("Storing division");
                DBObject divisionObject = (DBObject) mappingMongoConverter.convertToMongoType(division);
                divisionObject.put("_class", division.getClass().getCanonicalName());
                mongoDB.getCollection(division.getClass().getSimpleName().toLowerCase()).insert(divisionObject);
            }

            if (settings != null) {
                logger.debug("Storing settings");
                settings.saveSettings(user, null);
                DBObject settingsObject = (DBObject) mappingMongoConverter.convertToMongoType(settings);
                settingsObject.put("_class", settings.getClass().getCanonicalName());
                mongoDB.getCollection(settings.getClass().getSimpleName().toLowerCase()).insert(settingsObject);
            }

            logger.info("Successfully saved root division and super admin");
            return true;
        } catch (MongoException e) {
            logger.warn("Unable to store root division and super admin in database");
            return false;
        } finally {
            mongoClient.close();
        }
    } else {
        logger.warn(
                "Unable to save super admin and new root division, because the new MongoDB connection is not available");
        return false;
    }
}