Example usage for com.mongodb Mongo getDB

List of usage examples for com.mongodb Mongo getDB

Introduction

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

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:com.ovea.mongodb.EmbeddedMongoDBMain.java

License:Apache License

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//from ww w.j a  v  a 2s .co m
    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();
}

From source file:com.paradigma.recommender.db.MongoDBDataModel.java

License:Apache License

private void buildModel() throws UnknownHostException, MongoException {
    userIsObject = false;//w w w .  j  av  a 2 s  .c  om
    itemIsObject = false;
    idCounter = 0;
    preferenceIsString = true;
    Mongo mongoDDBB = new Mongo(mongoHost, mongoPort);
    DB db = mongoDDBB.getDB(mongoDB);
    mongoTimestamp = new Date(0);
    FastByIDMap<Collection<Preference>> userIDPrefMap = new FastByIDMap<Collection<Preference>>();
    if (!mongoAuth || (mongoAuth && db.authenticate(mongoUsername, mongoPassword.toCharArray()))) {
        collection = db.getCollection(mongoCollection);
        collectionMap = db.getCollection(MONGO_MAP_COLLECTION);
        DBObject indexObj = new BasicDBObject();
        indexObj.put("element_id", 1);
        collectionMap.ensureIndex(indexObj);
        indexObj = new BasicDBObject();
        indexObj.put("long_value", 1);
        collectionMap.ensureIndex(indexObj);
        collectionMap.remove(new BasicDBObject());
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            Map<String, Object> user = (Map<String, Object>) cursor.next().toMap();
            if (!user.containsKey("deleted_at")) {
                long userID = Long.parseLong(fromIdToLong(getID(user.get(mongoUserID), true), true));
                long itemID = Long.parseLong(fromIdToLong(getID(user.get(mongoItemID), false), false));
                float ratingValue = getPreference(user.get(mongoPreference));
                Collection<Preference> userPrefs = userIDPrefMap.get(userID);
                if (userPrefs == null) {
                    userPrefs = Lists.newArrayListWithCapacity(2);
                    userIDPrefMap.put(userID, userPrefs);
                }
                userPrefs.add(new GenericPreference(userID, itemID, ratingValue));
                if (user.containsKey("created_at")
                        && mongoTimestamp.compareTo(getDate(user.get("created_at"))) < 0) {
                    mongoTimestamp = getDate(user.get("created_at"));
                }
            }
        }
    }
    delegate = new GenericDataModel(GenericDataModel.toDataMap(userIDPrefMap, true));
}

From source file:com.photon.phresco.service.impl.DbService.java

License:Apache License

private GridFS getGridFs() throws PhrescoException {
    if (isDebugEnabled) {
        LOGGER.debug("DbService.getGridFs:Entry");
    }//  w w  w  . j  a  v a  2s. c  o  m
    try {
        Mongo mongo = new Mongo(serverConfig.getDbHost(), serverConfig.getDbPort());
        DB db = mongo.getDB(serverConfig.getDbName());
        GridFS gfsPhoto = new GridFS(db, "icons");
        if (isDebugEnabled) {
            LOGGER.debug("DbService.getGridFs:Exit");
        }
        return gfsPhoto;
    } catch (UnknownHostException e) {
        if (isDebugEnabled) {
            LOGGER.error("DbService.getGridFs", STATUS_FAILURE,
                    MESSAGE_EQUALS + "\"" + e.getLocalizedMessage() + "\"");
        }
        throw new PhrescoException(e);
    } catch (MongoException e) {
        if (isDebugEnabled) {
            LOGGER.error("DbService.getGridFs", STATUS_FAILURE,
                    MESSAGE_EQUALS + "\"" + e.getLocalizedMessage() + "\"");
        }
        throw new PhrescoException(e);
    }
}

From source file:com.ponysdk.mongodb.dao.MongoDAO.java

License:Apache License

public void setDB(final Mongo mongo) {
    this.mongo = mongo;
    this.db = mongo.getDB("mydb");
}

From source file:com.sample.MyGroceryListServlet.java

License:Open Source License

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*ww w .java  2 s. co  m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Reference: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver

    String envVars = System.getenv("VCAP_SERVICES");

    DBObject dbO = (DBObject) JSON.parse(envVars);
    String parsedString = dbO.get("mongodb").toString();

    // Remove trailing and starting array brackets (otherwise it won't be valid JSON)
    parsedString = parsedString.replaceFirst("\\[ ", "");
    parsedString = parsedString.replaceFirst("\\]$", "");

    // Get the credentials
    dbO = (DBObject) JSON.parse(parsedString);
    parsedString = dbO.get("credentials").toString();

    // For debugging only
    // System.out.println(parsedString);

    dbO = (DBObject) JSON.parse(parsedString);

    System.out.println("Host name : " + dbO.get("hostname"));
    String hostName = dbO.get("hostname").toString();
    int port = Integer.parseInt(dbO.get("port").toString());
    String dbName = dbO.get("db").toString();
    String userName = dbO.get("username").toString();
    String password = dbO.get("password").toString();

    Mongo mongoClient = new Mongo(hostName, port);

    DB db = mongoClient.getDB(dbName);
    db.authenticate(userName, password.toCharArray());

    // Clean up old entries
    DBCollection coll = db.getCollection("testCollection");
    coll.drop();

    BasicDBObject lastAddedObject = null;
    for (String curItem : myGroceryList) {
        lastAddedObject = new BasicDBObject("i", curItem);
        coll.insert(lastAddedObject);
    }
    response.getWriter().println("<b>My grocery list is:</b>");

    coll.remove(lastAddedObject);
    DBCollection loadedCollection = db.getCollection("testCollection");
    DBCursor cursor = loadedCollection.find();
    try {
        response.getWriter().println("<ul>");
        while (cursor.hasNext()) {
            response.getWriter().println("<li>" + cursor.next().get("i") + "</li>");
        }
        response.getWriter().println("</ul>");
    } finally {
        cursor.close();
    }
}

From source file:com.smartlearner.email.analytics.dbmanage.java

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

    Mongo mongoClient = new Mongo("localhost", 27017);

    DB db = mongoClient.getDB("header");
    System.out.println("Conn succesful");

    DBCollection coll3 = db.getCollection("head_coll");
    System.out.println("Collection created successfully ...");

    /* BasicDBObject document = new BasicDBObject();
    document.put("subject", "sub");/*www.  j a v  a  2s . com*/
    document.put("from","frm");
    document.put("date","dt");
    coll3.insert(document);
    */
    //Scanner in=new Scanner(System.in);
    //String tst;
    //System.out.println("Enter serach query:");
    //tst=in.nextLine();

    Pattern namesRegex;
    srchtest srch = new srchtest();
    srch.assignsearch("19/jan/2015");

    if (srch.result == "m3") {

        String tt = srch.month;

        // String tst = Character.toUpperCase(tt.charAt(0)) + tt.substring(1);

        String tst = "Aditya";
        //String tst1 = Character.toUpperCase(tst.charAt(0)) + tst.substring(1);
        namesRegex = Pattern.compile("^(.*)job(.*)you(.*)");

        prnt(namesRegex, coll3);

        BasicDBObject query = new BasicDBObject("subject", namesRegex);

        DBCursor cursor = coll3.find();
        System.out.println("***** Output *****");
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    }

    /*
     BasicDBObject abc=new BasicDBObject();
     abc.put("from","Myntra");
             
     DBCursor cursor = coll3.find(abc);
            
     while (cursor.hasNext())
    { 
              
    System.out.println(cursor.next()); 
               
    }
      */

    /*coll3.ensureIndex(new BasicDBObject("from", 1),new BasicDBObject("date", 1));
    List <DBObject> list = coll3.getIndexInfo();
            
    for (DBObject o : list) {
    System.out.println(o);
    }
         */
    //BasicDBObject abc=new BasicDBObject();
    //abc.put("subject","Internshala Campus Ambassador 3.0");
    //"2015-01-21T23:41:40.000Z"

    //DBCursor cursor = coll3.find(abc);
    //DBCursor.explain(BasicDB);
    //while(cursor.hasNext()) {
    //System.out.println(cursor.next());
    //}

}

From source file:com.smartlearner.email.analytics.EmailAnalytics.java

public static void main(String args[]) {

    try {//from  w  w w  .  j a v a2 s  . c  o  m

        Mongo mongoClient = new Mongo("localhost", 27017);

        DB db = mongoClient.getDB("header");
        System.out.println("Conn succesful");

        //DBCollection coll3 = db.getCollection("temp_col"); has date stored in date format,not as string
        DBCollection coll3 = db.getCollection("head_coll");
        System.out.println("Collection created successfully");

        FileOutputStream out = new FileOutputStream("EmailText.txt");
        PrintStream print = new PrintStream(out);

        Properties props = new Properties(System.getProperties());
        props.setProperty("mail.store.protocol", "imaps");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        //store.connect("imap.gmail.com", "techkrishacadquery@gmail.com", "Phoenix81#");
        store.connect("imap.gmail.com", "adityaravi65@gmail.com", "m@vr1ck2009");
        System.out.println(store);
        Folder inbox = store.getFolder("inbox");
        inbox.open(Folder.READ_ONLY);

        //HEADERS

        /*
        Message[] messages = inbox.getMessages();
        for (int i = 0; i < messages.length; i++) {
        System.out.println((i + 1));
        Enumeration headers = messages[i].getAllHeaders();
        while (headers.hasMoreElements()) {
        Header h = (Header) headers.nextElement();
                
        BasicDBObject document = new BasicDBObject();
        if((!"Subject".equals(h.getName()))&&(!"From".equals(h.getName()))&&(!"Date".equals(h.getName()))&&(!"To".equals(h.getName()))&&(!"Delivered-To".equals(h.getName())))
        {
        System.out.println(h.getName() + ": " + h.getValue());   
        document.put(h.getName(), h.getValue());
        }
        coll3.insert(document);
        System.out.println("=========================================");
        }}
                
        */

        //String[][] data = null;

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        int countMail = 0;
        //            int i=0;
        for (Message message : msg) {
            //if (countMail < 10) {
            if (!message.getFrom()[0].toString().contains("google.com")) {
                countMail++;

                //  if(message.getFrom()[0].toString().contains("Internshala"))
                //{
                BasicDBObject document = new BasicDBObject();

                Enumeration headers = message.getAllHeaders();
                while (headers.hasMoreElements()) {
                    Header h = (Header) headers.nextElement();

                    if ((!"Subject".equals(h.getName())) && (!"From".equals(h.getName()))
                            && (!"Date".equals(h.getName())) && (!"To".equals(h.getName()))
                            && (!"Delivered-To".equals(h.getName()))) {
                        System.out.println(h.getName() + ": " + h.getValue());
                        document.put(h.getName(), h.getValue());
                    }

                    System.out.println("=========================================");
                }

                // Date dt=new Date();
                String dt = message.getSentDate().toString();
                //System.out.println("HELOO!!!! DATE: " + dt);
                //print.println(message.getSentDate().toString());

                //System.out.println("Hello!!! FROM: " +message.getFrom()[0].toString());
                String frm = message.getFrom()[0].toString();

                //for (int i = 0; i < data.length; ++i) {}
                //  for (int j = 0; j < data[i].length; ++j){;}

                //print.println(message.getFrom()[0].toString());
                String sbj = message.getSubject();
                //System.out.println("SUBJECT: " + sbj);

                document.put("subject", sbj);
                document.put("from", frm);
                document.put("date", dt);
                coll3.insert(document);

                //print.println(message.getSubject());
                /*                System.out.println("CONTENT: " + message.getContent().toString());
                print.println(message.getContent().toString());
                System.out.println(message.getContentType());
                print.println(message.getContentType());
                */
                /*      
                Object content = message.getContent();
                if(content instanceof String)
                {
                    String str=(String) content;
                    print.println(str);
                } else if(content instanceof Multipart)
                {
                    Multipart mp=(Multipart) content;
                    int count = mp.getCount();
                    System.out.println("-----------");
                    for (int x = 0; x < count; x++)
                    {
                        BodyPart bp = mp.getBodyPart(x);
                        System.out.println(bp.getContent().toString());
                     // print.println(bp.getContent().toString());
                    }
                }
                  */

                //BasicDBObject newDocument = new BasicDBObject();
                //List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
                //obj.add(new BasicDBObject("subject",sbj));
                //obj.add(new BasicDBObject("from",frm));
                //newDocument.put("$and", obj);
                //newDocument.append("$set", new BasicDBObject().append("date", date));
                //coll.insert(newDocument);

                //DBCursor cursor = coll2.find();
                //while (cursor.hasNext())
                //{ 
                // System.out.println(cursor.next());             
                //}

                /*
                coll3.ensureIndex(new BasicDBObject("from", 1),new BasicDBObject("date", 1));
                coll3.ensureIndex(new BasicDBObject("sub", 1),new BasicDBObject("from", 1));
                coll3.ensureIndex(new BasicDBObject("from", 1));
                        */
                System.out.println("*******");
                //}
            }

            //System.out.println(countMail++);
            //}

        }
    } catch (MessagingException | IOException e) {
        e.printStackTrace(System.out);
    }
}

From source file:com.smartlearner.email.analytics.user.java

public static void main(String[] args) throws UnknownHostException {
    usrname = "adityaravi65@gmail.com";
    Mongo mongoClient = new Mongo("localhost", 27017);

    DB db = mongoClient.getDB("email3");
    System.out.println("Conn succesful");

    DBCollection coll3 = db.getCollection(usrname);
    System.out.println("Collection created successfully ...");

    //Search//from   w w  w  .  j  a v a  2s. c  om
    search srch = new search();
    srch.assignsearch("29aug1990");

    if (srch.result == "m3") {
        Date dt = srch.d;
        System.out.println(dt);
    }

    if (srch.result == "m6") {
        Date dt = srch.d;
    }

    if (srch.result == "m9") {
        str1 = srch.srchstr2;
        str2 = srch.srchstr3;

        //Use these two strings for searching in mongodb
    }

    if (srch.result == "m10") {
        //use these two strings for searching in mongodb
        str1 = srch.srchstr2;
        str2 = srch.srchstr3;
        str3 = srch.srchstr4;

        System.out.println(str1 + str2);
    }
    if (srch.result == "m11") {

    }
}

From source file:com.test.mavenproject1.Main.java

public static void main(String[] args) throws Exception {
    //Load our image
    byte[] imageBytes = LoadImage("/home/fabrice/Pictures/priv/DSCN3338.JPG");
    //Connect to database
    Mongo mongo = new Mongo("127.0.0.1");
    String dbName = "GridFSTestJava";
    DB db = mongo.getDB(dbName);
    //Create GridFS object
    GridFS fs = new GridFS(db);
    //Save image into database
    GridFSInputFile in = fs.createFile(imageBytes);
    in.save();/*from   w  w  w.  ja  v a2 s . c o m*/

    //Find saved image
    GridFSDBFile out = fs.findOne(new BasicDBObject("_id", in.getId()));

    //Save loaded image from database into new image file
    FileOutputStream outputImage = new FileOutputStream("/home/fabrice/Pictures/DSCN3338Copy.JPG");
    out.writeTo(outputImage);
    outputImage.close();
}

From source file:com.tomtom.examples.exampleUsingDatabase.ExampleDatabaseModule.java

License:Apache License

/**
 * Get the MongoDB database instance./*from ww  w . j a va 2s  .  c  o  m*/
 *
 * @param mongo           MongoDB handle.
 * @param databaseName    Database name.
 * @param subDatabaseName Sub-database name (for unit tests). If the subdatabase name is empty, the database name is
 *                        used, otherwise the subdatabase name is appended to. Example, database="TEST", subdatabase
 *                        name="texas" would produce "TEST_texas".
 * @return MongoDB instance.
 * @throws MongoDBConnectionException If something went wrong.
 */
@Nonnull
protected MongoDB getDB(@Nonnull final Mongo mongo, @Nonnull final String databaseName,
        @Nonnull final String subDatabaseName) {
    assert mongo != null;
    assert databaseName != null;
    assert subDatabaseName != null;

    final MongoDB mongoDb = new MongoDB(mongo.getDB(databaseName), subDatabaseName);
    return mongoDb;
}