Example usage for com.mongodb DBCollection insert

List of usage examples for com.mongodb DBCollection insert

Introduction

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

Prototype

public WriteResult insert(final List<? extends DBObject> documents) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:com.sanaldiyar.projects.nanohttpd.mongodbbasedsessionhandler.MongoDBBasedSessionHandler.java

/**
 * Request parser for session. Gets and builds session information
 *
 * @param request the request//from  ww w .j  av a  2 s  . c o m
 * @return session manager
 */
@Override
public NanoSessionManager parseRequest(Request request) {
    MongoDBBasedSessionManager nanoSessionManager = null;
    DBObject session = null;
    String sessionid = null;
    for (Cookie cookie : request.getCookies()) {
        if (cookie.getName().equals(SESSIONCOOKIEID)) {
            sessionid = cookie.getValue();
            break;
        }
    }
    DBCollection sessions = managers.getCollection("sessions");
    if (sessionid != null) {
        DBCursor cursor = sessions.find(new BasicDBObject("sessionid", sessionid));
        List<DBObject> result = cursor.toArray();
        cursor.close();
        if (result.size() == 1) {
            session = result.get(0);
        }
        if (session != null) {
            if (((Date) session.get("expires")).getTime() <= new Date().getTime()) {
                sessions.remove(new BasicDBObject().append("sessionid", sessionid));
                session = null;
            }
        }
    }
    if (session == null) {
        do {
            sessionid = new BigInteger(128, srng).toString(32);
        } while (sessions.findOne(new BasicDBObject().append("sessionid", sessionid)) != null
                && !sessionid.equals("0"));
        session = new BasicDBObject();
        nanoSessionManager = new MongoDBBasedSessionManager(session);
        nanoSessionManager.setSessionID(sessionid);
        sessions.insert(session);
    } else {
        nanoSessionManager = new MongoDBBasedSessionManager(session);
    }
    return nanoSessionManager;
}

From source file:com.se452group4.db.InsertDriver.java

public static void main(String[] args) throws UnknownHostException {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("Shop");
    DBCollection clothCollection = db.getCollection("Clothes");
    BasicDBObject cloth1 = new BasicDBObject();
    cloth1.put("clothesId", 1000);
    cloth1.put("type", "Dress");
    cloth1.put("brandName", "Zara");
    cloth1.put("price", 100);
    cloth1.put("gender", "Women");
    cloth1.put("quantity", 5);
    clothCollection.insert(cloth1);

    DBCursor clothCursor = clothCollection.find(cloth1);
    while (clothCursor.hasNext()) {
        System.out.println(clothCursor.next());
    }//from  w w  w .  jav a2s  .c o m
}

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

License:Open Source License

/**
 * Common handler for creating new objects. Assures that errors are handled in a
 * consistent way.//w  ww  . j  av  a  2 s.c o  m
 * 
 * @param collection
 * @param object
 * @throws SiteWhereException
 */
public static void insert(DBCollection collection, DBObject object) throws SiteWhereException {
    WriteResult result = collection.insert(object);
    if (!result.getLastError().ok()) {
        throw new SiteWhereException("Error during insert: " + result.getLastError().toString());
    }
}

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

public static void main(String args[]) {

    try {//w  ww .j a  v a 2  s  . com

        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.smbtec.xo.mongodb.impl.MongoDbDocumentManager.java

License:Apache License

@Override
public MongoDbDocument createEntity(TypeMetadataSet<EntityTypeMetadata<DocumentMetadata>> types,
        Set<String> discriminators,
        Map<PrimitivePropertyMethodMetadata<PropertyMetadata>, Object> exampleEntity) {
    if (types.size() > 1) {
        throw new XOException("multiple inheritance not allowed");
    }//from   www.j  a va  2  s  .c  o  m
    EntityTypeMetadata<DocumentMetadata> typeMetadata = Iterables.getOnlyElement(types);
    BasicDBObject document = new BasicDBObject();
    for (Entry<PrimitivePropertyMethodMetadata<PropertyMetadata>, Object> properties : exampleEntity
            .entrySet()) {
        String key = properties.getKey().getDatastoreMetadata().getName();
        Object v = properties.getValue();
        document.put(key, v);
    }

    String label = typeMetadata.getDatastoreMetadata().getDiscriminator();
    DBCollection collection = database.getCollection(label);
    collection.insert(document);
    return new MongoDbDocument(document, label);
}

From source file:com.softinstigate.restheart.db.DocumentDAO.java

License:Open Source License

/**
 *
 *
 * @param exchange//  w  w w  .j ava 2 s.c om
 * @param dbName
 * @param collName
 * @param content
 * @param requestEtag
 * @return the HttpStatus code to retrun
 */
public static int upsertDocumentPost(HttpServerExchange exchange, String dbName, String collName,
        DBObject content, ObjectId requestEtag) {
    DB db = DBDAO.getDB(dbName);

    DBCollection coll = db.getCollection(collName);

    ObjectId timestamp = new ObjectId();
    Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());

    if (content == null) {
        content = new BasicDBObject();
    }

    content.put("_etag", timestamp);
    content.put("_created_on", now.toString()); // make sure we don't change this field

    Object _id = content.get("_id");
    content.removeField("_id");

    if (_id == null) {
        ObjectId id = new ObjectId();
        content.put("_id", id);

        coll.insert(content);

        exchange.getResponseHeaders().add(HttpString.tryFromString("Location"),
                getReferenceLink(exchange.getRequestURL(), id.toString()).toString());

        return HttpStatus.SC_CREATED;
    }

    BasicDBObject idQuery = new BasicDBObject("_id", getId("" + _id));

    // we use findAndModify to get the @created_on field value from the existing document
    // we need to put this field back using a second update 
    // it is not possible in a single update even using $setOnInsert update operator
    // in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic) 
    DBObject oldDocument = coll.findAndModify(idQuery, null, null, false, content, false, true);

    if (oldDocument != null) { // upsert
        Object oldTimestamp = oldDocument.get("_created_on");

        if (oldTimestamp == null) {
            oldTimestamp = now.toString();
            logger.warn("properties of document /{}/{}/{} had no @created_on field. set to now", dbName,
                    collName, _id.toString());
        }

        // need to readd the @created_on field 
        BasicDBObject createdContet = new BasicDBObject("_created_on", "" + oldTimestamp);
        createdContet.markAsPartialObject();
        coll.update(idQuery, new BasicDBObject("$set", createdContet), true, false);

        // check the old etag (in case restore the old document version)
        return optimisticCheckEtag(coll, oldDocument, requestEtag, HttpStatus.SC_OK);
    } else { // insert
        return HttpStatus.SC_CREATED;
    }
}

From source file:com.softinstigate.restheart.db.PropsFixer.java

License:Open Source License

/**
 *
 * @param dbName// w w w.j  a v a2 s  .  c o  m
 * @param collName
 * @return
 * @throws MongoException
 */
public static boolean addCollectionProps(String dbName, String collName) throws MongoException {
    DBObject dbmd = DBDAO.getDbProps(dbName);

    if (dbmd == null) {
        // db must exists with properties
        return false;
    }

    DBObject md = CollectionDAO.getCollectionProps(dbName, collName);

    if (md != null) // properties exists
    {
        return false;
    }

    // check if collection has data
    DB db = DBDAO.getDB(dbName);

    if (!db.collectionExists(collName)) {
        return false;
    }

    // ok, create the properties
    DBObject properties = new BasicDBObject();

    ObjectId timestamp = new ObjectId();
    Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());

    properties.put("_id", "_properties");
    properties.put("_created_on", now.toString());
    properties.put("_etag", timestamp);

    DBCollection coll = CollectionDAO.getCollection(dbName, collName);

    coll.insert(properties);

    logger.info("properties added to {}/{}", dbName, collName);
    return true;
}

From source file:com.softinstigate.restheart.db.PropsFixer.java

License:Open Source License

/**
 *
 * @param dbName/*from  w w  w .j av  a  2 s  .co  m*/
 * @return
 */
public static boolean addDbProps(String dbName) {
    if (!DBDAO.doesDbExists(dbName)) {
        return false;
    }

    DBObject dbmd = DBDAO.getDbProps(dbName);

    if (dbmd != null) // properties exists
    {
        return false;
    }

    // ok, create the properties
    DBObject properties = new BasicDBObject();

    ObjectId timestamp = new ObjectId();
    Instant now = Instant.ofEpochSecond(timestamp.getTimestamp());

    properties.put("_id", "_properties");
    properties.put("_created_on", now.toString());
    properties.put("_etag", timestamp);

    DBCollection coll = CollectionDAO.getCollection(dbName, "_properties");

    coll.insert(properties);
    logger.info("properties added to {}", dbName);
    return true;
}

From source file:com.softlyinspired.jlw.connections.dbConnection.java

License:Open Source License

public int create() {
    /* Create a new connection */
    if (this.checkExisting()) {
        return 1;
    }/*  www. j  a v  a  2  s.  c o m*/

    try {
        /* Get the database collection */
        DBCollection connectionColl = repoConnection.getConnectionCollection();
        if (connectionColl == null) {
            return -1;
        }

        // search for the id
        BasicDBObject query = new BasicDBObject();
        query.put("name", connectionName);
        query.put("driver", connectionDriver);
        query.put("url", connectionURL);
        query.put("password", connectionPassword);
        query.put("user", connectionUser);

        try {
            connectionColl.insert(query);
        } catch (Exception e) {
            System.out.println("Error creating concern");
        }

    } catch (Exception e) {
        System.out.println("error in checking script during create");
    }
    return 0;
}

From source file:com.softlyinspired.jlw.reports.ReportReference.java

License:Open Source License

public int create() {
    /* Create a new report reference */

    if (this.checkExisting()) {
        return 1;
    }//from  w  ww  .j av a 2 s  . c om

    try {
        /* Get the database collection */
        DBCollection reportColl = repoConnection.getReportsCollection();
        if (reportColl == null) {
            return -1;
        }

        // search for the id
        BasicDBObject query = new BasicDBObject();

        query.put("reportId", reportId);
        query.put("name", reportName);
        query.put("type", reportType);
        query.put("description", reportDescription);
        query.put("category", reportCategory);
        query.put("reportLocation", reportLocation);
        try {
            reportColl.insert(query);
        } catch (Exception e) {
            System.out.println("Error defining report");
        }

    } catch (Exception e) {
        System.out.println("error during report reference create");
    }
    return 0;
}