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:mypackage.ManupulateData.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String ukey = request.getParameter("ukey");
        String docname = request.getParameter("doc");
        String db = request.getParameter("db");
        String coll = request.getParameter("coll");

        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB mongoDatabase = mongoClient.getDB(db);
        DBCollection dbcoll = mongoDatabase.getCollection(coll);
        if (ukey.equals("Update Document")) {
            String key = request.getParameter("dockey");
            String value = request.getParameter("docval");
            BasicDBObject basicDBObject = new BasicDBObject();
            basicDBObject.append("$set", new BasicDBObject().append(key, value));
            BasicDBObject serchQuery = new BasicDBObject("name", docname);
            dbcoll.update(serchQuery, basicDBObject);
            out.print("true");

        }//from  www.j  a va2 s  . c  om
        if (ukey.equals("New Document")) {
            BasicDBObject bObject = new BasicDBObject("name", docname);
            dbcoll.insert(bObject);
            out.print("true");

        }

    }
}

From source file:net.autosauler.ballance.server.model.AbstractStructuredData.java

License:Apache License

/**
 * Creates the record./*ww  w .  j  a  v a  2 s. co m*/
 * 
 * @return true, if successful
 */
private boolean createRecord() {

    boolean result = false;
    setNumber(findLastNumber());
    setCreatedate(new Date());
    onCreate();
    DB db = Database.get(getDomain());
    if (db != null) {
        BasicDBObject doc = (BasicDBObject) store(null);
        if (doc != null) {
            Database.retain();
            DBCollection coll = db.getCollection(getTableName());
            coll.insert(doc);
            Database.release();
            result = true;
        }
    }

    return result;
}

From source file:net.autosauler.ballance.server.model.AbstractStructuredData.java

License:Apache License

/**
 * Restore.//from w  w  w .  j av a2  s  .  co m
 * 
 * @param dump
 *            the dump
 */
public void restore(Element dump) {

    DB db = Database.get(getDomain());
    if (db != null) {
        DBCollection coll = db.getCollection(getTableName());
        Log.trace(getTableName());
        NodeList recordsets = dump.getElementsByTagName("records");

        for (int i = 0; i < recordsets.getLength(); i++) {
            Element recordset = (Element) recordsets.item(i);
            if (recordset.getParentNode() == dump) {
                NodeList records = recordset.getElementsByTagName("record");
                if (records.getLength() > 0) {

                    BasicDBObject q = new BasicDBObject();
                    q.put("domain", getDomain());
                    Database.retain();
                    coll.remove(q);

                    for (int j = 0; j < records.getLength(); j++) {
                        Log.trace("record");
                        BasicDBObject doc = new BasicDBObject();
                        Element record = (Element) records.item(j);
                        NodeList fields = record.getElementsByTagName("field");
                        for (int k = 0; k < fields.getLength(); k++) {
                            Element field = (Element) fields.item(k);
                            String name = field.getAttribute("name");
                            if (name.equals("domain")) {
                                doc.put("domain", getDomain());
                            } else {

                                int type = struct.getType(name);
                                String sval = field.getAttribute("value");
                                Log.error("field name=" + name + " value=" + sval);
                                doc.put(name, DataTypes.fromString(type, sval));
                            }
                        }
                        Log.trace("insert");
                        coll.insert(doc);
                    }
                }
            }
        }
        Database.release();

        onRestore(dump);
    }

}

From source file:net.autosauler.ballance.server.model.Currency.java

License:Apache License

/**
 * Receive currency values from cbr (http://www.cbr.ru).
 * /* ww w .  ja  va  2  s .  co m*/
 * @param day
 *            the day
 * @param database
 *            the database
 */
private static void receiveCBR(String day, DB database) {

    String requesturi = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=" + day;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    Document doc = null;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Log.error(ex.getMessage());
    } finally {
        try {
            doc = db.parse(requesturi);
        } catch (SAXException ex) {
            Log.error(ex.getMessage());
        } catch (IOException ex) {
            Log.error(ex.getMessage());
        } finally {
            try {
                doc.getDocumentElement().normalize();
                Log.trace("Root element " + doc.getDocumentElement().getNodeName());
                NodeList nodeLst = doc.getElementsByTagName("Valute");
                Log.trace("Information of all valutes");
                Database.retain();
                if (database == null) {
                    database = Database.get(null);
                }
                if (database != null) {
                    DBCollection coll = database.getCollection(CURRENCYTABLE);
                    Date now = new Date();
                    Long timestamp = now.getTime();
                    for (int s = 0; s < nodeLst.getLength(); s++) {

                        Node fstNode = nodeLst.item(s);

                        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

                            Element fstElmnt = (Element) fstNode;

                            // String id = fstElmnt.getAttribute("ID");
                            // String numcode = getNodeValue(fstElmnt,
                            // "NumCode");
                            String mnemo = getNodeValue(fstElmnt, "CharCode");
                            Integer nominal = Integer.parseInt(getNodeValue(fstElmnt, "Nominal"));
                            // String name = getNodeValue(fstElmnt, "Name");
                            Double value = Double
                                    .parseDouble(getNodeValue(fstElmnt, "Value").replace(',', '.'));

                            BasicDBObject dbdoc = new BasicDBObject();

                            dbdoc.put("date", day);
                            dbdoc.put("mnemo", mnemo);
                            dbdoc.put("timestamp", timestamp);
                            dbdoc.put("val", new Double(value / nominal));
                            coll.insert(dbdoc);

                        }
                    }
                }
                Database.release();

            }

            catch (Exception ex) {
                Log.error(ex.getMessage());
                Database.release();
            }
        }
    }

}

From source file:net.autosauler.ballance.server.model.GlobalSettings.java

License:Apache License

/**
 * Creates the default records./*from w ww  .  java2s.c o  m*/
 * 
 * @param db
 *            the db
 */
public static void createDefaultRecords(DB db) {

    if (db != null) {
        DBCollection coll = db.getCollection(SETTINGSTABLE);
        if (coll.getCount() < 1) {

            BasicDBObject rec = new BasicDBObject();
            rec.put("name", "default.record");
            rec.put("val", "default.value");
            coll.insert(rec);

            BasicDBObject i = new BasicDBObject();
            i.put("domain", 1);
            i.put("name", 1);
            coll.createIndex(i);

        }
    }
}

From source file:net.autosauler.ballance.server.model.GlobalSettings.java

License:Apache License

/**
 * Save changed values./*from ww  w  .  j av a  2 s .c o m*/
 */
public void save() {
    if (changed) {
        DBObject myDoc = null;
        Database.retain();
        DB db = Database.get(domain);
        if (db != null) {
            DBCollection coll = db.getCollection(SETTINGSTABLE);
            Set<String> keys = values.keySet();
            Iterator<String> i = keys.iterator();
            while (i.hasNext()) {
                String name = i.next();
                String val = values.get(name);

                BasicDBObject query = new BasicDBObject();
                query.put("name", name);
                query.put("domain", domain);
                myDoc = coll.findOne(query);
                if (myDoc != null) {
                    if (!val.equals(myDoc.get("val"))) {
                        myDoc.put("val", val);
                        coll.save(myDoc);
                    }
                } else {
                    myDoc = new BasicDBObject();
                    myDoc.put("name", name);
                    myDoc.put("domain", domain);
                    myDoc.put("val", val);
                    coll.insert(myDoc);
                }
            }
            changed = false;
        }
        Database.release();

    }
}

From source file:net.autosauler.ballance.server.model.Scripts.java

License:Apache License

/**
 * Sets the text.//from   ww  w.ja  va  2 s.  c o  m
 * 
 * @param txt
 *            the txt
 * @param andstore
 *            the andstore
 */
public void setText(String txt, boolean andstore) {
    text = txt;
    if (andstore) {
        DBObject doc = null;
        DB db = Database.get(domain);
        if (db != null) {
            Database.retain();
            DBCollection coll = db.getCollection(TABLENAME);
            BasicDBObject query = new BasicDBObject();
            query.put("domain", domain);
            query.put("name", name);

            doc = coll.findOne(query);

            if (doc != null) {
                doc.put("text", text);
                coll.save(doc);
            } else {
                doc = new BasicDBObject();
                doc.put("domain", domain);
                doc.put("name", name);
                doc.put("text", text);
                coll.insert(doc);
            }

            Database.release();

            initVM(null);

        }
    }
}

From source file:net.autosauler.ballance.server.model.User.java

License:Apache License

/**
 * Creates the new user record.//from   ww  w.j  a v a2 s .  com
 * 
 * @param restoremode
 *            the restoremode
 */
private void create(boolean restoremode) {
    Database.retain();
    DB db = Database.get(null);
    if (db != null) {
        if (!restoremode) {
            createdate = new Date();
            active = true;
            trash = false;
        }

        DBCollection coll = db.getCollection(USERSTABLE);

        BasicDBObject doc = new BasicDBObject();

        doc.put("hash", hash);
        doc.put("login", login);
        doc.put("domain", domain);
        doc.put("fullname", username);
        doc.put("roles", userrole.getRole());
        doc.put("createdate", createdate);
        doc.put("isactive", active);
        doc.put("istrash", trash);
        coll.insert(doc);

    }
    Database.release();
}

From source file:net.coreapi.mongo.documents.MessageDAO.java

License:Apache License

public void sendMessage(Message message) throws Exception {

    DBCollection dbCollection = ManagedMongoDriver.getInstance().getCollection(DATABASE_NAME, COLLECTION_NAME);

    try {//  w  w  w.  j a v  a  2s .  co m
        DBObject dbObject = MongoEntityMapper.entityToDBObject(message);
        dbCollection.insert(dbObject);
    } catch (FatalMappingException e) {
        throw new Exception("Failed to send message.");
    }
}

From source file:net.handle.server.MongoDBHandleStorage.java

License:Open Source License

/**
 * ******************************************************************
 * Sets a flag indicating whether or not this server is responsible
 * for the given naming authority.//w ww .jav a  2  s. c  o  m
 * *******************************************************************
 */

public void setHaveNA(byte authHandle[], boolean flag) throws HandleException {
    if (readOnly)
        throw new HandleException(HandleException.STORAGE_RDONLY, "Server is read-only");

    boolean currentlyHaveIt = haveNA(authHandle);
    if (currentlyHaveIt == flag)
        return;

    final DBCollection collection = getCollection(database, collection_nas);
    final BasicDBObject na = new BasicDBObject();
    na.put("na", Util.decodeString(authHandle));
    authHandle = Util.upperCase(authHandle);
    if (currentlyHaveIt) { // we already have it but need to remove it
        {
            collection.remove(na);
        }
    } else { // we need to add the NA to the database
        {
            collection.insert(na);

            // Add indices to the handle collection.
            final DBCollection handle_na = getCollection(authHandle);
            for (String index : indices) {
                handle_na.ensureIndex(index);
            }
        }
    }
}