public String execute() throws IOException { String[] fids = fid.split(","); File[] files = new File[fids.length]; String username = (String) httpSession.get("username"); System.out.println("fids: " + Arrays.toString(fids)); for (int i = 0; i < files.length; i++) { GridFSDBFile gridFSDBFile = boxService.download(fids[i]); files[i] = new File(gridFSDBFile.getFilename()); gridFSDBFile.writeTo(files[i]); } filename = "/tmp/download.zip"; ZipFileUtil.compressFiles2Zip(files, filename); inputStream = new FileInputStream(new File(filename)); filename = "download.zip"; return SUCCESS; }
private String isExistedImage(BundleEntry entry) { GridFS gridFS = getInstance(); DBObject query = new BasicDBObject(); query.put("crc",entry.crc); query.put("md5_source",entry.md5); GridFSDBFile _current = gridFS.findOne(query); //根据MD5值查询,检测是否存在 if(_current == null) { return null; } String format = (String)_current.get("format"); if(format.startsWith(".")) { return _current.getFilename() + format; } return _current.getFilename() + "." + format; }
@Override public GridFSDBFile getFile(String boardId, String fileId) throws FileNotFoundException { User user = getAuthorizedUser(); Board board = boardRepository.findOne(boardId); if(!user.hasRole(UserRole.ADMIN) && !board.getOwner().equals(user) && !board.getUsers().contains(user)) { log.warn("User {} has no rights on board {}", user.getUsername(), boardId); throw new AccessDeniedException("User does not have rights to access this board"); } FSFile file = filesRepository.findOne(fileId); if ( file == null ) { log.debug("No File with given ID " + fileId + " found."); throw new FileNotFoundException(); } return fileStore.read(file); }
@Override public Boolean storeBlob(CallingContext context, String docPath, InputStream newContent, Boolean append) { GridFS gridFS = getGridFS(); GridFSInputFile file; if (!append) { gridFS.remove(docPath); file = createNewFile(docPath, newContent); } else { GridFSDBFile existing = gridFS.findOne(docPath); if (existing != null) { try { file = updateExisting(context, docPath, newContent, gridFS, existing); } catch (IOException e) { file = null; log.error(String.format("Error while appending to docPath %s: %s", docPath, ExceptionToString.format(e))); } } else { file = createNewFile(docPath, newContent); } } return file != null; }
@Override public InputStream getBlob(CallingContext context, String docPath) { GridFS gridFS = getGridFS(); String lockKey = createLockKey(gridFS, docPath); LockHandle lockHandle = grabLock(context, lockKey); InputStream retVal = null; try { GridFSDBFile file = gridFS.findOne(docPath); if (file != null) { retVal = file.getInputStream(); } } finally { releaseLock(context, lockKey, lockHandle); } return retVal; }
@RequestMapping(method = POST) @PreAuthorize("isAuthenticated()") @ResponseBody @ResponseStatus(CREATED) public String create( @RequestParam("assetData") final MultipartFile assetData ) throws IOException { // Check duplicates final GridFSDBFile file = this.gridFs.findOne(Query.query(Criteria.where("filename").is(assetData.getOriginalFilename()))); if (file != null) { throw new DataIntegrityViolationException(String.format("Asset with name '%s' already exists", assetData.getOriginalFilename())); } else { try (InputStream usedStream = TikaInputStream.get(assetData.getInputStream())) { MediaType mediaType = null; try { mediaType = MediaType.parse(tika.detect(usedStream, assetData.getOriginalFilename())); } catch (IOException e) { log.warn("Could not detect content type", e); } this.gridFs.store(assetData.getInputStream(), assetData.getOriginalFilename(), Optional.ofNullable(mediaType).map(MediaType::toString).orElse(null)); return assetData.getOriginalFilename(); } } }
@RequestMapping({"/{filename:.+}"}) public void get( @PathVariable final String filename, final HttpServletRequest request, final HttpServletResponse response ) throws IOException { final GridFSDBFile file = this.gridFs.findOne(Query.query(Criteria.where("filename").is(filename))); if (file == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { final int cacheForDays = 365; response.setHeader("Content-Type", file.getContentType()); response.setHeader("Content-Disposition", String.format("inline; filename=\"%s\"", file.getFilename())); response.setHeader("Expires", now(of("UTC")).plusDays(cacheForDays).format(RFC_1123_DATE_TIME)); response.setHeader("Cache-Control", String.format("max-age=%d, %s", TimeUnit.DAYS.toSeconds(cacheForDays), "public")); file.writeTo(response.getOutputStream()); response.flushBuffer(); } }
@Test public void createShouldThrowException() throws Exception { final MockMultipartFile multipartFile = new MockMultipartFile("assetData", this.getClass().getResourceAsStream("/eu/euregjug/site/assets/asset.png")); when(this.gridFsTemplate.findOne(any(Query.class))).thenReturn(mock(GridFSDBFile.class)); mvc .perform( fileUpload("/api/assets") .file(multipartFile) ) .andExpect(status().isConflict()) .andExpect(content().string("")); verify(this.gridFsTemplate).findOne(any(Query.class)); verifyNoMoreInteractions(this.gridFsTemplate); }
@Override public Id createPreviewPdfFile(GridFSDBFile file) { for (DocumentConverter converter : getConverters()) { if (converter.canConvert(file.getContentType())) { ByteArrayOutputStream stream = converter.convert(file.getInputStream()); if (stream == null) return null; Id id = app.nextId(); createGridFsFile(id, new ByteArrayInputStream(stream.toByteArray()), "preview_" + file.getFilename(), "application/pdf"); return id; } } return null; }
@Override public void createPreview(MediaAssetFile mediaAssetFile, GridFSDBFile file) { if (file.getContentType().contains("image")) { mediaAssetFile.setPreviewImageId(mediaAssetFile.getId()); mediaAssetFile.setPreviewDocumentMimeType(mediaAssetFile.getMimeType()); } else if (file.getContentType().contains("pdf")) { mediaAssetFile.setPreviewDocId(mediaAssetFile.getId()); mediaAssetFile.setPreviewDocumentMimeType("aplication/pdf"); mediaAssetFile.setPreviewImageId(createPreviewImage(file)); mediaAssetFile.setPreviewDocumentMimeType("image/png"); } else { Id docId = createPreviewPdfFile(file); if (docId != null) { mediaAssetFile.setPreviewDocId(docId); mediaAssetFile.setPreviewDocumentMimeType("aplication/pdf"); Id imgId = createPreviewImage(mediaAssetService.getGridFsFile(docId)); if (imgId != null) { mediaAssetFile.setPreviewImageId(imgId); mediaAssetFile.setPreviewDocumentMimeType("image/png"); } } } }
@Override public MediaAsset update(Id mediaAssetId, InputStream inputStream, String filename) { String basename = FilenameUtils.getBaseName(filename); String extension = FilenameUtils.getExtension(filename); filename = Strings.slugify2(basename) + "." + extension; String mimeType = getMimeType(filename); MediaAssetFile mediaAssetFile = app.model(MediaAssetFile.class); mediaAssetFile.setId(app.nextId()); mediaAssetFile.setMediaAssetId(mediaAssetId); mediaAssetFile.setName(filename); mediaAssetFile.setMimeType(mimeType); mediaAssetFile.setActive(false); mediaAssetFile .setSize(createGridFsFile(mediaAssetFile.getId(), inputStream, filename, mediaAssetFile.getMimeType())); GridFSDBFile file = getGridFsFile(mediaAssetFile.getId()); mediaAssetFile.setMetadata(importMetadata(file.getInputStream())); mediaAssetHelper.createPreview(mediaAssetFile, file); mediaAssetFiles.add(mediaAssetFile); return mediaAssets.findById(MediaAsset.class, mediaAssetId); }
@Path("/validate") @POST public void validate(@PathParam("baseScreenshotId") String baseScreenshotId, @PathParam("newScreenshotId") String newScreenshotId) { logger.info(String.format("Validating: baseScreenshotId: '%s', newScreenshotId: ''%s", baseScreenshotId, newScreenshotId)); String diffImageFileName = String.format("%s|%s|%s", baseScreenshotId, newScreenshotId, "-differences"); ObjectId newBaseScreenshotId = new ObjectId(newScreenshotId); // pull the diff image from the DB, mark the field for processed screenshots to true BasicDBObject diffImageQuery = new BasicDBObject(); diffImageQuery.put("filename", diffImageFileName); GridFSDBFile diffFile = GFS_DIFF_PHOTOS.find(diffImageQuery).iterator().next(); diffFile.put("screenshotsHaveBeenReviewed", true); diffFile.save(); // update the image id of the base screenshot with the id of the new screenshot BasicDBObject baseQuery = new BasicDBObject(); baseQuery.put("imageId", new ObjectId(baseScreenshotId)); DBObject baseObject = BASE_IMAGES.find(baseQuery).next(); baseObject.put("imageId", newBaseScreenshotId); BASE_IMAGES.save(baseObject); }
@GET @Produces("image/png") public Response getScreenshotFromDb(@PathParam("collection") String collection, @PathParam("_id") String imgId, @Context Request request) { EndpointUtil.printClientInfo(request); BasicDBObject screenshotQuery = new BasicDBObject(); screenshotQuery.put("_id", new ObjectId(imgId)); GridFSDBFile screenshotFound = null; switch (collection.toLowerCase()) { case "photo": screenshotFound = GFS_PHOTO.findOne(screenshotQuery); break; case "diff_photos": screenshotFound = GFS_DIFF_PHOTOS.findOne(screenshotQuery); break; } return Response.ok().entity(screenshotFound.getInputStream()).build(); }
@Override public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { Mongo mongo = spec.connectionConfiguration().setupMongo(); try { GridFS gridfs = spec.connectionConfiguration().setupGridFS(mongo); DBCursor cursor = createCursor(gridfs); long size = 0; while (cursor.hasNext()) { GridFSDBFile file = (GridFSDBFile) cursor.next(); size += file.getLength(); } return size; } finally { mongo.close(); } }
@Override public AttachmentData getAttachment(AttachmentId attachmentId) { final GridFSDBFile attachment = getAttachmentGrid().findOne(attachmentId.serialise()); if (attachment == null) { return null; } else { return new AttachmentData() { @Override public InputStream getInputStream() throws IOException { return attachment.getInputStream(); } @Override public long getSize() { return attachment.getLength(); } }; } }
@RequestMapping(value = "/getPhoto/{code}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<byte[]> getCodableDTO(@PathVariable("code") String code) { System.out.println("finding getCodableDTO: code: " + code); try { //List<GridFSDBFile> result = gridFsTemplate.find(new Query().addCriteria(Criteria.where("filename").is(code))); GridFSDBFile gridFsFile = gridFsTemplate.findOne(new Query().addCriteria(Criteria.where("_id").is(code))); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); return new ResponseEntity<>(IOUtils.toByteArray(gridFsFile.getInputStream()), headers, HttpStatus.CREATED); } catch (Exception e) { System.out.println("eeeeeeeey get photo " + e); return null; } }
@RequestMapping(value = "/getPhoto/small/{code}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<byte[]> getCodableDTOSmall(@PathVariable("code") String code) { System.out.println("finding getCodableDTO: code: " + code); try { GridFSDBFile gridFsFile = gridFsTemplate.findOne(new Query().addCriteria(Criteria.where("_id").is(code))); //GridFSDBFile gridFsFile = gridFsTemplate.findOne(new Query().addCriteria(Criteria.where("metadata.size").is("small").and("metadata.parent").is(code))); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); return new ResponseEntity<>(IOUtils.toByteArray(gridFsFile.getInputStream()), headers, HttpStatus.CREATED); } catch (Exception e) { System.out.println("eeeeeeeey get photo " + e); return null; } }
/** * Download a file from the GridFS / MongoDB by a given filename. */ @RequestMapping(value = "/files/**") public ResponseEntity<?> downloadFile(HttpServletRequest request) { String completePath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); String fileName = completePath.replaceFirst("/public/files", ""); // find file in grid fs / mongo db GridFSDBFile gridFsFile = this.fileService.findFile(fileName); if (gridFsFile == null) { return ResponseEntity.notFound().build(); } HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.CONTENT_DISPOSITION, "filename=" + removeFolders(gridFsFile.getFilename())); // Return Status 200 or 304 if not modified return ResponseEntity.ok() .headers(headers) .contentLength(gridFsFile.getLength()) .cacheControl(CacheControl.maxAge(0, TimeUnit.MILLISECONDS).mustRevalidate() .cachePrivate().cachePublic()) .eTag(String.valueOf(gridFsFile.getUploadDate().getTime())) .lastModified(gridFsFile.getUploadDate().getTime()) .contentType(MediaType.parseMediaType(gridFsFile.getContentType())) .body(new InputStreamResource(gridFsFile.getInputStream())); }
private boolean readFile(GridFSDBFile dbFile, OutputStream os) throws IOException { InputStream is = null; try { is = dbFile.getInputStream(); byte data[] = new byte[4096]; int len = 0; while ((len = is.read(data, 0, data.length)) > 0) { os.write(data, 0, len); } return true; } finally { if (is != null) { is.close(); } } }
public void sendFile(String path, HttpServletResponse response) throws IOException { GridFSDBFile file = getFile(path); if (file == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("File %s does not exist", path)); } else { String contentType = file.getContentType(); if (contentType != null) { response.setContentType(contentType); } OutputStream os = null; try { readFile(file, os = response.getOutputStream()); } catch (Exception e) { System.err.println("Send error: " + path); } finally { if (os != null) { os.close(); } } } }
public TEIFile nextTeiDocument() { InputStream teiStream = null; TEIFile tei = new TEIFile(); DBObject obj = cursor.next(); tei.setRepositoryDocId((String) obj.get("repositoryDocId")); tei.setFileName(tei.getRepositoryDocId() + ".tei.xml"); tei.setDocumentType((String) obj.get("documentType")); tei.setAnhalyticsId((String) obj.get("anhalyticsId")); tei.setSource((String) obj.get("source")); tei.setRepositoryDocVersion((String) obj.get("version")); GridFSDBFile binaryfile = gfs.findOne(tei.getFileName()); tei.setFileType((String) binaryfile.getContentType()); indexFile++; teiStream = binaryfile.getInputStream(); try { tei.setTei(IOUtils.toString(teiStream)); teiStream.close(); } catch (IOException ex) { logger.error(ex.getMessage(), ex.getCause()); } return tei; }
/** * Updates already existing tei with new (more enriched one, fulltext..). */ public void updateTei(String newTei, String repositoryDocId, String collection) { try { GridFS gfs = new GridFS(db, collection); GridFSDBFile gdf = gfs.findOne(repositoryDocId + ".tei.xml"); GridFSInputFile gfsNew = gfs.createFile(new ByteArrayInputStream(newTei.getBytes()), true); gfsNew.put("uploadDate", gdf.getUploadDate()); gfsNew.setFilename(gdf.get("repositoryDocId") + ".tei.xml"); gfsNew.put("repositoryDocId", gdf.get("repositoryDocId")); gfsNew.put("documentType", gdf.get("documentType")); gfsNew.put("anhalyticsId", gdf.get("anhalyticsId")); gfsNew.put("source", gdf.get("source")); gfsNew.save(); gfs.remove(gdf); } catch (Exception e) { logger.error(e.getMessage(), e.getCause()); } }
/** * Check if the document has been already grobidified. */ public boolean isGrobidified(String repositoryDocId, String version) { GridFS gfs = new GridFS(db, MongoCollectionsInterface.GROBID_TEIS); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("repositoryDocId", repositoryDocId); whereQuery.put("version", version); List<GridFSDBFile> fs = null; boolean result = false; fs = gfs.find(whereQuery); if (fs.size() > 0) { result = true; } else { result = false; } return result; }
@Test public void testFetchDocumentsByDate() throws ParserConfigurationException, IOException, InterruptedException { System.out.println("Test harvesting.."); HarvestProperties.setOaiUrl("http://api.archives-ouvertes.fr/oai/hal"); OAIHarvester oaih = new OAIHarvester(mm); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); //cal.add(Calendar.DATE, -1); String date = dateFormat.format(cal.getTime()); Utilities.updateDates(date, date); Runnable fooRunner = new MyRunnable(oaih, date); Thread fooThread = new Thread(fooRunner); fooThread.start(); Thread.sleep(60000); fooThread.interrupt(); List<GridFSDBFile> f = (new GridFS(db, MongoManager.ADDITIONAL_TEIS)).find((DBObject)null); assertTrue(f.size() > 1); }
private List<Page> readPageSet(Map<Integer, Object> pageId,int pageStart,int pageEnd) { List<Page> pages = new ArrayList<>(); GridFSDBFile gridFSDBFile; for (Map.Entry<Integer, Object> integerStringEntry : pageId.entrySet()) { if(integerStringEntry.getKey() >= pageStart && integerStringEntry.getKey() <= pageEnd){ gridFSDBFile = gridFsTemplate.findOne(createQueryFindById(integerStringEntry.getValue())); pages.add(PageBuilder.newPageBuilder() .bytes(gridFSDBFile2ByteArray(gridFSDBFile)) .fileName(gridFSDBFile.getFilename()) .id(gridFSDBFile.getId().toString()) .build()); } } return pages; }
public TreeMap<String,SubjectsBucket> createAllBuckets(int distributionID) { TreeMap<String,SubjectsBucket> result = new TreeMap<String,SubjectsBucket>(); // get collection GridFS gfs = new GridFS(DBSuperClass2.getDBInstance(), SUBJECTS_BUCKET_COLLECTION_NAME); // create query BasicDBObject distribution = new BasicDBObject(DISTRIBUTION_ID, distributionID); // make query List<GridFSDBFile> buckets = gfs.find(distribution); for (GridFSDBFile f : buckets) { BloomFilterI filter = BloomFilterFactory.newBloomFilter(); try { filter.readFrom(new BufferedInputStream(f.getInputStream())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } result.put(f.get(FIRST_RESOURCE).toString(),new SubjectsBucket(filter, f.get(FIRST_RESOURCE).toString(), f.get(LAST_RESOURCE).toString())); } return result; }
/** * Converts a GridFSDBFile object into a struct * * @param filefs * @return */ protected cfStructData toStruct( GridFSDBFile filefs ){ cfStructData s = new cfStructData(); if ( filefs == null ) return s; s.put("_id", new cfStringData(filefs.getId().toString()) ); s.put("chunkSize", new cfNumberData(filefs.getChunkSize()) ); s.put("length", new cfNumberData(filefs.getLength()) ); s.put("md5", new cfStringData(filefs.getMD5()) ); s.put("filename", new cfStringData(filefs.getFilename()) ); s.put("contentType", new cfStringData(filefs.getContentType()) ); s.put("uploadDate", new cfDateData(filefs.getUploadDate()) ); s.put("metadata", tagUtils.convertToCfData( filefs.getMetaData() ) ); return s; }
@Override public ImmutableMap<String, BlobMetaData> listBlobsByPrefix(@Nullable String blobNamePrefix) throws IOException { ImmutableMap.Builder<String, BlobMetaData> blobsBuilder = ImmutableMap.builder(); List<GridFSDBFile> files; if (blobNamePrefix != null) { files = blobStore.gridFS().find(new BasicDBObject("filename", "/^" + buildKey(blobNamePrefix) + "/")); } else { files = blobStore.gridFS().find(new BasicDBObject("filename", "/^" + keyPath + "/")); } if (files != null && !files.isEmpty()) { for (GridFSDBFile file : files) { String name = file.getFilename().substring(keyPath.length()); blobsBuilder.put(name, new PlainBlobMetaData(name, file.getLength())); } } return blobsBuilder.build(); }
private int fetchBlobFromMongo() throws Exception { GridFSDBFile gridFile = gridFS.findOne(new BasicDBObject("md5", blobId)); long fileLength = gridFile.getLength(); long start = blobOffset; long end = blobOffset + length; if (end > fileLength) { end = fileLength; } length = (int) (end - start); if (start < end) { InputStream is = gridFile.getInputStream(); if (blobOffset > 0) { IOUtils.skipFully(is, blobOffset); } IOUtils.readFully(is, buffer, bufferOffset, length); is.close(); return length; } return -1; }
@Test public void testResizeStoreMongo() throws Exception { JsonObject json = new JsonObject() .putString("action", "resize") .putString("src", SRC_IMG) .putString("dest", "gridfs://fs") .putNumber("width", 300); eb.send(ADDRESS, json, new Handler<Message<JsonObject>>() { public void handle(Message<JsonObject> reply) { assertEquals("ok", reply.body().getString("status")); String id = reply.body().getString("output"); GridFS fs = new GridFS(db, "fs"); GridFSDBFile f = fs.findOne((DBObject) JSON.parse("{\"_id\":\"" + id + "\"}")); assertEquals("image/jpeg", f.getContentType()); testComplete(); } }); }
/** * 保存文件到Mongo中 * @param file 文件对象 * @param id id_ 自定义序列 * @param metaData 元数据类型 Key Value * @return */ public boolean concatGridFile(File file, Object id, DBObject metaData){ GridFSInputFile gridFSInputFile; DBObject query = new BasicDBObject("_id", id); GridFSDBFile gridFSDBFile = myFS.findOne(query); if(gridFSDBFile!= null) return false; try { gridFSInputFile = myFS.createFile(file); gridFSInputFile.put("_id",id); gridFSInputFile.setFilename(file.getName()); gridFSInputFile.setMetaData(metaData); gridFSInputFile.setContentType(file.getName().substring(file.getName().lastIndexOf("."))); gridFSInputFile.save(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
public static byte[] readFileFromGridFS(GridFSDBFile file) { InputStream is = file.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { byte bytes[] = new byte[BUFFER_SIZE]; int read = -1; while ((read = is.read(bytes)) != -1) { baos.write(bytes, 0, read); } return baos.toByteArray(); } catch (Exception e) { } return null; }
/** * @param imageName * unique image name * @return return an image mapped from the given name, null if one can't be loaded */ public static BufferedImage loadImage(final String imageName) throws IOException { BufferedImage image = null; final List<GridFSDBFile> files = images.find(imageName); if (files != null && files.size() > 0) { final Date uploadDate = files.get(0).getUploadDate(); final long timeDiff = Math.abs(uploadDate.getTime() - System.currentTimeMillis()); final long limitTimeDiff = 1000L * 60 * 60 * 24 * 30; if (timeDiff > limitTimeDiff) { final ObjectId id = (ObjectId)files.get(0).getId(); images.remove(id); return null; } try(final InputStream inputStream = files.get(0).getInputStream()){ image = ImageIO.read(inputStream); } } return image; }
private AttachmentData fileToAttachmentData(final GridFSDBFile attachmant) { if (attachmant == null) { return null; } else { return new AttachmentData() { @Override public InputStream getInputStream() throws IOException { return attachmant.getInputStream(); } @Override public long getSize() { return attachmant.getLength(); } }; } }
@Override public Blob getBlob(String container, String name, GetOptions options) { GridFSIdentifier identifier = parseGridFSIdentifier(container); if (!identifier.storeExists(mongo)) { throw new ContainerNotFoundException(container, "could not find expected collections in database"); } // TODO: support get options if (options != null && ( options.getIfMatch() != null || options.getIfNoneMatch() != null || options.getIfModifiedSince() != null || options.getIfUnmodifiedSince() != null || !options.getRanges().isEmpty() )) { throw new IllegalArgumentException("Get options are not currently supported by this provider"); } GridFS gridFS = identifier.connect(mongo); // TODO: cache GridFSDBFile dbFile = gridFS.findOne(name); if (dbFile == null) { return null; } Blob blob = dbFileToBlob.apply(dbFile); blob.getMetadata().setContainer(container); return blob; }
@Override public MutableBlobMetadata apply(GridFSDBFile input) { MutableBlobMetadata metadata = new MutableBlobMetadataImpl(); MutableContentMetadata contentMetadata = metadata.getContentMetadata(); String contentType = input.getContentType(); if (contentType != null) { contentMetadata.setContentType(contentType); } contentMetadata.setContentLength(input.getLength()); metadata.setETag(input.getMD5()); metadata.setLastModified(input.getUploadDate()); metadata.setName(input.getFilename()); metadata.getUserMetadata().putAll(input.getMetaData().toMap()); // TODO: support populating metadata.getContentMetadata().setContentMD5() return metadata; }