List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:com.opendesign.controller.ProjectController.java
/** * ?? ? ?// w w w . j a v a2 s. c om * * @param projectVO * @param request * @return * @throws Exception */ @RequestMapping(value = "/registerProject.ajax") public ModelAndView registerProject(@ModelAttribute("project") ProjectVO projectVO, MultipartHttpServletRequest request) throws Exception { Map<String, Object> resultMap = new HashMap<String, Object>(); UserVO loginUser = CmnUtil.getLoginUser(request); if (loginUser == null || !StringUtil.isNotEmpty(loginUser.getSeq())) { resultMap.put("result", "100"); return new JsonModelAndView(resultMap); } projectVO.setOwnerSeq(Integer.parseInt(loginUser.getSeq())); String fileUploadDbPath = CmnUtil.handleFileUpload(request, "fileUrlFile", FileUploadDomain.PROJECT); /* * ?? Thumbnail * ?? ? ? ? Thumbnail */ String fileUploadDir = CmnUtil.getFileUploadDir(request, FileUploadDomain.PROJECT); String fileName = File.separator + FilenameUtils.getName(fileUploadDbPath); ThumbnailManager.saveThumbDesignWorkMedium(fileUploadDir + fileName); ThumbnailManager.saveThumbProjectWorkMedium(fileUploadDir + fileName); String oriFileName = CmnUtil.handleFileUploadGetOriFileName(request, "fileUrlFile"); projectVO.setFileName(oriFileName); projectVO.setFileUrl(fileUploadDbPath); String currentDate = Day.getCurrentTimestamp().substring(0, 12); projectVO.setRegisterTime(currentDate); projectVO.setUpdateTime(currentDate); projectVO.setProgressStatus("P"); String[] categoryCodes = request.getParameterValues("categoryCodes"); String[] emails = request.getParameterValues("emails"); int projectSeq = service.insertProject(projectVO, categoryCodes, emails); resultMap.put(RstConst.P_NAME, RstConst.V_SUCESS); return new JsonModelAndView(resultMap); }
From source file:de.iai.ilcd.webgui.controller.admin.ImportHandler.java
private UploadedFileInformation analyzeAndCopyArchive(UploadedFile file) throws IOException { UploadedFileInformation fileInformation = new UploadedFileInformation(); /*//from ww w . j a v a 2 s . c om * CG / 2012-01-06: don't use only file.getFileName() - which uses FileItem.getName() - * because IE will return the whole path but not just the file name, * see http://commons.apache.org/fileupload/faq.html#whole-path-from-IE */ String fileName = FilenameUtils.getName(file.getFileName()); fileInformation.setFileName(fileName); fileInformation.setFileType(file.getContentType()); fileInformation.setFileSize(file.getSize()); String targetDirectory = this.getUploadDirectory(); InputStream in = file.getInputstream(); this.copyFile(file.getInputstream(), targetDirectory, fileName); in.close(); fileInformation.setPathName(targetDirectory + "/" + fileName); return fileInformation; }
From source file:com.zlk.fckeditor.Dispatcher.java
/** * Called by the connector servlet to handle a {@code POST} request. In * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and * {@link Command#QUICK_UPLOAD QuickUpload} commands. * //from w w w. j a v a2 s .co m * @param request * the current request instance * @return the upload response instance associated with this request */ UploadResponse doPost(final HttpServletRequest request) { logger.debug("Entering Dispatcher#doPost"); Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) uploadResponse = UploadResponse.getFileUploadDisabledError(); // check parameters else if (!Command.isValidForPost(context.getCommandStr())) uploadResponse = UploadResponse.getInvalidCommandError(); else if (!ResourceType.isValidType(context.getTypeStr())) uploadResponse = UploadResponse.getInvalidResourceTypeError(); else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) uploadResponse = UploadResponse.getInvalidCurrentFolderError(); else { // call the Connector#fileUpload ResourceType type = context.getDefaultResourceType(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename String fileName = FilenameUtils.getName(uplFile.getName()); logger.debug("Parameter NewFile: {}", fileName); // ?? if (uplFile.getSize() > 1024 * 1024 * 50) {//50M // ? uploadResponse = new UploadResponse(204); } else { //??uuid? String extension = FilenameUtils.getExtension(fileName); fileName = UUID.randomUUID().toString() + "." + extension; /* String path=request.getSession().getServletContext().getRealPath("/")+"userfiles/"; fileName = makeFileName(path+"/"+type.getPath(), fileName);*/ logger.debug("Change FileName to UUID: {} (by zhoulukang)", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) uploadResponse = UploadResponse.getInvalidFileTypeError(); // Secure image check (can't be done if QuickUpload) else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); if (sanitizedFileName.equals(newFileName)) uploadResponse = UploadResponse.getOK(fileUrl); else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } } catch (InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadHelper.java
/** * Internet Explorer and Opera will give you the full path along with the * filename. This will remove the path./*from w ww . j a v a 2s. c om*/ */ private String getSimpleFilename(FileItem item) { String fileName = item.getName(); if (fileName == null) { return null; } else { return FilenameUtils.getName(fileName); } }
From source file:com.opendesign.service.ProjectService.java
/** * ? ?//from w ww . ja v a 2 s . co m * * @param workVO * @param request * @return * @throws IOException */ @Transactional public Map<String, Object> insertProjectWork(ProjectWorkVO workVO, MultipartHttpServletRequest request) throws IOException { Map<String, Object> resultMap = new HashMap<String, Object>(); // 00. ?: MultipartFile ckFile = request.getFile("fileUriFile"); if (ckFile != null) { if (ckFile.getSize() > CheckRule.LIMIT_FILE_SIZE) { resultMap.put(RstConst.P_NAME, RstConst.V_FILE_SIZE); resultMap.put("fileName", ckFile.getOriginalFilename()); return resultMap; } } // CmnUtil.handleHtmlEnterRN2BR(workVO, "contents"); //0. // === ?? ? String fileUploadDbPathThumb = CmnUtil.handleFileUpload(request, "fileUriFileThumb", FileUploadDomain.PROJECT_WORK_FILE); workVO.setThumbUri(fileUploadDbPathThumb); /* * ?? ? ?? Thumbnail */ String fileUploadDirThumb = CmnUtil.getFileUploadDir(request, FileUploadDomain.PROJECT_WORK_FILE); String fileNameThumb = File.separator + FilenameUtils.getName(fileUploadDbPathThumb); ThumbnailManager.saveThumbProjectWorkSmall(fileUploadDirThumb + fileNameThumb); // === 1.work // projectSubjectSeq . UserVO user = CmnUtil.getLoginUser(request); workVO.setMemberSeq(user.getSeq()); CmnUtil.setCmnDate(workVO); dao.insertProjectWork(workVO); // === 2.workVer // === ? String fileUploadDbPath = CmnUtil.handleFileUpload(request, "fileUriFile", FileUploadDomain.PROJECT_WORK_FILE); /* * ?? ? ?? Thumbnail * ?? ? ? ? Thumbnail */ String fileUploadDir = CmnUtil.getFileUploadDir(request, FileUploadDomain.PROJECT_WORK_FILE); String fileName = File.separator + FilenameUtils.getName(fileUploadDbPath); if (CmnUtil.isImageFile(fileName)) { ThumbnailManager.saveThumbProjectWorkSmall(fileUploadDir + fileName); ThumbnailManager.saveThumbProjectWorkLarge(fileUploadDir + fileName); } String oriFileName = CmnUtil.handleFileUploadGetOriFileName(request, "fileUriFile"); ProjectWorkVerVO verVO = new ProjectWorkVerVO(); verVO.setProjectWorkSeq(workVO.getSeq()); verVO.setFileUri(fileUploadDbPath); verVO.setFilename(oriFileName); verVO.setVer(VERSION_START); CmnUtil.setCmnDate(verVO); dao.insertProjectWorkVer(verVO); // 2.1 ver workVO.setLastVer(VERSION_START); dao.updateProjectWorkLastVer(workVO); // === 3. workMember // ?: (??? ?). Set<String> allEmails = new HashSet<String>(); allEmails.add(user.getEmail()); if (!CmnUtil.isEmpty(workVO.getWorkMemberEmails())) { for (String item : workVO.getWorkMemberEmails()) { allEmails.add(item); } } List<String> seqs = userDao.selectMemberSeqsFromEmails(allEmails); for (String seq : seqs) { insertWorkMember(workVO.getSeq(), seq); } resultMap.put(RstConst.P_NAME, RstConst.V_SUCESS); return resultMap; }
From source file:com.epam.ngb.cli.TestHttpServer.java
public void addReferenceRegistration(Long refId, Long refBioId, String path, String name) { onRequest().havingMethodEqualTo(HTTP_POST).havingPathEqualTo(REF_REGISTRATION_URL) .havingHeaderEqualTo(AUTHORISATION, BEARER + TOKEN) .havingBodyEqualTo(TestDataProvider.getNotTypedRegistrationJson(null, path, name, null, null)) .respond()//from w w w . j a v a2 s . c om .withBody(TestDataProvider.getFilePayloadJson(refId, refBioId, BiologicalDataItemFormat.REFERENCE, path, name == null ? FilenameUtils.getName(path) : name)) .withStatus(HTTP_STATUS_OK); }
From source file:de.unirostock.sems.cbarchive.web.Tools.java
/** * checks whether a filename is blacklisted or not * /*from w ww . java2 s. c om*/ * @param filename the file name * @return true if filename is blacklisted */ public static boolean isFilenameBlacklisted(String filename) { if (filename == null || filename.isEmpty()) return true; if (Fields.FILENAME_BLACKLIST.contains(FilenameUtils.getName(filename))) return true; return false; }
From source file:com.iyonger.apm.web.controller.FileEntryController.java
/** * Download file entry of given path.//from w w w .jav a2s. c o m * * @param user current user * @param path user * @param response response */ @RequestMapping("/download/**") public void download(User user, String path, HttpServletResponse response) { FileEntry fileEntry = fileEntryService.getOne(user, path); if (fileEntry == null) { LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path); return; } response.reset(); try { response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(FilenameUtils.getName(fileEntry.getPath()), "utf8")); } catch (UnsupportedEncodingException e1) { LOG.error(e1.getMessage(), e1); } response.setContentType("application/octet-stream; charset=UTF-8"); response.addHeader("Content-Length", "" + fileEntry.getFileSize()); byte[] buffer = new byte[4096]; ByteArrayInputStream fis = null; OutputStream toClient = null; try { fis = new ByteArrayInputStream(fileEntry.getContentBytes()); toClient = new BufferedOutputStream(response.getOutputStream()); int readLength; while (((readLength = fis.read(buffer)) != -1)) { toClient.write(buffer, 0, readLength); } } catch (IOException e) { throw processException("error while download file", e); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(toClient); } }
From source file:com.gitpitch.services.OfflineService.java
private void fetchOnlineAssets(PitchParams pp, Path zipRoot) { List<String> assetUrls = null; Path mdOnlinePath = zipRoot.resolve(PITCHME_ONLINE_PATH); File mdOnlineFile = mdOnlinePath.toFile(); if (mdOnlineFile.exists()) { MarkdownModel markdownModel = (MarkdownModel) markdownModelFactory.create(null); try (Stream<String> stream = Files.lines(mdOnlinePath)) { assetUrls = stream.map(md -> { return markdownModel.offlineAssets(md); }).collect(Collectors.toList()); log.debug("fetchOnlineAssets: assetUrls={}", assetUrls); Path zipMdAssetsPath = zipRoot.resolve(ZIP_MD_ASSETS_DIR); zipMdAssetsPath = diskService.ensure(zipMdAssetsPath); List<String> fetched = new ArrayList<String>(); for (String assetUrl : assetUrls) { if (assetUrl != null && !fetched.contains(assetUrl)) { diskService.download(pp, zipMdAssetsPath, assetUrl, FilenameUtils.getName(assetUrl), grsManager.get(pp).getHeaders()); fetched.add(assetUrl); }/* w w w . j av a 2 s .co m*/ } } catch (Exception mex) { log.warn("fetchOnlineAssets: ex={}", mex); } } else { log.warn("fetchOnlineAssets: mdOnline not found={}", mdOnlineFile); } }
From source file:com.perceptivesoftware.mule.connector.PerceptiveContentMuleSoftConnector.java
/** * Add a page to a a Perceptive Content Document * /*from w w w.j a v a2 s . c o m*/ * {@sample.xml ../../../doc/perceptive-content-mulesoft-connector.xml.sample perceptive-content:add-page-to-document} * @param documentId The Perceptive Content Document ID * @param pageName This is what the name of the page will be called in the Perceptive Content Document. (optional) * @param filePath The file location to the page to be added * @throws FileNotFoundException Thrown if the file fails to open * @throws IntegrationServerConnectorException Thrown if call fails */ @Processor(friendlyName = "Document - Add Page") public void addPageToDocument(String documentId, String filePath, @Optional String pageName) throws IntegrationServerConnectorException, FileNotFoundException { if (Strings.isNullOrEmpty(pageName)) { pageName = FilenameUtils.getName(filePath); } FileInputStream input = new FileInputStream(filePath); client.getDocumentEndpoint().addPage(documentId, pageName, input); }