List of usage examples for com.mongodb.gridfs GridFSInputFile getId
public Object getId()
From source file:UnitTest3.java
License:Open Source License
public static int testgridfs() { long time1;// w ww . j av a2s .c o m long time2; long time3; long time4; try { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("JFileDB"); // TODO JFileMetaDataTable should be in MetaDB database DBCollection collection = db.getCollection("JFileMetaDataTable"); String newFileName = "com.dilmus.scabi.testdata.in.App.class"; File jFile = new File("/home/anees/workspace/testdata/in/App.class"); // create a JFileTable namespace GridFS gfsj = new GridFS(db, "JFileTable"); // get file from local drive GridFSInputFile gfsFile = gfsj.createFile(jFile); // set a new filename for identify purpose gfsFile.setFilename(newFileName); gfsFile.setContentType("class"); // jar, zip, war // save the image file into mongoDB gfsFile.save(); // Let's create a new JSON document with some "metadata" information BasicDBObject info = new BasicDBObject(); info.put("DBHost", "localhost"); info.put("DBPort", "27017"); info.put("JFileName", newFileName); info.put("JFileID", gfsFile.getId()); info.put("JFileMD5", gfsFile.getMD5()); collection.insert(info, WriteConcern.ACKNOWLEDGED); // print the result DBCursor cursor = gfsj.getFileList(); while (cursor.hasNext()) { System.out.println(cursor.next()); } DBCursor cursor2 = collection.find(); while (cursor2.hasNext()) { System.out.println(cursor2.next()); } // get file by it's filename GridFSDBFile jForOutput = gfsj.findOne(newFileName); // save it into a new image file jForOutput.writeTo("/home/anees/workspace/testdata/out/AppOut.class"); // remove the file from mongoDB // gfsj.remove(gfsj.findOne(newFileName)); System.out.println("Done"); mongo.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; }
From source file:com.bluedragon.mongo.gridfs.Add.java
License:Open Source License
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException { // Get the necessary Mongo references DB db = getDB(_session, argStruct);/*from w w w . ja va2s . co m*/ GridFS gridfs = getGridFS(_session, argStruct, db); GridFSInputFile fsInputFile = null; // Get the file information String filename = getNamedStringParam(argStruct, "filename", null); if (filename == null) throwException(_session, "please specify a filename"); try { cfData ftmp = getNamedParam(argStruct, "file", null); if (ftmp.getDataType() == cfData.CFBINARYDATA) { fsInputFile = gridfs.createFile(((cfBinaryData) ftmp).getByteArray()); } else { // The 'file' parameter is a string, which means it is a path to a file File inputFile = new File(ftmp.getString()); if (!inputFile.exists()) throwException(_session, "File:" + inputFile + " does not exist"); if (!inputFile.isFile()) throwException(_session, "File:" + inputFile + " is not a valid file"); fsInputFile = gridfs.createFile(inputFile); } } catch (IOException e) { throwException(_session, e.getMessage()); } fsInputFile.setFilename(filename); String contenttype = getNamedStringParam(argStruct, "contenttype", null); if (contenttype != null) fsInputFile.setContentType(contenttype); String _id = getNamedStringParam(argStruct, "_id", null); if (_id != null) fsInputFile.setId(_id); // Get and set the metadata cfData mTmp = getNamedParam(argStruct, "metadata", null); if (mTmp != null) fsInputFile.setMetaData(getDBObject(mTmp)); // Save the Object try { fsInputFile.save(); return new cfStringData(fsInputFile.getId().toString()); } catch (MongoException me) { throwException(_session, me.getMessage()); return null; } }
From source file:com.cloudbees.demo.beesshop.service.MongoDbFileStorageService.java
License:Apache License
@Nonnull public String storeFile(InputStream in, String contentType) { String extension = defaultFileExtensionByContentType.get(contentType); String fileName = Joiner.on(".").skipNulls().join(Math.abs(random.nextLong()), extension); GridFSInputFile file = gridFS.createFile(in, fileName); file.setContentType(contentType);// w w w. ja va 2 s . c o m file.save(); return "gridfs://" + gridFS.getBucketName() + "/" + file.getId().toString(); }
From source file:com.cognifide.aet.vs.artifacts.ArtifactsDAOMongoDBImpl.java
License:Apache License
@Override public String saveArtifact(DBKey dbKey, InputStream data, String contentType) { String resultObjectId = null; GridFS gfs = getGridFS(dbKey);/* w ww.j ava2s . c o m*/ if (gfs != null) { GridFSInputFile file = gfs.createFile(data); if (file != null) { file.setContentType(contentType); file.save(); resultObjectId = file.getId().toString(); } } return resultObjectId; }
From source file:com.englishtown.integration.java.IntegrationTestHelper.java
License:Open Source License
public static String createFile(JsonObject config, String bucket) { GridFS gridFS = IntegrationTestHelper.getGridFS(config, bucket); GridFSInputFile inputFile = gridFS .createFile(IntegrationTestHelper.class.getResourceAsStream("/EF_Labs_ENG_logo.JPG")); inputFile.setContentType(DEFAULT_CONTENT_TYPE); inputFile.setFilename(DEFAULT_FILENAME); inputFile.setChunkSize(DEFAULT_CHUNK_SIZE); inputFile.setMetaData(DEFAULT_METADATA); inputFile.save();//w w w . jav a 2 s .c o m return inputFile.getId().toString(); }
From source file:com.ikanow.infinit.e.api.social.sharing.ShareHandler.java
License:Open Source License
/** * Saves bytes into a new gridfile//from w w w. j av a2 s .c o m * * @param bytes * @return the id of the gridfile */ private ObjectId saveGridFile(byte[] bytes) { try { GridFSInputFile file = DbManager.getSocial().getShareBinary().createFile(bytes); file.save(); return (ObjectId) file.getId(); } catch (Exception ex) { } return null; }
From source file:com.ikanow.infinit.e.api.social.sharing.ShareHandler.java
License:Open Source License
/** * Updates a gridfile with new data, if binaryId is null * the old gridfile did not exist, just create a new one. * /*from w ww.j a v a2s.c om*/ * If it is not null, will remove and create a new entry. * * @param binaryId * @param bytes * @return */ private ObjectId updateGridFile(ObjectId binaryId, byte[] bytes) { try { //create new file GridFSInputFile file = DbManager.getSocial().getShareBinary().createFile(bytes); file.save(); //remove old file if exists (this way if file throws an exception we don't lose the old file) if (binaryId != null) DbManager.getSocial().getShareBinary().remove(binaryId); return (ObjectId) file.getId(); } catch (Exception ex) { } return binaryId; }
From source file:com.imaginea.mongodb.services.GridFSServiceImpl.java
License:Apache License
/** * Service implementation for uploading a file to GridFS. * * @param dbName Name of Database//w w w .j av a 2s.c o m * @param bucketName Name of GridFS Bucket * @param formData formDataBodyPart of the uploaded file * @param inputStream inputStream of the uploaded file * @param dbInfo Mongo Db Configuration provided by user to connect to. * @returns Success message with additional file details such as name, size, * download url & deletion url as JSON Array string. */ public JSONArray insertFile(String dbName, String bucketName, String dbInfo, InputStream inputStream, FormDataBodyPart formData) throws DatabaseException, CollectionException, DocumentException, ValidationException { mongoInstance = mongoInstanceProvider.getMongoInstance(); if (dbName == null) { throw new EmptyDatabaseNameException("Database name is null"); } if (dbName.equals("")) { throw new EmptyDatabaseNameException("Database Name Empty"); } if (bucketName == null) { throw new EmptyCollectionNameException("Bucket name is null"); } if (bucketName.equals("")) { throw new EmptyCollectionNameException("Bucket Name Empty"); } JSONArray result = new JSONArray(); FormDataContentDisposition fileData = formData.getFormDataContentDisposition(); try { if (!mongoInstance.getDatabaseNames().contains(dbName)) { throw new UndefinedDatabaseException("DB [" + dbName + "] DOES NOT EXIST"); } GridFS gridFS = new GridFS(mongoInstance.getDB(dbName), bucketName); GridFSInputFile fsInputFile = gridFS.createFile(inputStream, fileData.getFileName()); fsInputFile.setContentType(formData.getMediaType().toString()); fsInputFile.save(); JSONObject obj = new JSONObject(); obj.put("name", fsInputFile.getFilename()); obj.put("size", fsInputFile.getLength()); obj.put("url", String.format("services/%s/%s/gridfs/getfile?id=%s&download=%s&dbInfo=%s&ts=%s", dbName, bucketName, fsInputFile.getId().toString(), false, dbInfo, new Date())); obj.put("delete_url", String.format("services/%s/%s/gridfs/dropfile?id=%s&dbInfo=%s&ts=%s", dbName, bucketName, fsInputFile.getId().toString(), dbInfo, new Date().getTime())); obj.put("delete_type", "GET"); result.put(obj); } catch (Exception e) { CollectionException ce = new CollectionException(ErrorCodes.UPLOAD_FILE_EXCEPTION, "UPLOAD_FILE_EXCEPTION", e.getCause()); throw ce; } return result; }
From source file:com.impetus.client.mongodb.MongoDBClient.java
License:Apache License
/** * On persist GFS./*from w w w. ja va2s.co m*/ * * @param entity * the entity * @param entityId * the entityId * @param entityMetadata * the entity metadata * @param isUpdate * the is update */ private void onPersistGFS(Object entity, Object entityId, EntityMetadata entityMetadata, boolean isUpdate) { KunderaGridFS gfs = new KunderaGridFS(mongoDb, entityMetadata.getTableName()); if (!isUpdate) { GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity, kunderaMetadata, isUpdate); saveGridFSFile(gfsInputFile, entityMetadata); } else { Object val = handler.getLobFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata); String md5 = MongoDBUtils.calculateMD5(val); GridFSDBFile outputFile = findGridFSDBFile(entityMetadata, entityId); // checking MD5 of the file to be updated with the file saved in DB if (md5.equals(outputFile.getMD5())) { DBObject metadata = handler.getMetadataFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata); outputFile.setMetaData(metadata); outputFile.save(); } else { // GFSInput file is created corresponding to the entity to be // merged with a new ObjectID() GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity, kunderaMetadata, isUpdate); ObjectId updatedId = (ObjectId) gfsInputFile.getId(); DBObject metadata = gfsInputFile.getMetaData(); // updated file is saved in DB saveGridFSFile(gfsInputFile, entityMetadata); // last version of file is deleted DBObject query = new BasicDBObject("_id", outputFile.getId()); gfs.remove(query); // newly added file is found using its _id outputFile = gfs.findOne(updatedId); // Id of entity (which is saved in metadata) is updated to its // actual Id metadata.put(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(), entityId); outputFile.setMetaData(metadata); // output file is updated outputFile.save(); } } }
From source file:com.kurento.kmf.repository.internal.repoimpl.mongo.MongoRepository.java
License:Open Source License
@Override public RepositoryItem createRepositoryItem() { GridFSInputFile dbFile = gridFS.createFile(); dbFile.setFilename(dbFile.getId().toString()); return createRepositoryItem(dbFile); }