List of usage examples for com.mongodb DBCollection save
public WriteResult save(final DBObject document)
From source file:org.datanucleus.store.mongodb.valuegenerator.IncrementGenerator.java
License:Open Source License
protected ValueGenerationBlock reserveBlock(long size) { if (size < 1) { return null; }/*from ww w. j a v a 2s .c o m*/ List oids = new ArrayList(); ManagedConnection mconn = connectionProvider.retrieveConnection(); try { DB db = (DB) mconn.getConnection(); if (!storeMgr.isAutoCreateTables() && !db.collectionExists(collectionName)) { throw new NucleusUserException(LOCALISER.msg("040011", collectionName)); } // Create the collection if not existing DBCollection dbCollection = db.getCollection(collectionName); BasicDBObject query = new BasicDBObject(); query.put("field-name", key); DBCursor curs = dbCollection.find(query); if (curs == null || !curs.hasNext()) { // No current entry for this key, so add initial entry long initialValue = 0; if (properties.containsKey("key-initial-value")) { initialValue = Long.valueOf(properties.getProperty("key-initial-value")) - 1; } BasicDBObject dbObject = new BasicDBObject(); dbObject.put("field-name", key); dbObject.put(INCREMENT_COL_NAME, new Long(initialValue)); dbCollection.insert(dbObject); } // Create the entry for this field if not existing query = new BasicDBObject(); query.put("field-name", key); curs = dbCollection.find(query); DBObject dbObject = curs.next(); Long currentValue = (Long) dbObject.get(INCREMENT_COL_NAME); long number = currentValue.longValue(); for (int i = 0; i < size; i++) { oids.add(number + i + 1); } dbObject.put(INCREMENT_COL_NAME, new Long(number + size)); dbCollection.save(dbObject); } finally { connectionProvider.releaseConnection(); } return new ValueGenerationBlock(oids); }
From source file:org.datavyu.models.db.MongoDatastore.java
License:Open Source License
@Override public Variable createVariable(final String name, final Argument.Type type) throws UserWarningException { DBCollection varCollection = mongoDB.getCollection("variables"); // Check to make sure the variable name is not already in use: Variable varTest = getVariable(name); if (varTest != null) { throw new UserWarningException("Unable to add variable, one with the same name already exists."); }//from w w w . j a v a 2 s .co m Variable v = new MongoVariable(name, new Argument("arg01", type)); varCollection.save((MongoVariable) v); for (DatastoreListener dbl : this.dbListeners) { dbl.variableAdded(v); } markDBAsChanged(); return v; }
From source file:org.datavyu.models.db.MongoVariable.java
License:Open Source License
@Override public Cell createCell() { Cell c = new MongoCell((ObjectId) this.get("_id"), deserializeArgument((BasicDBObject) this.get("type"))); DBCollection cell_collection = MongoDatastore.getDB().getCollection("cells"); cell_collection.save((MongoCell) c); for (VariableListener vl : getListeners(getID())) { vl.cellInserted(c);//from w ww . ja va2 s . c o m } MongoDatastore.markDBAsChanged(); return c; }
From source file:org.exist.mongodb.xquery.mongodb.collection.Save.java
License:Open Source License
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {/* w w w. j a v a2s . co m*/ // Verify clientid and get client String mongodbClientId = args[0].itemAt(0).getStringValue(); MongodbClientStore.getInstance().validate(mongodbClientId); MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId); // Get parameters String dbname = args[1].itemAt(0).getStringValue(); String collection = args[2].itemAt(0).getStringValue(); // Get database DB db = client.getDB(dbname); DBCollection dbcol = db.getCollection(collection); // Get data BasicDBObject data = (BasicDBObject) JSON.parse(args[3].itemAt(0).getStringValue()); // Execute save WriteResult result = dbcol.save(data); return new StringValue(result.toString()); } catch (MongoCommandException ex) { // TODO return as value? LOG.error(ex.getMessage(), ex); throw new XPathException(this, MongodbModule.MONG0005, ex.getMessage()); } catch (JSONParseException ex) { String msg = "Invalid JSON data: " + ex.getMessage(); LOG.error(msg); throw new XPathException(this, MongodbModule.MONG0004, msg); } catch (XPathException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, ex.getMessage(), ex); } catch (MongoException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage()); } catch (Throwable t) { LOG.error(t.getMessage(), t); throw new XPathException(this, MongodbModule.MONG0003, t.getMessage()); } }
From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java
License:Open Source License
@PUT @Path("/databases/{dbName}/collections/{collName}/documents/{docId}") @Override/* w w w. j a v a 2 s . c o m*/ public Response updateDocument(@PathParam("dbName") String dbName, @PathParam("collName") String collName, @PathParam("docId") String docId, org.exoplatform.mongo.entity.request.Document document, @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context SecurityContext securityContext) { if (shutdown) { return Response.status(ServerError.SERVICE_UNAVAILABLE.code()) .entity(ServerError.SERVICE_UNAVAILABLE.message()).build(); } Response response = null; String user = null; try { Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext); user = credentials.getUserName(); String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName); if (mongo.getDatabaseNames().contains(dbNamespace)) { DB db = mongo.getDB(dbNamespace); authServiceAgainstMongo(db); if (db.getCollectionNames().contains(collName)) { DBCollection dbCollection = db.getCollection(collName); String documentJson = document.getJson(); if (!StringUtils.isNullOrEmpty(documentJson)) { DBObject incomingDocument = (DBObject) JSON.parse(documentJson); DBObject query = new BasicDBObject(); query.put("_id", new ObjectId(docId)); DBObject persistedDocument = dbCollection.findOne(query); URI statusSubResource = null; try { if (persistedDocument == null) { dbCollection.insert(incomingDocument, WriteConcern.SAFE); statusSubResource = uriInfo.getBaseUriBuilder().path(MongoRestServiceImpl.class) .path("/databases/" + dbName + "/collections/" + collName + "/documents/" + ((DBObject) incomingDocument.get("_id"))) .build(); response = Response.created(statusSubResource).build(); } else { dbCollection.save(incomingDocument); statusSubResource = uriInfo .getBaseUriBuilder().path(MongoRestServiceImpl.class).path("/databases/" + dbName + "/collections/" + collName + "/documents/" + docId) .build(); response = Response.ok(statusSubResource).build(); } } catch (DuplicateKey duplicateObject) { response = Response.status(ClientError.BAD_REQUEST.code()) .entity("Document already exists and could not be created").build(); } } else { response = Response.status(ClientError.BAD_REQUEST.code()) .entity("Document JSON is required").build(); } } else { response = Response.status(ClientError.NOT_FOUND.code()) .entity(collName + " does not exist in " + dbName).build(); } } else { response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build(); } } catch (Exception exception) { response = lobException(exception, headers, uriInfo); } finally { updateStats(user, "updateDocument"); } return response; }
From source file:org.fastmongo.odm.bson.repository.BsonMongoTemplate.java
License:Apache License
/** * Saves the given document into its MongoDB collection. * * @param object the document.//from w w w.ja v a 2s. c om * @param mongoObjectId the Mongo _id for the document. * @param <T> the type of the document. * @return the saved document. */ public <T> T save(T object, Object mongoObjectId) { DBObject db = toConverter.toDbObject(object); db.put(MongoUtils.OBJECT_ID_KEY, mongoObjectId); DBCollection collection = getCollection(object.getClass()); collection.save(db); return object; }
From source file:org.keycloak.connections.mongo.updater.impl.updates.Update1_7_0.java
License:Apache License
@Override public void update(KeycloakSession session) throws ClassNotFoundException { DBCollection clients = db.getCollection("clients"); DBCursor clientsCursor = clients.find(); try {/*from w w w . j a va 2 s . c om*/ while (clientsCursor.hasNext()) { BasicDBObject client = (BasicDBObject) clientsCursor.next(); boolean directGrantsOnly = client.getBoolean("directGrantsOnly", false); client.append("standardFlowEnabled", !directGrantsOnly); client.append("implicitFlowEnabled", false); client.append("directAccessGrantsEnabled", directGrantsOnly); client.removeField("directGrantsOnly"); clients.save(client); } } finally { clientsCursor.close(); } }
From source file:org.keycloak.connections.mongo.updater.impl.updates.Update2_5_0.java
License:Apache License
@Override public void update(KeycloakSession session) { List<ProviderFactory> factories = session.getKeycloakSessionFactory() .getProviderFactories(UserStorageProvider.class); for (ProviderFactory factory : factories) { portUserFedToComponent(factory.getId()); }// w w w . ja va2s . c o m DBCollection realms = db.getCollection("realms"); try (DBCursor realmsCursor = realms.find()) { while (realmsCursor.hasNext()) { BasicDBObject realm = (BasicDBObject) realmsCursor.next(); realm.append("loginWithEmailAllowed", true); realm.append("duplicateEmailsAllowed", false); realms.save(realm); } } }
From source file:org.mca.qmass.persistence.MongoDBTupleStore.java
License:Apache License
@Override public void persist(Tuple tuple) { DBObject dbObj = new BasicDBObject(); dbObj.put("key", tuple.getKey()); dbObj.put("value", ss.serialize(tuple)); remove(tuple);//from w w w . j a v a 2 s . c om DBCollection dbColl = db.getCollection(tuple.getType()); dbColl.save(dbObj); getKeysCollection(tuple.getType()).save(new BasicDBObject("key", tuple.getKey())); log.trace("persistet " + tuple); }
From source file:org.mule.module.mongo.tools.MongoRestoreDirectory.java
License:Open Source License
private void restore() throws IOException { Validate.notNull(inputPath);//w w w .j a v a 2s . c o m List<RestoreFile> restoreFiles = getRestoreFiles(inputPath); List<RestoreFile> oplogRestores = new ArrayList<RestoreFile>(); for (RestoreFile restoreFile : restoreFiles) { if (!isOplog(restoreFile.getCollection())) { if (drop && !BackupUtils.isSystemCollection(restoreFile.getCollection())) { mongoClient.dropCollection(restoreFile.getCollection()); } DBCollection dbCollection = mongoClient.getCollection(restoreFile.getCollection()); List<DBObject> dbObjects = restoreFile.getCollectionObjects(); if (BackupUtils.isUserCollection(restoreFile.getCollection())) { for (DBObject currentUser : dbCollection.find()) { if (!dbObjects.contains(currentUser)) { dbCollection.remove(currentUser); } } } for (DBObject dbObject : dbObjects) { dbCollection.save(dbObject); } } else { oplogRestores.add(restoreFile); } } if (oplogReplay && !oplogRestores.isEmpty()) { for (RestoreFile oplogRestore : oplogRestores) { mongoClient.executeComamnd( new BasicDBObject("applyOps", filterOplogForDatabase(oplogRestore).toArray())); } } }