Example usage for com.mongodb Mongo Mongo

List of usage examples for com.mongodb Mongo Mongo

Introduction

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

Prototype

Mongo(final MongoClientURI mongoURI, @Nullable final MongoDriverInformation mongoDriverInformation) 

Source Link

Usage

From source file:com.sampleapp.db.MongoDAOFactory.java

License:Open Source License

public MongoDAOFactory(Properties serviceProperties) {

    if (serviceProperties == null) {
        System.out.println("No VCAP_SERVICES found");
        return;/* w  w w.ja va2  s. c  o m*/
    }

    System.out.println("VCAP_SERVICES found");

    try {

        host = serviceProperties.getProperty("hostname");
        port = serviceProperties.getProperty("port");
        username = serviceProperties.getProperty("username");
        password = serviceProperties.getProperty("password");
        database = serviceProperties.getProperty("db");

        System.out.println("Found all the params");

        // Mongo initialization
        mongoClient = new Mongo(host, Integer.parseInt(port));
        db = mongoClient.getDB(database);

        System.out.println("Connected to mongoDB on " + host + ":" + port);

        if (db.authenticate(username, password.toCharArray())) {
            infColl = db.getCollection("infcollection");
            System.out.println("Authenticated with mongoDB successfully");
        } else {
            throw new Exception("Authentication Failed");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.seer.datacruncher.jpa.dao.MongoDbDao.java

License:Open Source License

/**
 * Gets connection to data base./*w  w  w.  ja  v  a  2 s . c  o m*/
 * Note: mongoPool is thread-safe.
 *
 * @return connection
 */
private static DB getConnection() {
    try {
        if (mongoPool == null) {
            mongoPool = new Mongo(contactNode, Integer.parseInt(defaultPort));
            MongoOptions mo = mongoPool.getMongoOptions();
            if (mo.getConnectionsPerHost() <= 0 && !StringUtils.isEmpty(poolSize)) {
                mo.connectionsPerHost = Integer.parseInt(poolSize);
            }
        }
        DB mongoDB = mongoPool.getDB(MONGO_KEY_SPACE);
        if (userName != null && !userName.isEmpty() && password != null && !password.isEmpty()) {
            mongoDB.authenticate(userName, password.toCharArray());
        }
        return mongoDB;
    } catch (NumberFormatException e) {
        log.error("Number format exception", e);
    } catch (UnknownHostException e) {
        log.error(e);
    }
    return null;
}

From source file:com.servlets.GetPhotosList.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    context = config.getServletContext();
    // create a MongDB connection
    client = (Mongo) context.getAttribute("mongoClient");
    if (client == null) {
        client = new Mongo(Upload.address, 27017);
        context.setAttribute("mongoClient", client);
    }/*from w  w w  . ja v  a  2s.c o m*/
    db = (DB) context.getAttribute("mongoDB");
    if (db == null) {
        db = client.getDB("images");
        context.setAttribute("mongoDB", db);
    }
}

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");//from   w  w  w.  j a v a 2  s. co m
    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  ww  w .  j  a v a  2s  .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 ww . ja  va2  s . 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.sonyericsson.jenkins.plugins.bfa.db.MongoDBKnowledgeBase.java

License:Open Source License

/**
 * Gets the connection to the MongoDB/*from w w  w.  jav a  2s  .c  om*/
 * @return the Mongo.
 * @throws UnknownHostException if the host cannot be found.
 */
private Mongo getMongoConnection() throws UnknownHostException {
    if (mongo == null) {
        mongo = new Mongo(host, port);
    }
    return mongo;
}

From source file:com.springsource.html5expense.config.LocalMongoDbFactoryConfiguration.java

License:Apache License

@Override
@Bean//w  w  w.  j  ava 2  s.c om
public MongoDbFactory mongoDbFactory() throws Exception {
    return new SimpleMongoDbFactory(
            new Mongo(propertyResolver.getProperty("mongo.host"),
                    new Integer(propertyResolver.getProperty("mongo.port"))),
            propertyResolver.getProperty("mongo.db.name"));
}

From source file:com.streamreduce.datasource.MongoFactoryBean.java

License:Apache License

@Override
protected Mongo createInstance() throws Exception {
    if (StringUtils.hasText(this.hostname)) {
        return new Mongo(new ServerAddress(hostname, port), getMongoOptions());
    } else {/*from w  w  w .j a  va 2 s.  c  o  m*/
        return new Mongo();
    }
}

From source file:com.streamreduce.storm.MongoClient.java

License:Apache License

/**
 * Initializes the {@link Mongo} object.
 *
 * @param host     the host MongoDB is expected to be running on
 * @param port     the port MongoDB is expected to be listening on
 * @param username the username to authenticate as
 * @param password the password to the username above
 *//*from  w w  w.  j  a  v  a2s.  c  om*/
private void init(String host, int port, String username, String password) {
    this.host = host;
    this.port = port;
    this.username = username;
    this.password = password;

    logger.info("Mongo Client Connecting to " + host + ":" + port);

    try {
        MongoOptions options = new MongoOptions();
        options.autoConnectRetry = true;
        //options.connectionsPerHost = 50;
        options.connectTimeout = 1500;
        options.socketTimeout = 60000;
        options.threadsAllowedToBlockForConnectionMultiplier = 1000;
        //options.connectionsPerHost = 50; // * 5, so up to 250 can wait before it dies
        this.mongo = new Mongo(new ServerAddress(host, port), options);
    } catch (UnknownHostException e) {
        MongoException me = new MongoException("Unable to connect to Mongo at " + host + ":" + port, e);
        logger.error(me.getMessage(), me);
        throw me;
    }
}