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:org.opentestsystem.delivery.testadmin.scheduling.DbDumpImporter.java

License:Open Source License

public static void loadDefaultBsonDumps(final MongoTemplate mongoTemplate) {

    InputStream is = null;// w w w .  j a v  a2 s . co m
    byte[] buf = new byte[32768];
    byte[] lengthBuf = new byte[4];
    int len;
    int readLen = 0;

    for (String collection : DB_DUMP_COLLECTIONS) {

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        is = DbDumpImporter.class.getResourceAsStream("/db-dump/" + collection + ".bson");

        List<DBObject> bsonList = new ArrayList<DBObject>();

        try {

            while ((len = is.read(lengthBuf, 0, LENGTH_BYTES)) > 0) {
                ArrayUtils.reverse(lengthBuf);

                readLen = new BigInteger(lengthBuf).intValue();

                ArrayUtils.reverse(lengthBuf);

                System.arraycopy(lengthBuf, 0, buf, 0, 4);

                len = is.read(buf, 4, readLen - LENGTH_BYTES);

                if (len > 0) {
                    bsonList.add(new BasicDBObject(BSON.decode(buf).toMap()));
                }

                Arrays.fill(buf, (byte) 0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        DBCollection dbCollection = mongoTemplate.getCollection(collection);
        dbCollection.insert(bsonList);

    }

    if (is != null) {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:org.primefaces.examples.view.insertInventory.java

public void insertItemData() throws UnknownHostException {
    DB db = (new MongoClient("localhost", 27017)).getDB("shopData"); // JDBC
    if (!itemName.equals("") && !producerName.equals("") && !barcode.equals("")) {
        DBCollection dBCollection = db.getCollection("Item"); // Requesting to get collection
        DBObject dBObject = new BasicDBObject(); //Creating a database object
        //inserting items to Java Database Object
        dBObject.put("itemName", itemName);
        dBObject.put("manufacturerName", producerName);
        dBObject.put("itemCode", barcode);
        dBCollection.insert(dBObject);
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "SUCCESS:", "Added Item Successful"));
        resetData();/*from  w w  w.j av  a 2  s.  c o m*/
    } else {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR:", "Submition Failed"));
    }
}

From source file:org.primefaces.examples.view.insertInventory.java

public void insertItemDetailData() throws UnknownHostException {
    DB db = (new MongoClient("localhost", 27017)).getDB("shopData");
    if (!itemDetailCode.equals("") && qty != 0 && !itemCode.equals("")) {
        DBCollection dBCollection = db.getCollection("ItemDetails");
        DBObject dBObject = new BasicDBObject();
        dBObject.put("itemDetailCode", itemDetailCode);
        dBObject.put("itemCode", itemCode);
        dBObject.put("Quantity", qty);
        dBCollection.insert(dBObject);
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "SUCCESS:", "Added Item Details Successful"));
    }/*from   w w  w.j  av a2s.c  o  m*/
}

From source file:org.primefaces.examples.view.insertJSON.java

public void insertJSON() throws UnknownHostException {
    DB db = (new MongoClient("localhost", 27017).getDB("shopData"));
    if (inputJSON.startsWith("{") && inputJSON.endsWith("}")) {
        DBCollection dBCollection = db.getCollection("Item");
        dBCollection.insert((DBObject) JSON.parse(inputJSON));
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "SUCCESS:", "Submited JSON"));
    } else {//from  ww w .  j a v a  2 s  . c  o m
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR:", "Not a valide JSON"));
    }
}

From source file:org.restheart.db.PropsFixer.java

License:Open Source License

/**
 *
 * @param dbName/* ww w . j  a  v  a2  s  . co m*/
 * @param collName
 * @return
 * @throws MongoException
 */
public boolean addCollectionProps(String dbName, String collName) throws MongoException {

    DBObject dbmd = dbsDAO.getDatabaseProperties(dbName, false);

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

    DBObject md = dbsDAO.getCollectionProperties(dbName, collName, false);

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

    // check if collection has data
    DB db = dbsDAO.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.".concat(collName));
    properties.put("_created_on", now.toString());
    properties.put("_etag", timestamp);

    DBCollection propsColl = dbsDAO.getCollection(dbName, "_properties");

    propsColl.insert(properties);

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

From source file:org.restheart.db.PropsFixer.java

License:Open Source License

/**
 *
 * @param dbName/*  w w w  .ja  v a2 s  . c om*/
 * @return
 */
public boolean addDbProps(String dbName) {
    if (!dbsDAO.existsDatabaseWithName(dbName)) {
        return false;
    }

    DBObject dbmd = dbsDAO.getDatabaseProperties(dbName, false);

    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 = dbsDAO.getCollection(dbName, "_properties");

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

From source file:org.sipfoundry.sipxconfig.openacd.OpenAcdProvisioningContextImpl.java

License:Open Source License

protected void storeCommand(BasicDBObject command) {
    try {//  w  w w.ja va 2s . c o m
        DB openAcdDb = m_db.getDb();
        openAcdDb.requestStart();
        DBCollection commandsCollection = openAcdDb.getCollection("commands");
        WriteResult result = commandsCollection.insert(command);
        String error = result.getError();
        if (error != null) {
            throw new UserException("&msg.mongo.write.error", error);
        }
        openAcdDb.requestDone();
    } catch (Exception ex) {
        throw new UserException("&msg.cannot.connect");
    }
}

From source file:org.socialhistoryservices.security.MongoTokenStore.java

License:Open Source License

public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    // insert into oauth_access_token (token_id, token, authentication_id, authentication, refresh_token) values (?, ?, ?, ?, ?)
    String refreshToken = null;/*from  w  ww  . jav a  2  s .c om*/
    if (token.getRefreshToken() != null) {
        refreshToken = token.getRefreshToken().getValue();
    }
    final String name = (authentication.getUserAuthentication() == null) ? null
            : authentication.getUserAuthentication().getName();
    final BasicDBObject document = new BasicDBObject();
    document.put("token_id", token.getValue());
    document.put("token", serialize(token));
    document.put("authentication_id", null);
    document.put("authentication", serialize(authentication));
    document.put("refresh_token", refreshToken);
    document.put("name", name);
    final DBCollection collection = getCollection(OAUTH_ACCESS_TOKEN);
    collection.insert(document);
}

From source file:org.socialhistoryservices.security.MongoTokenStore.java

License:Open Source License

public void storeRefreshToken(ExpiringOAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {

    // insert into oauth_refresh_token (token_id, token, authentication) values (?, ?, ?)
    final BasicDBObject document = new BasicDBObject();
    document.put("token_id", refreshToken.getValue());
    document.put("token", serialize(refreshToken));
    document.put("authentication", serialize(authentication));
    final DBCollection collection = getCollection(OAUTH_REFRESH_TOKEN);
    collection.insert(document);
}

From source file:org.springframework.data.document.mongodb.MongoTemplate.java

License:Apache License

protected Object insertDBObject(String collectionName, final DBObject dbDoc) {

    // DATADOC-95: This will prevent null objects from being saved.
    //if (dbDoc.keySet().isEmpty()) {
    //return null;
    //}//from w w w  .  j ava2 s .  c om

    //TODO: Need to move this to more central place
    if (dbDoc.containsField("_id")) {
        if (dbDoc.get("_id") instanceof String) {
            ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id"));
            if (oid != null) {
                dbDoc.put("_id", oid);
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "insert DBObject containing fields: " + dbDoc.keySet() + " in collection: " + collectionName);
    }
    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            if (writeConcern == null) {
                collection.insert(dbDoc);
            } else {
                collection.insert(dbDoc, writeConcern);
            }
            return dbDoc.get(ID);
        }
    });
}