List of usage examples for com.mongodb DBCollection save
public WriteResult save(final DBObject document)
From source file:org.apache.sling.mongodb.impl.MongoDBResourceProvider.java
License:Apache License
/** * @see org.apache.sling.api.resource.ModifyingResourceProvider#commit(ResourceResolver) *//*from www. ja v a 2 s. com*/ public void commit(final ResourceResolver resolver) throws PersistenceException { try { for (final String deleted : this.deletedResources) { final String[] info = this.extractResourceInfo(deleted); // check if the collection still exists final DBCollection col = this.getCollection(info[0]); if (col != null) { if (col.findAndRemove(QueryBuilder.start(getPROP_PATH()).is(info[1]).get()) != null) { this.context.notifyRemoved(info); } } } for (final MongoDBResource changed : this.changedResources.values()) { final DBCollection col = this.context.getDatabase().getCollection(changed.getCollection()); if (col != null) { final String[] info = new String[] { changed.getCollection(), changed.getProperties().get(getPROP_PATH()).toString() }; // create or update? if (changed.getProperties().get(PROP_ID) != null) { col.update(QueryBuilder.start(getPROP_PATH()) .is(changed.getProperties().get(getPROP_PATH())).get(), changed.getProperties()); this.context.notifyUpdated(info); } else { // create col.save(changed.getProperties()); this.context.notifyUpdated(info); } } else { throw new PersistenceException("Unable to create collection " + changed.getCollection(), null, changed.getPath(), null); } } } finally { this.revert(resolver); } }
From source file:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public void addUserFullName(String user, String fullname) { DBCollection coll = db().getCollection(M_USERS_COLLECTION); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query);/*w ww . ja v a 2s.c om*/ if (!cursor.hasNext()) { BasicDBObject doc = new BasicDBObject(); doc.put("_id", user); doc.put("user", user); doc.put("fullname", fullname); coll.insert(doc); } else { DBObject doc = cursor.next(); doc.put("fullname", fullname); coll.save(doc); } }
From source file:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public void addUserEmail(String user, String email) { DBCollection coll = db().getCollection(M_USERS_COLLECTION); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query);//from w w w . ja v a2s.c om if (!cursor.hasNext()) { BasicDBObject doc = new BasicDBObject(); doc.put("_id", user); doc.put("user", user); doc.put("email", email); coll.insert(doc); } else { DBObject doc = cursor.next(); doc.put("email", email); coll.save(doc); } }
From source file:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public void setSpaces(String user, List<SpaceBean> spaces) { List<String> spaceIds = new ArrayList<String>(); DBCollection coll = db().getCollection(M_ROOMS_COLLECTION); for (SpaceBean bean : spaces) { String room = ChatUtils.getRoomId(bean.getId()); spaceIds.add(room);// w ww . ja v a2s. co m BasicDBObject query = new BasicDBObject(); query.put("_id", room); DBCursor cursor = coll.find(query); if (!cursor.hasNext()) { BasicDBObject doc = new BasicDBObject(); doc.put("_id", room); doc.put("space_id", bean.getId()); doc.put("displayName", bean.getDisplayName()); doc.put("groupId", bean.getGroupId()); doc.put("shortName", bean.getShortName()); doc.put("type", ChatService.TYPE_ROOM_SPACE); coll.insert(doc); } else { DBObject doc = cursor.next(); String displayName = doc.get("displayName").toString(); if (!bean.getDisplayName().equals(displayName)) { doc.put("_id", room); doc.put("displayName", bean.getDisplayName()); doc.put("groupId", bean.getGroupId()); doc.put("shortName", bean.getShortName()); coll.save(doc); } } } coll = db().getCollection(M_USERS_COLLECTION); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query); if (cursor.hasNext()) { DBObject doc = cursor.next(); doc.put("spaces", spaceIds); coll.save(doc, WriteConcern.SAFE); } else { BasicDBObject doc = new BasicDBObject(); doc.put("_id", user); doc.put("user", user); doc.put("spaces", spaceIds); coll.insert(doc); } }
From source file:org.breizhbeans.thrift.tools.thriftmongobridge.example.SimpleApp.java
License:Apache License
public static void main(String[] args) throws Exception { // --------------------------------------------------------------- // NON SECURED GET ALWAYS PASSWORD'S KEYSTORE FROM A SECURED PLACE // get it from a secured console String pwd = args[0];//from w ww .j a v a2 s . c om // get it from a console String keyProtectedPassword = args[1]; // NON SECURED GET ALWAYS PASSWORD'S KEYSTORE FROM A SECURED PLACE // --------------------------------------------------------------- // load key from the key store final KeyStore keyStore = KeyStore.getInstance("JCEKS"); keyStore.load(new FileInputStream("./keystore/secretkey.keystore"), pwd.toCharArray()); // Extract the AES key KeyStore.PasswordProtection keyPassword = new KeyStore.PasswordProtection( keyProtectedPassword.toCharArray()); KeyStore.SecretKeyEntry aesKey = (KeyStore.SecretKeyEntry) keyStore.getEntry("aesKey", keyPassword); // AES KEY byte[] key = aesKey.getSecretKey().getEncoded(); // Secured bridge initialisation // First create the wrapper SecuredWrapper securedWrapper = new SecuredWrapper(key); // Set the fields protected securedWrapper.secureThriftFields(People.class, true, People._Fields.FIRST_NAME); securedWrapper.secureThriftFields(People.class, true, People._Fields.LAST_NAME); securedWrapper.secureThriftFields(People.class, false, People._Fields.BIRTHDAY); securedWrapper.secureThriftFields(People.class, true, People._Fields.EMAIL); // Add the wrapper TBSONUnstackedProtocol.addSecuredWrapper(securedWrapper); // setup mongo // and get the collection MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("example-thrift-mongo"); DBCollection peoples = db.getCollection("people"); // write people People people = new People(); people.setFirstName("my secret first name"); people.setLastName("my secret last name"); people.setEmail("me@me"); people.setInceptionDate(System.currentTimeMillis()); people.setBirthday("1970-01-01"); people.setLanguage("en"); // serialize it DBObject dbObject = ThriftMongoHelper.thrift2DBObject(people); System.out.println("save=" + dbObject.toString()); // write the document peoples.save(dbObject); // find document by secured field BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put(People._Fields.FIRST_NAME.getFieldName(), securedWrapper.digest64("my secret first name".getBytes())); System.out.println("query=" + searchQuery.toString()); DBCursor cursor = peoples.find(searchQuery); while (cursor.hasNext()) { // print secured people DBObject dbSecuredObject = cursor.next(); System.out.println("secured=" + dbSecuredObject); // deserialize the secured object People peopleDeserialized = (People) ThriftMongoHelper.DBObject2Thrift(dbSecuredObject, People.class); System.out.println("unwrapped=" + peopleDeserialized.toString()); } // Bye System.out.println("Thrift and mongo rocks :D"); System.out.println("Destroy the collection"); peoples.drop(); }
From source file:org.broad.igv.plugin.mongocollab.MongoCollabPlugin.java
License:Open Source License
/** * Save the specified FeatDBObject to the specified collection * Does either an insert or update/*from w w w.j a va2 s . com*/ * * @param collection * @param dbFeat * @return */ static String saveFeature(DBCollection collection, DBFeature dbFeat) { String errorMessage = ""; try { if (log.isDebugEnabled()) { log.debug("Saving feature " + Locus.getFormattedLocusString(dbFeat.getChr(), dbFeat.getStart(), dbFeat.getEnd())); } WriteResult wr = collection.save(dbFeat); errorMessage = wr.getError(); } catch (Exception ex) { errorMessage = ex.getMessage(); log.error(errorMessage, ex); if (errorMessage == null) errorMessage = "" + ex; } return errorMessage; }
From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java
License:Apache License
public void update(ServerConfiguration configuration, MongoCollection mongoCollection, DBObject mongoDocument) { MongoClient mongo = null;//w w w . jav a 2 s .c o m try { String databaseName = mongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); DB database = mongo.getDB(databaseName); DBCollection collection = database.getCollection(mongoCollection.getName()); collection.save(mongoDocument); } catch (UnknownHostException ex) { throw new ConfigurationException(ex); } finally { if (mongo != null) { mongo.close(); } } }
From source file:org.codinjutsu.tools.nosql.mongo.logic.MongoClient.java
License:Apache License
public void update(ServerConfiguration configuration, MongoCollection mongoCollection, DBObject mongoDocument) { com.mongodb.MongoClient mongo = null; try {//from www . j a v a 2s. c o m String databaseName = mongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); DB database = mongo.getDB(databaseName); DBCollection collection = database.getCollection(mongoCollection.getName()); collection.save(mongoDocument); } catch (UnknownHostException ex) { throw new ConfigurationException(ex); } finally { if (mongo != null) { mongo.close(); } } }
From source file:org.datanucleus.store.mongodb.MongoDBPersistenceHandler.java
License:Open Source License
public void insertObject(ObjectProvider op) { assertReadOnlyForUpdateOfObject(op); ExecutionContext ec = op.getExecutionContext(); ManagedConnection mconn = storeMgr.getConnection(ec); try {/*from w ww . jav a 2s . c o m*/ DB db = (DB) mconn.getConnection(); AbstractClassMetaData cmd = op.getClassMetaData(); if (!storeMgr.managesClass(cmd.getFullClassName())) { // Make sure schema exists, using this connection ((MongoDBStoreManager) storeMgr).addClasses(new String[] { cmd.getFullClassName() }, ec.getClassLoaderResolver(), db); } long startTime = System.currentTimeMillis(); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.Insert.Start", op.getObjectAsPrintable(), op.getInternalObjectId())); } DBCollection collection = db.getCollection(storeMgr.getNamingFactory().getTableName(cmd)); DBObject dbObject = getDBObjectForObjectProviderToInsert(op, !cmd.pkIsDatastoreAttributed(storeMgr)); NucleusLogger.DATASTORE_NATIVE.debug("Persisting object " + op + " as " + dbObject); collection.insert(dbObject, new WriteConcern(1)); if (ec.getStatistics() != null) { ec.getStatistics().incrementNumWrites(); } if (cmd.pkIsDatastoreAttributed(storeMgr)) { // Set the identity of the object based on the datastore-generated IDENTITY strategy value if (cmd.getIdentityType() == IdentityType.DATASTORE) { // Set identity from MongoDB "_id" field ObjectId idKey = (ObjectId) dbObject.get("_id"); op.setPostStoreNewObjectId(idKey.toString()); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg( "MongoDB.Insert.ObjectPersistedWithIdentity", op.getObjectAsPrintable(), idKey)); } } else if (cmd.getIdentityType() == IdentityType.APPLICATION) { int[] pkFieldNumbers = cmd.getPKMemberPositions(); for (int i = 0; i < pkFieldNumbers.length; i++) { AbstractMemberMetaData mmd = cmd .getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNumbers[i]); if (storeMgr.isStrategyDatastoreAttributed(cmd, pkFieldNumbers[i])) { if (mmd.getType() != String.class) { // Field type must be String since MongoDB "_id" is a hex String. throw new NucleusUserException( "Any field using IDENTITY value generation with MongoDB should be of type String"); } ObjectId idKey = (ObjectId) dbObject.get("_id"); op.replaceField(mmd.getAbsoluteFieldNumber(), idKey.toString()); op.setPostStoreNewObjectId(idKey); // TODO This is incorrect if part of a composite PK if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST .debug(LOCALISER_MONGODB.msg("MongoDB.Insert.ObjectPersistedWithIdentity", op.getObjectAsPrintable(), idKey)); } } } } // Update any relation fields StoreFieldManager fieldManager = new StoreFieldManager(op, dbObject, true); int[] fieldNumbers = cmd.getRelationMemberPositions(ec.getClassLoaderResolver(), ec.getMetaDataManager()); if (fieldNumbers != null && fieldNumbers.length > 0) { op.provideFields(fieldNumbers, fieldManager); NucleusLogger.DATASTORE_NATIVE.debug("Saving object " + op + " as " + dbObject); collection.save(dbObject); if (ec.getStatistics() != null) { ec.getStatistics().incrementNumWrites(); } } } else { if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.Insert.ObjectPersisted", op.getObjectAsPrintable(), op.getInternalObjectId())); } } if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug( LOCALISER_MONGODB.msg("MongoDB.ExecutionTime", (System.currentTimeMillis() - startTime))); } if (ec.getStatistics() != null) { ec.getStatistics().incrementInsertCount(); } } catch (MongoException me) { NucleusLogger.PERSISTENCE.error("Exception inserting object " + op, me); throw new NucleusDataStoreException("Exception inserting object for " + op, me); } finally { mconn.release(); } }
From source file:org.datanucleus.store.mongodb.MongoDBPersistenceHandler.java
License:Open Source License
public void updateObject(ObjectProvider op, int[] fieldNumbers) { assertReadOnlyForUpdateOfObject(op); ExecutionContext ec = op.getExecutionContext(); ManagedConnection mconn = storeMgr.getConnection(ec); try {//from ww w . j av a 2 s. c o m DB db = (DB) mconn.getConnection(); long startTime = System.currentTimeMillis(); AbstractClassMetaData cmd = op.getClassMetaData(); if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { StringBuilder fieldStr = new StringBuilder(); for (int i = 0; i < fieldNumbers.length; i++) { if (i > 0) { fieldStr.append(","); } fieldStr.append(cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]).getName()); } NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER_MONGODB.msg("MongoDB.Update.Start", op.getObjectAsPrintable(), op.getInternalObjectId(), fieldStr.toString())); } DBCollection collection = db.getCollection(storeMgr.getNamingFactory().getTableName(cmd)); DBObject dbObject = MongoDBUtils.getObjectForObjectProvider(collection, op, true, true); if (dbObject == null) { if (cmd.isVersioned()) { throw new NucleusOptimisticException("Object with id " + op.getInternalObjectId() + " and version " + op.getTransactionalVersion() + " no longer present"); } else { throw new NucleusDataStoreException( "Could not find object with id " + op.getInternalObjectId()); } } int[] updatedFieldNums = fieldNumbers; if (cmd.isVersioned()) { // Version object so calculate version to store with Object currentVersion = op.getTransactionalVersion(); VersionMetaData vermd = cmd.getVersionMetaDataForClass(); Object nextVersion = VersionHelper.getNextVersion(vermd.getVersionStrategy(), currentVersion); op.setTransactionalVersion(nextVersion); if (vermd.getFieldName() != null) { // Update the version field value AbstractMemberMetaData verMmd = cmd.getMetaDataForMember(vermd.getFieldName()); op.replaceField(verMmd.getAbsoluteFieldNumber(), nextVersion); boolean updatingVerField = false; for (int i = 0; i < fieldNumbers.length; i++) { if (fieldNumbers[i] == verMmd.getAbsoluteFieldNumber()) { updatingVerField = true; } } if (!updatingVerField) { // Add the version field to the fields to be updated updatedFieldNums = new int[fieldNumbers.length + 1]; System.arraycopy(fieldNumbers, 0, updatedFieldNums, 0, fieldNumbers.length); updatedFieldNums[fieldNumbers.length] = verMmd.getAbsoluteFieldNumber(); } } else { // Update the stored surrogate value String fieldName = storeMgr.getNamingFactory().getColumnName(cmd, ColumnType.VERSION_COLUMN); dbObject.put(fieldName, nextVersion); } } StoreFieldManager fieldManager = new StoreFieldManager(op, dbObject, false); op.provideFields(updatedFieldNums, fieldManager); if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) { NucleusLogger.DATASTORE_NATIVE.debug("Updating object " + op + " as " + dbObject); } collection.save(dbObject); if (ec.getStatistics() != null) { ec.getStatistics().incrementNumWrites(); ec.getStatistics().incrementUpdateCount(); } if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) { NucleusLogger.DATASTORE_PERSIST.debug( LOCALISER_MONGODB.msg("MongoDB.ExecutionTime", (System.currentTimeMillis() - startTime))); } } catch (MongoException me) { NucleusLogger.PERSISTENCE.error("Exception updating object " + op, me); throw new NucleusDataStoreException("Exception updating object for " + op, me); } finally { mconn.release(); } }