List of usage examples for com.mongodb.client.gridfs GridFSBucket delete
void delete(BsonValue id);
From source file:UnitTest3.java
License:Open Source License
public static void testgridfs4() throws FileNotFoundException, IOException { MongoClient mongo = new MongoClient("localhost", 27017); //DB db = mongo.getDB("JFileDB"); MongoDatabase db = mongo.getDatabase("JFileDB"); GridFSBucket gridFSBucket = GridFSBuckets.create(db); // Get the input stream InputStream streamToUploadFrom = new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8)); // Create some custom options GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024) .metadata(new Document("type", "file")); ObjectId fileId = gridFSBucket.uploadFromStream("test", streamToUploadFrom, options); streamToUploadFrom.close();/*from ww w . j a va 2s .c om*/ System.out.println("The fileId of the uploaded file is: " + fileId.toHexString()); // Get some data to write byte[] data = "some data to upload into GridFS".getBytes(StandardCharsets.UTF_8); GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sample_data"); uploadStream.write(data); uploadStream.close(); System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString()); /* gridFSBucket.find().forEach(new Block<GridFSFile>() { public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); */ /* gridFSBucket.find(eq("metadata.contentType", "image/png")).forEach( new Block<GridFSFile>() { public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); */ FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/test.txt"); gridFSBucket.downloadToStream(fileId, streamToDownloadTo); streamToDownloadTo.close(); streamToDownloadTo = new FileOutputStream("/tmp/test.txt"); GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0); gridFSBucket.downloadToStreamByName("test", streamToDownloadTo, downloadOptions); streamToDownloadTo.close(); GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId); int fileLength = (int) downloadStream.getGridFSFile().getLength(); byte[] bytesToWriteTo = new byte[fileLength]; downloadStream.read(bytesToWriteTo); downloadStream.close(); System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8)); downloadStream = gridFSBucket.openDownloadStreamByName("sample_data"); fileLength = (int) downloadStream.getGridFSFile().getLength(); bytesToWriteTo = new byte[fileLength]; downloadStream.read(bytesToWriteTo); downloadStream.close(); System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8)); gridFSBucket.rename(fileId, "test2"); gridFSBucket.delete(fileId); mongo.close(); }
From source file:com.imaginea.mongodb.services.impl.GridFSServiceImpl.java
License:Apache License
/** * Service implementation for dropping a file from GridFS. * * @param dbName Name of Database/*from w w w .j av a 2 s . c o m*/ * @param bucketName Name of GridFS Bucket * @param _id Object id of file to be deleted * @return Status message. */ public String deleteFile(String dbName, String bucketName, String _id) throws DatabaseException, DocumentException, CollectionException, ValidationException { if (dbName == null) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null"); } if (dbName.equals("")) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty"); } if (bucketName == null) { throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Bucket name is null"); } if (bucketName.equals("")) { throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Bucket Name Empty"); } String result = null; GridFSFile gridFSFile = null; try { // if (!databaseService.getDbList().contains(dbName)) { // throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS, // "DB [" + dbName + "] DOES NOT EXIST"); // } if (_id == null) { throw new DocumentException(ErrorCodes.DOCUMENT_EMPTY, "File is empty"); } ObjectId objectId = new ObjectId(_id); MongoDatabase db = mongoInstance.getDatabase(dbName); GridFSBucket gridFS = GridFSBuckets.create(db, bucketName); Document id = new Document(); id.put("_id", objectId); gridFSFile = gridFS.find(id).first(); if (gridFSFile == null) { throw new DocumentException(ErrorCodes.DOCUMENT_DOES_NOT_EXIST, "Document does not exist !"); } gridFS.delete(objectId); } catch (MongoException e) { throw new DocumentException(ErrorCodes.DOCUMENT_DELETION_EXCEPTION, e.getMessage()); } result = "File [" + gridFSFile.getFilename() + "] has been deleted."; return result; }
From source file:gridfs.GridFSTour.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes an optional single argument for the connection string * @throws FileNotFoundException if the sample file cannot be found * @throws IOException if there was an exception closing an input stream */// w ww. j av a 2 s . c o m public static void main(final String[] args) throws FileNotFoundException, IOException { MongoClient mongoClient; if (args.length == 0) { // connect to the local database server mongoClient = new MongoClient(); } else { mongoClient = new MongoClient(new MongoClientURI(args[0])); } // get handle to "mydb" database MongoDatabase database = mongoClient.getDatabase("mydb"); database.drop(); GridFSBucket gridFSBucket = GridFSBuckets.create(database); /* * UploadFromStream Example */ // Get the input stream InputStream streamToUploadFrom = new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8)); // Create some custom options GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024) .metadata(new Document("type", "presentation")); ObjectId fileId = gridFSBucket.uploadFromStream("mongodb-tutorial", streamToUploadFrom, options); streamToUploadFrom.close(); System.out.println("The fileId of the uploaded file is: " + fileId.toHexString()); /* * OpenUploadStream Example */ // Get some data to write byte[] data = "Data to upload into GridFS".getBytes(StandardCharsets.UTF_8); GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sampleData"); uploadStream.write(data); uploadStream.close(); System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString()); /* * Find documents */ gridFSBucket.find().forEach(new Block<GridFSFile>() { @Override public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); /* * Find documents with a filter */ gridFSBucket.find(eq("metadata.contentType", "image/png")).forEach(new Block<GridFSFile>() { @Override public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); /* * DownloadToStream */ FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.txt"); gridFSBucket.downloadToStream(fileId, streamToDownloadTo); streamToDownloadTo.close(); /* * DownloadToStreamByName */ streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.txt"); GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0); gridFSBucket.downloadToStreamByName("mongodb-tutorial", streamToDownloadTo, downloadOptions); streamToDownloadTo.close(); /* * OpenDownloadStream */ GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId); int fileLength = (int) downloadStream.getGridFSFile().getLength(); byte[] bytesToWriteTo = new byte[fileLength]; downloadStream.read(bytesToWriteTo); downloadStream.close(); System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8)); /* * OpenDownloadStreamByName */ downloadStream = gridFSBucket.openDownloadStreamByName("sampleData"); fileLength = (int) downloadStream.getGridFSFile().getLength(); bytesToWriteTo = new byte[fileLength]; downloadStream.read(bytesToWriteTo); downloadStream.close(); System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8)); /* * Rename */ gridFSBucket.rename(fileId, "mongodbTutorial"); /* * Delete */ gridFSBucket.delete(fileId); database.drop(); }
From source file:net.liaocy.ml4j.nlp.word2vec.Train.java
private void saveModel(String modelName, Word2Vec vec) throws IOException { MongoDatabase db = Mongo.getDB();// w w w . ja va 2 s . com GridFSBucket gridFSBucket = GridFSBuckets.create(db, "word2vecmodels"); GridFSFile gfsfi = gridFSBucket.find(new Document("filename", modelName)).first(); if (gfsfi != null) { ObjectId id = gfsfi.getObjectId(); gridFSBucket.delete(id); } try (GridFSUploadStream uploadStream = gridFSBucket.openUploadStream(modelName)) { WordVectorSerializer.writeWord2VecModel(vec, uploadStream); System.out.println("Save Model Successed!"); } }
From source file:net.liaocy.ml4j.tfidf.tfidf.java
public void save() throws IOException { MongoDatabase db = Mongo.getDB();//from w w w. jav a 2 s. com GridFSBucket gridFSBucket = GridFSBuckets.create(db, "tfidfmodels"); GridFSFile gfsfi = gridFSBucket.find(new Document("filename", this.modelName)).first(); if (gfsfi != null) { ObjectId id = gfsfi.getObjectId(); gridFSBucket.delete(id); } for (Entry<Integer, Integer> word : wordCount.entrySet()) { double idf = this.getIdf(word.getValue()); this.idfMax = Math.max(this.idfMax, idf); this.idfMin = Math.min(this.idfMax, idf); } try (GridFSUploadStream uploadStream = gridFSBucket.openUploadStream(this.modelName)) { try (ObjectOutputStream o = new ObjectOutputStream(uploadStream)) { o.writeObject(this.wordDocCount); o.writeObject(this.docCount); o.writeObject(this.wordCount); o.writeDouble(this.idfMax.doubleValue()); o.writeDouble(this.idfMin.doubleValue()); } } System.out.println("Save Model Successed!"); }
From source file:org.apache.nifi.processors.mongodb.gridfs.DeleteGridFS.java
License:Apache License
@Override public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { FlowFile input = session.get();/*from w w w . j ava 2 s.c om*/ if (input == null) { return; } final String deleteQuery = getQuery(context, input); final String queryAttribute = context.getProperty(QUERY_ATTRIBUTE).isSet() ? context.getProperty(QUERY_ATTRIBUTE).evaluateAttributeExpressions(input).getValue() : null; GridFSBucket bucket = getBucket(input, context); try { Document query = Document.parse(deleteQuery); MongoCursor cursor = bucket.find(query).iterator(); if (cursor.hasNext()) { GridFSFile file = (GridFSFile) cursor.next(); bucket.delete(file.getObjectId()); if (!StringUtils.isEmpty(queryAttribute)) { input = session.putAttribute(input, queryAttribute, deleteQuery); } session.transfer(input, REL_SUCCESS); } else { getLogger().error(String.format("Query %s did not delete anything in %s", deleteQuery, bucket.getBucketName())); session.transfer(input, REL_FAILURE); } cursor.close(); } catch (Exception ex) { getLogger().error(String.format("Error deleting using query: %s", deleteQuery), ex); session.transfer(input, REL_FAILURE); } }
From source file:org.hibernate.ogm.datastore.mongodb.binarystorage.GridFSStorageManager.java
License:LGPL
private void deleteExistingContent(String fieldName, Object documentId, GridFSBucket gridFSFilesBucket) { GridFSFindIterable results = gridFSFilesBucket .find(Filters.and(Filters.eq("filename", fileName(fieldName, documentId)))); try (MongoCursor<GridFSFile> iterator = results.iterator()) { while (iterator.hasNext()) { GridFSFile next = iterator.next(); gridFSFilesBucket.delete(next.getId()); }//w ww . j a v a 2 s . c o m } }
From source file:org.restheart.db.GridFsDAO.java
License:Open Source License
@Override public OperationResult deleteFile(final Database db, final String dbName, final String bucketName, final BsonObjectId fileId, final String requestEtag, final boolean checkEtag) { final String bucket = extractBucketName(bucketName); GridFSBucket gridFSBucket = GridFSBuckets.create(db.getDatabase(dbName), bucket); GridFSFile file = gridFSBucket.find(eq("_id", fileId)).limit(1).iterator().tryNext(); if (file == null) { return new OperationResult(HttpStatus.SC_NOT_FOUND); } else if (checkEtag) { Object oldEtag = file.getMetadata().get("_etag"); if (oldEtag != null) { if (requestEtag == null) { return new OperationResult(HttpStatus.SC_CONFLICT, oldEtag); } else if (!Objects.equals(oldEtag.toString(), requestEtag)) { return new OperationResult(HttpStatus.SC_PRECONDITION_FAILED, oldEtag); }//from w ww. ja va 2 s . c om } } gridFSBucket.delete(fileId.asObjectId().getValue()); return new OperationResult(HttpStatus.SC_NO_CONTENT); }