List of usage examples for com.mongodb.gridfs GridFSInputFile setFilename
public void setFilename(final String filename)
From source file:org.mule.module.mongo.api.MongoClientImpl.java
License:Open Source License
public DBObject createFile(final InputStream content, final String filename, final String contentType, final DBObject metadata) { Validate.notNull(filename);// ww w .ja v a 2s.c o m Validate.notNull(content); final GridFSInputFile file = getGridFs().createFile(content); file.setFilename(filename); file.setContentType(contentType); if (metadata != null) { file.setMetaData(metadata); } file.save(); return file; }
From source file:org.mule.transport.mongodb.MongoDBMessageDispatcher.java
License:Open Source License
protected Object doDispatchToBucket(MuleEvent event, String bucket) throws Exception { DB db;//from w w w .j a v a2 s.c o m if (StringUtils.isNotBlank(connector.getMongoURI().getDatabase())) { db = connector.getMongo().getDB(connector.getMongoURI().getDatabase()); } else { db = connector.getMongo().getDB(connector.getMongoURI().getDatabase()); } GridFS gridFS = new GridFS(db, bucket); db.requestStart(); Object payload = event.getMessage().getPayload(); GridFSInputFile file = null; if (payload instanceof File) { file = gridFS.createFile((File) payload); } if (payload instanceof InputStream) { file = gridFS.createFile((InputStream) payload); } if (payload instanceof byte[]) { file = gridFS.createFile((byte[]) payload); } if (payload instanceof String) { file = gridFS.createFile(((String) payload).getBytes()); } if (file == null) { throw new MongoDBException( String.format("Cannot persist objects of type %s to GridFS", payload.getClass())); } String filename = event.getMessage().getOutboundProperty(MongoDBConnector.PROPERTY_FILENAME, ""); if (StringUtils.isNotBlank(filename)) { logger.debug("Setting filename on GridFS file to: " + filename); file.setFilename(filename); } String contentType = event.getMessage().getOutboundProperty(MongoDBConnector.PROPERTY_CONTENT_TYPE, ""); if (StringUtils.isBlank(contentType) && event.getEndpoint().getProperties().containsKey("contentType")) { contentType = (String) event.getEndpoint().getProperty("contentType"); } if (StringUtils.isNotBlank(contentType)) { logger.debug("Setting contentType on GridFS file to: " + contentType); file.setContentType(contentType); } logger.debug("Attempting to save file: " + file.getFilename()); Date startTime = new Date(); file.save(); Date endTime = new Date(); long elapsed = endTime.getTime() - startTime.getTime(); logger.debug(String.format("GridFS file %s saved in %s seconds", file.getId(), elapsed / 1000.0)); try { file.validate(); } catch (MongoException ex) { if (ex.getMessage().startsWith("md5 differ")) { logger.error("MD5 checksum mismatch while saving the file. " + "This may be the real deal or is possibly an issue that keeps recurring with" + " some releases of the Java driver "); } } ObjectId id = (ObjectId) file.getId(); event.getMessage().setOutboundProperty(MongoDBConnector.PROPERTY_OBJECT_ID, id.toStringMongod()); db.requestDone(); return file; }
From source file:org.nuxeo.ecm.core.storage.mongodb.GridFSBinaryManager.java
License:Apache License
@Override protected Binary getBinary(InputStream in) throws IOException { // save the file to GridFS GridFSInputFile inputFile = gridFS.createFile(in, true); inputFile.save();//from w w w. j a va2 s . c o m // now we know length and digest String digest = inputFile.getMD5(); // if the digest is already known then reuse it instead GridFSDBFile dbFile = gridFS.findOne(digest); if (dbFile == null) { // no existing file, set its filename as the digest inputFile.setFilename(digest); inputFile.save(); } else { // file already existed, no need for the temporary one gridFS.remove(inputFile); } return new GridFSBinary(digest, blobProviderId); }
From source file:org.sipfoundry.commons.userdb.profile.UserProfileServiceImpl.java
License:Open Source License
@Override public void saveAvatar(String userName, InputStream originalIs) throws AvatarUploadException { ByteArrayOutputStream os = null; InputStream is = null;// w w w . j a v a2s. co m try { BufferedImage originalImage = ImageIO.read(originalIs); BufferedImage thumbnail = Thumbnails.of(originalImage).crop(Positions.CENTER).size(128, 128) .asBufferedImage(); os = new ByteArrayOutputStream(); ImageIO.write(thumbnail, "png", os); is = new ByteArrayInputStream(os.toByteArray()); String fileName = String.format(AVATAR_NAME, userName); GridFS avatarFS = new GridFS(m_template.getDb()); avatarFS.remove(fileName); GridFSInputFile gfsFile = avatarFS.createFile(is); gfsFile.setFilename(fileName); gfsFile.save(); } catch (Exception ex) { throw new AvatarUploadException(ex); } finally { IOUtils.closeQuietly(originalIs); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
From source file:org.springframework.data.mongodb.gridfs.GridFsTemplate.java
License:Apache License
public GridFSFile store(InputStream content, String filename, String contentType, DBObject metadata) { Assert.notNull(content);/*ww w . java2 s .c om*/ GridFSInputFile file = getGridFs().createFile(content); if (filename != null) { file.setFilename(filename); } if (metadata != null) { file.setMetaData(metadata); } if (contentType != null) { file.setContentType(contentType); } file.save(); return file; }
From source file:org.teiid.translator.mongodb.MongoDBExecutionFactory.java
License:Open Source License
/** * Mongodb only supports certain data types, Teiid need to serialize them in other compatible * formats, and convert them back while reading them. * @param value/*from w w w. ja va2s .c o m*/ * @return */ public Object convertToMongoType(Object value, DB mongoDB, String fqn) throws TranslatorException { if (value == null) { return null; } try { if (value instanceof BigDecimal) { return ((BigDecimal) value).doubleValue(); } else if (value instanceof BigInteger) { return ((BigInteger) value).doubleValue(); } else if (value instanceof Character) { return ((Character) value).toString(); } else if (value instanceof java.sql.Date) { return new java.util.Date(((java.sql.Date) value).getTime()); } else if (value instanceof java.sql.Time) { return new java.util.Date(((java.sql.Time) value).getTime()); } else if (value instanceof java.sql.Timestamp) { return new java.util.Date(((java.sql.Timestamp) value).getTime()); } else if (value instanceof BinaryType) { return new Binary(((BinaryType) value).getBytes()); } else if (value instanceof byte[]) { return new Binary((byte[]) value); } else if (value instanceof Blob) { String uuid = UUID.randomUUID().toString(); GridFS gfs = new GridFS(mongoDB, fqn); GridFSInputFile gfsFile = gfs.createFile(((Blob) value).getBinaryStream()); gfsFile.setFilename(uuid); gfsFile.save(); return uuid; } else if (value instanceof Clob) { String uuid = UUID.randomUUID().toString(); GridFS gfs = new GridFS(mongoDB, fqn); GridFSInputFile gfsFile = gfs.createFile(((Clob) value).getAsciiStream()); gfsFile.setFilename(uuid); gfsFile.save(); return uuid; } else if (value instanceof SQLXML) { String uuid = UUID.randomUUID().toString(); GridFS gfs = new GridFS(mongoDB, fqn); GridFSInputFile gfsFile = gfs.createFile(((SQLXML) value).getBinaryStream()); gfsFile.setFilename(uuid); gfsFile.save(); return uuid; } else if (value instanceof Object[]) { BasicDBList list = new BasicDBList(); for (Object obj : (Object[]) value) { list.add(obj); } return list; } return value; } catch (SQLException e) { throw new TranslatorException(e); } }
From source file:rmi_video.VideoServer.java
@Override public boolean addVideo(VideoData d) throws RemoteException { try {/*from w w w. j a v a 2 s . com*/ //Conexao com mongoDB MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("VideoDatabase"); try (FileOutputStream fos = new FileOutputStream("/Users/philcr/Documents/" + d.getFileName())) { fos.write(d.getData()); } File videoFile = new File("/Users/philcr/Documents/" + d.getFileName()); GridFS gfsVideo = new GridFS(db, "video"); //Cria e salva o arquivo no DB pelo GridFS GridFSInputFile gfsFile = gfsVideo.createFile(videoFile); gfsFile.setId(new ObjectId()); //Utiliza a criao de ID do mongo gfsFile.put("videoId", d.getId()); //Utiliza nosso metodo de ID gfsFile.setFilename(d.getFileName()); gfsFile.save(); //Exclui o arquivo local boolean deletedFlag = videoFile.delete(); if (!deletedFlag) { System.err.println("File could not be deleted!"); } mongoClient.close(); return true; } catch (UnknownHostException ex) { Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (FileNotFoundException ex) { Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex); return false; } }
From source file:tango.mongo.ImageManager.java
License:Open Source License
public synchronized boolean saveInputImage(ObjectId xpId, ObjectId field_id, int fileRank, ImageHandler img, boolean flushImage) { if (img == null) return false; //IJ.log("file: "+img.getTitle()+" size:"+img.getSizeInMb()+ " available memory:"+Core.getAvailableMemory()+ " please free memory"); double scaleZ = img.getScaleZ(); String unit = img.getUnit();/*ww w. j a v a 2 s.c om*/ String title = img.getTitle(); MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); try { byte[] data = img.getBinaryData(); if (data == null) { IJ.log("couldn't save image:" + title); return false; } if (flushImage) img.flush(); GridFSInputFile gfi = this.gfsField.get(xpId).createFile(data); data = null; gfi.setFilename(title); gfi.put("field_id", field_id); gfi.put("fileRank", fileRank); gfi.put("pixelDepth", scaleZ); gfi.put("unit", unit); removeInputImage(xpId, field_id, fileRank); gfi.save(); gfi.getOutputStream().close(); return true; } catch (Exception e) { exceptionPrinter.print(e, "Error while saving image: " + title, true); } catch (OutOfMemoryError e) { int MEGABYTE = (1024 * 1024); MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); long maxMemory = heapUsage.getMax() / MEGABYTE; long usedMemory = heapUsage.getUsed() / MEGABYTE; IJ.log("Error while saving image:" + title + " Out of memory. Memory Use :" + usedMemory + "M/" + maxMemory + "M"); } return false; }
From source file:tango.mongo.ImageManager.java
License:Open Source License
public synchronized void saveNucleusImage(ObjectId xpId, ObjectId nucleus_id, int fileIdx, int fileType, ImageHandler img) {/*from w w w. jav a 2s. co m*/ if (img == null) return; removeNucleusImage(xpId, nucleus_id, fileIdx, fileType); try { GridFSInputFile gfi = this.gfsNucleus.get(xpId).createFile(img.getBinaryData()); gfi.setFilename(img.getImagePlus().getShortTitle()); gfi.put("nucleus_id", nucleus_id); gfi.put("fileIdx", fileIdx); gfi.put("fileType", fileType); gfi.put("pixelDepth", img.getScaleZ()); gfi.put("unit", img.getUnit()); gfi.save(); if (gfi != null) gfi.getOutputStream().close(); } catch (Exception e) { exceptionPrinter.print(e, "Error while saving image:" + img.getTitle(), Core.GUIMode); } }
From source file:tango.mongo.MongoConnector.java
License:Open Source License
public synchronized boolean saveInputImage(ObjectId field_id, int fileRank, ImageHandler img, boolean flushImage) { if (img == null) { return false; }//from w ww .j a v a 2s. c o m //IJ.log("file: "+img.getTitle()+" size:"+img.getSizeInMb()+ " available memory:"+Core.getAvailableMemory()+ " please free memory"); double scaleZ = img.getScaleZ(); String unit = img.getUnit(); String title = img.getTitle(); MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); try { byte[] data = img.getBinaryData(); if (data == null) { IJ.log("couldn't save image:" + title); return false; } if (flushImage) { img.flush(); } GridFSInputFile gfi = this.gfsField.createFile(data); data = null; gfi.setFilename(title); gfi.put("field_id", field_id); gfi.put("fileRank", fileRank); gfi.put("pixelDepth", scaleZ); gfi.put("unit", unit); removeInputImage(field_id, fileRank); gfi.save(); gfi.getOutputStream().close(); return true; } catch (Exception e) { exceptionPrinter.print(e, "Error while saving image: " + title, true); } catch (OutOfMemoryError e) { int MEGABYTE = (1024 * 1024); MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); long maxMemory = heapUsage.getMax() / MEGABYTE; long usedMemory = heapUsage.getUsed() / MEGABYTE; IJ.log("Error while saving image:" + title + " Out of memory. Memory Use :" + usedMemory + "M/" + maxMemory + "M"); } return false; }