List of usage examples for java.nio.file Files probeContentType
public static String probeContentType(Path path) throws IOException
From source file:org.wso2.carbon.inbound.localfile.LocalFileOneTimePolling.java
private void processFile(final Path path, String contentType) { try {// w ww. j a va2 s . c om if (StringUtils.isEmpty(contentType)) { contentType = Files.probeContentType(path); } String readAllBytes = new String(Files.readAllBytes(path)); injectFileContent(readAllBytes, contentType); if (StringUtils.isNotEmpty(actionAfterProcess) && actionAfterProcess.toUpperCase().equals(LocalFileConstants.MOVE)) { if (Files.exists(Paths.get(moveFileURI))) { moveFile(path.toString(), moveFileURI); } else { Files.createDirectory(Paths.get(moveFileURI)); moveFile(path.toString(), moveFileURI); } } else if (StringUtils.isNotEmpty(actionAfterProcess) && actionAfterProcess.toUpperCase().equals(LocalFileConstants.DELETE)) { Files.delete(path); } } catch (IOException e) { log.error("Error while processing file : " + e.getMessage(), e); } if (log.isDebugEnabled()) { log.debug("The processing file path is : " + path); } }
From source file:com.github.jrialland.ajpclient.AbstractTomcatTest.java
@SuppressWarnings("serial") protected void addStaticResource(final String mapping, final Path file) { if (!Files.isRegularFile(file)) { final FileNotFoundException fnf = new FileNotFoundException(file.toString()); fnf.fillInStackTrace();//from ww w .j av a2s. co m throw new IllegalArgumentException(fnf); } String md5; try { final InputStream is = file.toUri().toURL().openStream(); md5 = computeMd5(is); is.close(); } catch (final Exception e) { throw new RuntimeException(e); } final String fMd5 = md5; addServlet(mapping, new HttpServlet() { @Override protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { resp.setContentLength((int) Files.size(file)); resp.setHeader("Content-MD5", fMd5); final String mime = Files.probeContentType(file); if (mime != null) { resp.setContentType(mime); } final OutputStream out = resp.getOutputStream(); Files.copy(file, out); out.flush(); } }); }
From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java
/*************************************************** * URL: /upload/jqueryUpload upload(): receives files * /*from w ww.java2 s. c o m*/ * @param request * : MultipartHttpServletRequest auto passed * @param response * : HttpServletResponse auto passed * @return LinkedList<FileMeta> as json format ****************************************************/ @ResponseBody @RequestMapping(value = "/jqueryUpload", method = RequestMethod.POST) public FileMetaList jqueryUpload(@RequestParam final Long albumId, final MultipartHttpServletRequest request, final HttpServletResponse response) throws Exception { Assert.notNull(albumId, "No Album Id supplied !"); final FileMetaList files = new FileMetaList(); // 1. build an iterator final Iterator<String> itr = request.getFileNames(); // 2. get each file while (itr.hasNext()) { // 2.1 get next MultipartFile final MultipartFile mpf = request.getFile(itr.next()); // Here the file is uploaded final String originalFilename = mpf.getOriginalFilename(); final String contentType = mpf.getContentType(); final Matcher zipMatcher = UploadPicturesController.ZIP_CONTENT_TYPE_PATTERN.matcher(contentType); if (zipMatcher.find()) { // 2.3 create new fileMeta final FileMeta zipMeta = new FileMeta(); zipMeta.setFileName(originalFilename); zipMeta.setFileSize(mpf.getSize() / 1024 + " Kb"); zipMeta.setFileType(mpf.getContentType()); final List<Path> picturesPaths = this.processArchive(mpf); final Collection<Future<Void>> futures = new ArrayList<>(picturesPaths.size()); final ExecutorService executorService = Executors .newFixedThreadPool(Runtime.getRuntime().availableProcessors()); for (final Path picturePath : picturesPaths) { final Future<Void> future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { final String pictureFileName = picturePath.getName(picturePath.getNameCount() - 1) .toString(); final byte[] pictureContents = Files.readAllBytes(picturePath); final FileMeta pictureMeta = new FileMeta(); try { final Picture picture = UploadPicturesController.this.createPicture(albumId, pictureFileName.toString(), pictureContents); final Long imageId = picture.getImage().getId(); final Long thumbnailId = picture.getThumbnail().getId(); pictureMeta.setFileName(pictureFileName); pictureMeta.setFileSize(pictureContents.length / 1024 + " Kb"); pictureMeta.setFileType(Files.probeContentType(picturePath)); pictureMeta.setUrl( response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId)); pictureMeta.setThumbnailUrl(response .encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId)); } catch (final PictureAlreadyExistsException e) { // Picture already exists ! pictureMeta.setError( UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG + e.getFilename()); } catch (final UnsupportedPictureTypeException e) { // Picture already exists ! pictureMeta.setError( UploadPicturesController.UNSUPPORTED_PICTURE_TYPE_MSG + e.getFilename()); } files.add(pictureMeta); return null; } }); futures.add(future); } for (final Future<Void> future : futures) { future.get(); } files.add(zipMeta); } final Matcher imgMatcher = UploadPicturesController.IMG_CONTENT_TYPE_PATTERN.matcher(contentType); if (imgMatcher.find()) { // 2.3 create new fileMeta final FileMeta fileMeta = new FileMeta(); try { final byte[] fileContents = mpf.getBytes(); final Picture picture = this.createPicture(albumId, originalFilename, fileContents); final Long imageId = picture.getImage().getId(); final Long thumbnailId = picture.getThumbnail().getId(); fileMeta.setFileName(originalFilename); fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb"); fileMeta.setFileType(mpf.getContentType()); fileMeta.setBytes(fileContents); fileMeta.setUrl(response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId)); fileMeta.setThumbnailUrl( response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId)); // 2.4 add to files files.add(fileMeta); } catch (final PictureAlreadyExistsException e) { // Picture already exists ! fileMeta.setError(UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG); } } } // result will be like this // {files:[{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]} return files; }
From source file:com.jmeter.alfresco.utils.HttpUtils.java
/** * Gets the mime type./*from w ww . ja v a2 s. c om*/ * * @param fileObj the file obj * @return the mime type * @throws IOException Signals that an I/O exception has occurred. */ public String getMimeType(final File fileObj) throws IOException { final Path source = Paths.get(fileObj.getPath()); return Files.probeContentType(source); }
From source file:com.kappaware.logtrawler.MFile.java
void qualify(Agent config) throws IOException { try {/* w ww .j a va 2s . co m*/ this.mimeType = Files.probeContentType(this.path); } catch (IOException e) { //log.error(String.format("Unable to probe content of %s", this.path.toString()), e); this.isLog = false; throw e; } if (config.getLogMimeTypes().contains(this.mimeType)) { this.isLog = true; } else { this.isLog = false; } }
From source file:uk.co.everywheremusic.model.RestApi.java
/** * * @param request/* w w w. j av a 2s . c om*/ * @param response * @throws ServletException * @throws IOException */ public void handleSongRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = ""; boolean auth = false; if (queryString != null) { String[] args = queryString.split(Pattern.quote("&")); if (args != null && args.length == 2) { String[] keyValueOne = args[0].split(Pattern.quote("=")); if (keyValueOne != null && keyValueOne.length == 2) { if (keyValueOne[0].equals("path")) { path = keyValueOne[1]; } } String[] keyValueTwo = args[1].split(Pattern.quote("=")); if (keyValueTwo != null && keyValueTwo.length == 2) { if (keyValueTwo[0].equals("auth")) { DBManager dbm = new DBManager(installFolder); PasswordDAO pdao = dbm.getPasswordDAO(); auth = pdao.authenticatePassword(keyValueTwo[1]); } } } } if (auth) { // check if valid song DBManager dbm = new DBManager(installFolder); SongDAO sdao = dbm.getSongDAO(); SongBean song = sdao.getSongFromPath(path); if (song != null) { File file = new File(path); String mime = Files.probeContentType(Paths.get(file.getAbsolutePath())); response.setStatus(HttpServletResponse.SC_OK); response.setContentType(mime); response.setHeader("Content-Disposition", "filename=\"" + file.getName() + "\""); response.setContentLengthLong(file.length()); FileUtils.copyFile(file, response.getOutputStream()); } else { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("<h1>Error 400: Bad request</h1><br />Invalid song"); } } else { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().println("<h1>Error 401: Forbidden</h1>"); } }
From source file:com.osbitools.ws.shared.prj.web.ExFileMgrWsSrvServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/*from w w w. j ava 2 s. co m*/ super.doGet(req, resp); } catch (ServletException e) { if (e.getCause().getClass().equals(WsSrvException.class)) { // Authentication failed checkSendError(req, resp, (WsSrvException) e.getCause()); return; } else { throw e; } } // Check if only info requires HashSet<String> extl = null; String info = req.getParameter("info"); String fname = req.getParameter(FNAME); EntityUtils eut = getEntityUtils(req); String dname = req.getParameter(DNAME); Boolean fmask = PrjMgrConstants.EXT_FILE_LIST_MASK.matcher(fname).matches(); if (!fmask) { // Check if file extension supported String ext; try { ext = GenericUtils.getFileExt(fname); } catch (WsSrvException e) { checkSendError(req, resp, e); return; } if (!eut.hasExt(ext)) { //-- 258 checkSendError(req, resp, 258, "File extension '" + ext + "' is not supported"); return; } } try { extl = getExtListByDirName(eut, dname); } catch (WsSrvException e) { checkSendError(req, resp, e); return; } if (Utils.isEmpty(info)) { try { // Check if file list required if (fmask) { resp.getWriter().print(GenericUtils.getResDirExtList(getPrjRootDir(req), fname, dname, eut.getExtLstFilenameFilter(dname))); } else { // Get single file File f = GenericUtils.checkFile(getPrjRootDir(req), fname, extl, dname, true); printMimeFile(resp, Files.probeContentType(f.toPath()), fname, GenericUtils.readFile(f), "utf-8"); } } catch (WsSrvException e) { checkSendError(req, resp, e); } } else { if (info.toLowerCase().equals("file_info")) { try { printJson(resp, GenericUtils.getInfo(getPrjRootDir(req), fname, extl, dname, getReqParamValues(req), isMinfied(req))); } catch (WsSrvException e) { return; } } else { if (!eut.hasInfoReq(info)) { //-- 252 checkSendError(req, resp, 252, null, new String[] { "Info request \'" + info + "\' is not supported." }); return; } try { printJson(resp, eut.execInfoReq(info, getPrjRootDir(req), fname, extl, dname, getReqParamValues(req), isMinfied(req))); } catch (WsSrvException e) { checkSendError(req, resp, e); } } } }
From source file:algorithm.MetsSubmissionInformationPackage.java
@SuppressWarnings("unchecked") @Override//from w w w .j a v a 2 s .co m public File encapsulate(File carrier, List<File> userPayloadList) throws IOException { List<File> payloadList = new ArrayList<File>(); payloadList.addAll(userPayloadList); Mets metsDocument = new Mets(); metsDocument.setID(carrier.getName() + "_SIP"); metsDocument.setLABEL("PeriCAT information package"); metsDocument.setTYPE("digital object and metadata files"); // HEADER: Agent periPack = new Agent(); periPack.setID("peripack agent"); periPack.setROLE(Role.PRESERVATION); periPack.setOTHERTYPE("SOFTWARE"); Name name = new Name(); PCData nameString = new PCData(); nameString.add("peripack"); name.getContent().add(nameString); periPack.getContent().add(name); Note note = new Note(); PCData noteString = new PCData(); noteString.add(TOOL_DESCRIPTION); note.getContent().add(noteString); periPack.getContent().add(note); MetsHdr header = new MetsHdr(); header.setID("mets header"); header.setCREATEDATE(new Date()); header.setLASTMODDATE(new Date()); header.setRECORDSTATUS("complete"); header.getContent().add(periPack); if (truePersonButton.isSelected()) { Agent person = new Agent(); person.setID("peripack user"); person.setROLE(Role.CREATOR); person.setTYPE(Type.INDIVIDUAL); Name personName = new Name(); PCData personNameString = new PCData(); personNameString.add(personField.getText()); personName.getContent().add(personNameString); person.getContent().add(personName); header.getContent().add(person); } metsDocument.getContent().add(header); // FILE SECTION: FileSec fileSection = new FileSec(); FileGrp carrierGroup = new FileGrp(); carrierGroup.setID("carrier files"); carrierGroup.setUSE("digital object"); // carrier div for structural map: Div carrierDiv = new Div(); carrierDiv.setID("carrier list"); carrierDiv.setTYPE("carrier files"); // back to file section: edu.harvard.hul.ois.mets.File metsCarrier = new edu.harvard.hul.ois.mets.File(); metsCarrier.setID(carrier.getAbsolutePath()); metsCarrier.setGROUPID("carrier"); metsCarrier.setCHECKSUM("" + FileUtils.checksumCRC32(carrier)); metsCarrier.setMIMETYPE(Files.probeContentType(carrier.toPath())); metsCarrier.setOWNERID(Files.getOwner(carrier.toPath(), LinkOption.NOFOLLOW_LINKS).toString()); metsCarrier.setSIZE(Files.size(carrier.toPath())); metsCarrier.setUSE(Files.getPosixFilePermissions(carrier.toPath(), LinkOption.NOFOLLOW_LINKS).toString()); FLocat fileLocation = new FLocat(); fileLocation.setXlinkHref(carrier.getAbsolutePath()); fileLocation.setLOCTYPE(Loctype.OTHER); fileLocation.setOTHERLOCTYPE("system file path"); fileLocation.setXlinkTitle("original file path of the carrier"); metsCarrier.getContent().add(fileLocation); carrierGroup.getContent().add(metsCarrier); // add structural map information: Fptr carrierFilePointer = new Fptr(); carrierFilePointer.setFILEID(carrier.getAbsolutePath()); carrierDiv.getContent().add(carrierFilePointer); fileSection.getContent().add(carrierGroup); FileGrp payloadGroup = new FileGrp(); payloadGroup.setID("payload files"); payloadGroup.setUSE("metadata"); // payload div for structural map: Div payloadDiv = new Div(); payloadDiv.setID("payload list"); payloadDiv.setTYPE("payload files"); // back to file section: for (File payload : payloadList) { edu.harvard.hul.ois.mets.File metsPayload = new edu.harvard.hul.ois.mets.File(); metsPayload.setID(payload.getAbsolutePath()); metsPayload.setGROUPID("payload"); metsPayload.setCHECKSUM(DigestUtils.md5Hex(new FileInputStream(payload))); metsPayload.setCHECKSUMTYPE(Checksumtype.MD5); metsPayload.setMIMETYPE(Files.probeContentType(payload.toPath())); metsPayload.setOWNERID(Files.getOwner(payload.toPath(), LinkOption.NOFOLLOW_LINKS).toString()); metsPayload.setSIZE(Files.size(payload.toPath())); metsPayload .setUSE(Files.getPosixFilePermissions(payload.toPath(), LinkOption.NOFOLLOW_LINKS).toString()); FLocat fileLocation2 = new FLocat(); fileLocation2.setXlinkHref(payload.getAbsolutePath()); fileLocation2.setLOCTYPE(Loctype.OTHER); fileLocation2.setOTHERLOCTYPE("system file path"); fileLocation2.setXlinkTitle("original file path of the payload"); metsPayload.getContent().add(fileLocation2); payloadGroup.getContent().add(metsPayload); // add structural map information: Fptr payloadFilePointer = new Fptr(); payloadFilePointer.setFILEID(payload.getAbsolutePath()); payloadDiv.getContent().add(payloadFilePointer); } fileSection.getContent().add(payloadGroup); metsDocument.getContent().add(fileSection); // STRUCTURAL MAP: StructMap structuralMap = new StructMap(); structuralMap.setID("structural map"); Div encapsulatedFiles = new Div(); encapsulatedFiles.setID("peripack files"); encapsulatedFiles.setTYPE("encapsulated files"); structuralMap.getContent().add(encapsulatedFiles); encapsulatedFiles.getContent().add(carrierDiv); encapsulatedFiles.getContent().add(payloadDiv); metsDocument.getContent().add(structuralMap); File metsFile = new File(OUTPUT_DIRECTORY + "mets.xml"); FileOutputStream outputStream = new FileOutputStream(metsFile); try { metsDocument.write(new MetsWriter(outputStream)); } catch (MetsException e) { } outputStream.close(); payloadList.add(metsFile); File outputFile = null; if (zipButton.isSelected()) { outputFile = new ZipPackaging().encapsulate(carrier, payloadList); } else if (tarButton.isSelected()) { outputFile = new TarPackaging().encapsulate(carrier, payloadList); } metsFile.delete(); return outputFile; }
From source file:ch.threema.apitool.helpers.E2EHelper.java
/** * Encrypt a file message and send it to the given recipient. * The thumbnailMessagePath can be null. * * @param threemaId target Threema ID/*from w w w . j av a2 s . co m*/ * @param fileMessageFile the file to be sent * @param thumbnailMessagePath file for thumbnail; if not set, no thumbnail will be sent * @return generated message ID * @throws InvalidKeyException * @throws IOException * @throws NotAllowedException */ public String sendFileMessage(String threemaId, File fileMessageFile, File thumbnailMessagePath) throws InvalidKeyException, IOException, NotAllowedException { //fetch public key byte[] publicKey = this.apiConnector.lookupKey(threemaId); if (publicKey == null) { throw new InvalidKeyException("invalid threema id"); } //check capability of a key CapabilityResult capabilityResult = this.apiConnector.lookupKeyCapability(threemaId); if (capabilityResult == null || !capabilityResult.canImage()) { throw new NotAllowedException(); } if (!fileMessageFile.isFile()) { throw new IOException("invalid file"); } byte[] fileData = this.readFile(fileMessageFile); if (fileData == null) { throw new IOException("invalid file"); } //encrypt the image EncryptResult encryptResult = CryptTool.encryptFileData(fileData); //upload the image UploadResult uploadResult = apiConnector.uploadFile(encryptResult); if (!uploadResult.isSuccess()) { throw new IOException("could not upload file (upload response " + uploadResult.getResponseCode() + ")"); } UploadResult uploadResultThumbnail = null; if (thumbnailMessagePath != null && thumbnailMessagePath.isFile()) { byte[] thumbnailData = this.readFile(thumbnailMessagePath); if (thumbnailData == null) { throw new IOException("invalid thumbnail file"); } //encrypt the thumbnail EncryptResult encryptResultThumbnail = CryptTool.encryptFileThumbnailData(fileData, encryptResult.getSecret()); //upload the thumbnail uploadResultThumbnail = this.apiConnector.uploadFile(encryptResultThumbnail); } //send it EncryptResult fileMessage = CryptTool.encryptFileMessage(encryptResult, uploadResult, Files.probeContentType(fileMessageFile.toPath()), fileMessageFile.getName(), (int) fileMessageFile.length(), uploadResultThumbnail, privateKey, publicKey); return this.apiConnector.sendE2EMessage(threemaId, fileMessage.getNonce(), fileMessage.getResult()); }
From source file:org.fon.documentmanagementsystem.controllers.DocumentController.java
@RequestMapping(path = "/download/{id}", method = RequestMethod.GET) public ResponseEntity<byte[]> downloadFile(@PathVariable("id") long id) { try {//from www .j a va 2 s . com Dokument document = dokumentService.findOne(id); HttpHeaders header = new HttpHeaders(); //header.setContentType(MediaType.valueOf(document.getFajlTip())); String nazivfajla = document.getFajl(); int li = nazivfajla.lastIndexOf('\\'); String subsnaziv = nazivfajla.substring(li + 1, nazivfajla.length()); header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + subsnaziv); File file = new File(nazivfajla); Path path = file.toPath(); byte[] outputByte = Files.readAllBytes(path); String fajltype = Files.probeContentType(path); System.out.println(fajltype + " je tip"); header.setContentType(MediaType.valueOf(fajltype)); header.setContentLength(outputByte.length); return new ResponseEntity<>(outputByte, header, HttpStatus.OK); } catch (Exception e) { return null; } }