List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:ch.entwine.weblounge.kernel.site.SiteServlet.java
/** * Depending on whether a call to a jsp is made or not, delegates to the * jasper servlet with a controlled context class loader or tries to load the * requested file from the bundle as a static resource. * //from w ww. ja v a 2 s. c o m * @see HttpServlet#service(HttpServletRequest, HttpServletResponse) */ @Override public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { String filename = FilenameUtils.getName(request.getPathInfo()); // Don't allow listing the root directory? if (StringUtils.isBlank(filename)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } // Check the requested format. In case of a JSP, this can either be // processed (default) or raw, in which case the file contents are // returned rather than Jasper's output of it. Format format = Format.Processed; String f = request.getParameter(PARAM_FORMAT); if (StringUtils.isNotBlank(f)) { try { format = Format.valueOf(StringUtils.capitalize(f.toLowerCase())); } catch (IllegalArgumentException e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } } if (Format.Processed.equals(format) && filename.endsWith(".jsp")) { serviceJavaServerPage(request, response); } else { serviceResource(request, response); } }
From source file:fr.insalyon.creatis.vip.datamanager.server.business.TransferPoolBusiness.java
/** * /*from www.j av a 2 s. c o m*/ * @param operation * @param currentUserFolder * @return * @throws DataManagerException */ private PoolOperation processOperation(Operation operation, String currentUserFolder) throws DataManagerException { SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy HH:mm"); String source = ""; String dest = ""; PoolOperation.Type type = null; PoolOperation.Status status = PoolOperation.Status.valueOf(operation.getStatus().name()); if (operation.getType() == Operation.Type.Upload) { type = PoolOperation.Type.Upload; source = FilenameUtils.getName(operation.getSource()); dest = DataManagerUtil.parseRealDir(operation.getDest(), currentUserFolder); } else if (operation.getType() == Operation.Type.Delete) { type = PoolOperation.Type.Delete; source = DataManagerUtil.parseRealDir(operation.getSource(), currentUserFolder); } else { type = PoolOperation.Type.Download; dest = "Platform"; source = operation.getType() == Operation.Type.Download ? DataManagerUtil.parseRealDir(operation.getSource(), currentUserFolder) : FilenameUtils.getBaseName(operation.getDest()); } return new PoolOperation(operation.getId(), operation.getRegistration(), dateFormat.format(operation.getRegistration()), source, dest, type, status, operation.getUser(), operation.getProgress()); }
From source file:it.polimi.meteocal.web.SettingBean.java
/** * Method that change the setting of the user and his personal information *///from www . ja va 2 s .c o m public void changeSetting() { long id = 0; try { // VALIDATE PASSWORD id = handleUser.checkAccessCredential(loggedUser.getId(), loggedUser.getPassword()); } catch (ErrorRequestException ex) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", ex.getMessage())); LOGGER.log(Level.ERROR, ex); } // UPLOAD IMAGE if (uploadedFile != null && id != 0 && uploadedFile.getSize() > 0) { String filename = FilenameUtils.getName(uploadedFile.getFileName()); try { InputStream input = uploadedFile.getInputstream(); File file = new File(System.getProperty("com.sun.aas.instanceRoot") + "/var/webapp/images", filename); OutputStream output = new FileOutputStream(file); LOGGER.log(Level.INFO, file.getAbsolutePath()); loggedUser.setAvatar("/images/" + file.getName()); IOUtils.copy(input, output); IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } catch (IOException ex) { LOGGER.log(Level.ERROR, ex); } } else { LOGGER.log(Level.ERROR, "IMAGE NULL"); } if (id != 0) { // CHECK NEW PASSWORD if (newpassword != null && newpassword.equals(renewpassword)) { loggedUser.setPassword(newpassword); } try { handleUser.changeSettings(loggedUser); handleUser.changeCalendarVisibility(calendarVisibility); } catch (ErrorRequestException ex) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", ex.getMessage())); LOGGER.log(Level.ERROR, ex); } FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Settings", "Sccessfully Updated")); } }
From source file:customer.cms.CustomerCaseManagedBean.java
public void uploadPhoto(FileUploadEvent e) throws IOException { System.out.println("CustomerCaseManagedBean.uploadPhoto: start uploading"); UploadedFile uploadedPhoto = e.getFile(); String filename = FilenameUtils.getName(uploadedPhoto.getFileName()); byte[] bytes = null; if (uploadedPhoto != null) { ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); directoryPath = ec.getRealPath("//WEB-INF//files//"); bytes = uploadedPhoto.getContents(); String filepath = directoryPath + "/" + filename; System.out.println("CustomerCaseManagedBean.uploadPhoto.filenAME: " + filepath); try (FileOutputStream stream = new FileOutputStream((new File(directoryPath + "/" + filename)))) { System.out.println("CustomerCaseManagedBean.uploadPhoto: start writing"); stream.write(bytes);//from w ww.java 2s . c o m stream.flush(); newIssue.setAttachmentFileName(filename); } catch (Exception ex) { System.out.println("CustomerCaseManagedBean.uploadPhoto: " + ex.toString()); } } }
From source file:com.jaeksoft.searchlib.crawler.web.spider.Crawl.java
protected void parseContent(InputStream inputStream) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException, SearchLibException, NoSuchAlgorithmException, URISyntaxException { if (parserSelector == null) { urlItem.setParserStatus(ParserStatus.NOPARSER); return;/*from ww w . j a v a 2 s. c om*/ } String fileName = urlItem.getContentDispositionFilename(); if (fileName == null) { URL url = urlItem.getURL(); if (url != null) fileName = FilenameUtils.getName(url.getFile()); } IndexDocument sourceDocument = new IndexDocument(); urlItem.populate(sourceDocument); Date parserStartDate = new Date(); // TODO Which language for OCR ? parser = parserSelector.parseStream(sourceDocument, fileName, urlItem.getContentBaseType(), urlItem.getUrl(), inputStream, null, parserSelector.getWebCrawlerDefaultParser()); if (parser == null) { urlItem.setParserStatus(ParserStatus.NOPARSER); return; } if (parser.getError() != null) { urlItem.setParserStatus(ParserStatus.PARSER_ERROR); return; } urlItem.clearInLinks(); urlItem.clearOutLinks(); for (ParserResultItem result : parser.getParserResults()) { urlItem.addInLinks(result.getFieldContent(ParserFieldEnum.internal_link)); urlItem.addInLinks(result.getFieldContent(ParserFieldEnum.internal_link_nofollow)); urlItem.addOutLinks(result.getFieldContent(ParserFieldEnum.external_link)); urlItem.addOutLinks(result.getFieldContent(ParserFieldEnum.external_link_nofollow)); urlItem.setLang(result.getFieldValue(ParserFieldEnum.lang, 0)); urlItem.setLangMethod(result.getFieldValue(ParserFieldEnum.lang_method, 0)); urlItem.setContentTypeCharset(result.getFieldValue(ParserFieldEnum.charset, 0)); } ParserStatus parsedStatus = ParserStatus.PARSED; if (parser instanceof HtmlParser) if (!((HtmlParser) parser).isCanonical()) parsedStatus = ParserStatus.PARSED_NON_CANONICAL; urlItem.setParserStatus(parsedStatus); String oldMd5size = urlItem.getMd5size(); String newMd5size = parser.getMd5size(); urlItem.setMd5size(newMd5size); Date oldContentUpdateDate = urlItem.getContentUpdateDate(); Date newContentUpdateDate = null; if (oldContentUpdateDate == null) newContentUpdateDate = parserStartDate; else { if (oldMd5size != null && newMd5size != null) if (!oldMd5size.equals(newMd5size)) newContentUpdateDate = parserStartDate; } if (newContentUpdateDate != null) urlItem.setContentUpdateDate(newContentUpdateDate); for (ParserResultItem result : parser.getParserResults()) { FieldContent fieldContent = result.getFieldContent(ParserFieldEnum.meta_robots); if (fieldContent != null) { List<FieldValueItem> fieldValues = fieldContent.getValues(); if (fieldValues != null) { for (FieldValueItem item : result.getFieldContent(ParserFieldEnum.meta_robots).getValues()) if ("noindex".equalsIgnoreCase(item.getValue())) { urlItem.setIndexStatus(IndexStatus.META_NOINDEX); break; } } } } }
From source file:de.uzk.hki.da.format.TiffConversionStrategy.java
/** * Generate target file path.// w w w . ja v a 2s . c o m * * @param ci the ci * @return the string */ public String generateTargetFilePath(ConversionInstruction ci) { String input = ci.getSource_file().toRegularFile().getAbsolutePath(); return object.getPath("newest") + "/" + Utilities.slashize(ci.getTarget_folder()) + FilenameUtils.getName(input); }
From source file:fr.gouv.finances.dgfip.xemelios.importers.archives.rules.FilterModel.java
/** * Renvoie <tt>true</tt> si ce document satisfait ce filtre * @param document/*from www . j a v a 2s . co m*/ * @return */ public boolean matches(Element document) { if (all) return true; else { boolean ret = true; if (typeDoc != null) { String documentType = ArchiveImporter.normalizeDocumentType(document.getAttributeValue("type")); ret = ret && typeDoc.equals(documentType); } if (collectivite != null) { String documentCollectivite = document.getAttributeValue("buIdCol"); ret = ret && collectivite.equals(documentCollectivite); } if (budget != null) { String documentBudget = document.getAttributeValue("buCode"); ret = ret && budget.equals(documentBudget); } if (fileName != null) { String documentFileName = FilenameUtils.getName(document.getAttributeValue("path")); ret = ret && fileName.equals(documentFileName); } for (AttributeModel am : attributes) { ret = ret && am.matches(document); } return ret; } }
From source file:com.joyent.manta.client.MantaClientFindIT.java
/** * This test determines that we are filtering results as per our expection * when using a filter predicate with find(). *///from w w w .java2 s . co m public void canFindRecursivelyWithFilter() throws IOException { List<String> level1Dirs = Arrays.asList(testPathPrefix + "aaa_bbb_ccc", testPathPrefix + "aaa_111_ccc", testPathPrefix + UUID.randomUUID()); List<String> level1Files = Arrays.asList(testPathPrefix + UUID.randomUUID(), testPathPrefix + "aaa_222_ccc"); for (String dir : level1Dirs) { mantaClient.putDirectory(dir); } for (String file : level1Files) { mantaClient.put(file, TEST_DATA, StandardCharsets.UTF_8); } List<String> level2Files = level1Dirs.stream().flatMap(dir -> Stream.of(dir + SEPARATOR + "aaa_333_ccc", dir + SEPARATOR + "aaa_444_ccc", dir + SEPARATOR + UUID.randomUUID())).collect(Collectors.toList()); for (String file : level2Files) { mantaClient.put(file, TEST_DATA, StandardCharsets.UTF_8); } final String[] results; Predicate<? super MantaObject> filter = (Predicate<MantaObject>) obj -> FilenameUtils.getName(obj.getPath()) .startsWith("aaa_"); try (Stream<MantaObject> stream = mantaClient.find(testPathPrefix, filter)) { Stream<String> paths = stream.map(MantaObject::getPath); Stream<String> sorted = paths.sorted(); results = sorted.toArray(String[]::new); } String[] expected = new String[] { testPathPrefix + "aaa_111_ccc", testPathPrefix + "aaa_111_ccc" + SEPARATOR + "aaa_333_ccc", testPathPrefix + "aaa_111_ccc" + SEPARATOR + "aaa_444_ccc", testPathPrefix + "aaa_222_ccc", testPathPrefix + "aaa_bbb_ccc", testPathPrefix + "aaa_bbb_ccc" + SEPARATOR + "aaa_333_ccc", testPathPrefix + "aaa_bbb_ccc" + SEPARATOR + "aaa_444_ccc", }; try { Assert.assertEqualsNoOrder(results, expected); } catch (AssertionError e) { System.err.println("ACTUAL: " + StringUtils.join(results, ", ")); System.err.println("EXPECTED: " + StringUtils.join(expected, ", ")); throw e; } }
From source file:com.ephesoft.gxt.admin.server.ImportBatchClassUploadServlet.java
private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService, BatchClassService bcService, ImportBatchService imService) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempZipFile = null;/* w w w .ja va2s. com*/ InputStream instream = null; OutputStream out = null; String zipWorkFlowName = "", tempOutputUnZipDir = "", zipWorkflowDesc = "", zipWorkflowPriority = ""; BatchClass importBatchClass = null; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } String zipFileName = ""; String zipPathname = ""; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) {//&& "importFile".equals(item.getFieldName())) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; // get only the file name not whole path if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { log.error("Unable to create the export folder." + e, e); printWriter.write("Unable to create the export folder.Please try again."); } catch (IOException e) { log.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + zipFileName); } } } } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.')) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (Exception e) { log.error("Unable to unzip the file." + e, e); printWriter.write("Unable to unzip the file.Please try again."); tempZipFile.delete(); } String serializableFilePath = FileUtils.getFileNameOfTypeFromFolder(tempOutputUnZipDir, SERIALIZATION_EXT); InputStream serializableFileStream = null; try { serializableFileStream = new FileInputStream(serializableFilePath); importBatchClass = (BatchClass) SerializationUtils.deserialize(serializableFileStream); zipWorkFlowName = importBatchClass.getName(); zipWorkflowDesc = importBatchClass.getDescription(); zipWorkflowPriority = "" + importBatchClass.getPriority(); } catch (Exception e) { tempZipFile.delete(); log.error("Error while importing" + e, e); printWriter.write("Error while importing.Please try again."); } finally { if (serializableFileStream != null) { try { serializableFileStream.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + serializableFilePath); } } } } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } if (tempZipFile != null) { tempZipFile.delete(); } List<String> uncList = bcService.getAssociatedUNCList(zipWorkFlowName); DeploymentService deploymentService = this.getSingleBeanOfType(DeploymentService.class); boolean isWorkflowDeployed = deploymentService.isDeployed(zipWorkFlowName); if (null != importBatchClass) { boolean isWorkflowEqual = imService.isImportWorkflowEqualDeployedWorkflow(importBatchClass, importBatchClass.getName()); printWriter.write(AdminSharedConstants.WORK_FLOW_NAME + zipWorkFlowName); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORK_FLOW_DESC + zipWorkflowDesc); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORK_FLOW_PRIORITY + zipWorkflowPriority); printWriter.append("|"); printWriter.append(AdminSharedConstants.FILE_PATH).append(tempOutputUnZipDir); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_DEPLOYED + isWorkflowDeployed); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_EQUAL + isWorkflowEqual); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_EXIST_IN_BATCH_CLASS + ((uncList == null || uncList.size() == 0) ? false : true)); printWriter.append("|"); } printWriter.flush(); }
From source file:com.ephesoft.gxt.systemconfig.server.ImportPoolServlet.java
/** * Unzip the attached zipped file.//w w w . j av a2 s . c om * * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} * @param batchSchemaService {@link BatchSchemaService} * @throws IOException */ private void attachFile(final HttpServletRequest req, final HttpServletResponse resp, final BatchSchemaService batchSchemaService) throws IOException { final PrintWriter printWriter = resp.getWriter(); File tempZipFile = null; InputStream instream = null; OutputStream out = null; String tempOutputUnZipDir = CoreCommonConstant.EMPTY_STRING; if (ServletFileUpload.isMultipartContent(req)) { final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); final String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); final File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } String zipFileName = CoreCommonConstant.EMPTY_STRING; String zipPathname = CoreCommonConstant.EMPTY_STRING; List<FileItem> items; try { items = upload.parseRequest(req); for (final FileItem item : items) { if (!item.isFormField()) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; // get only the file name not whole path if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); final byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (final FileNotFoundException fileNotFoundException) { log.error("Unable to create the export folder." + fileNotFoundException, fileNotFoundException); printWriter.write("Unable to create the export folder.Please try again."); } catch (final IOException ioException) { log.error("Unable to read the file." + ioException, ioException); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (final IOException ioException) { log.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (final IOException ioException) { log.info("Could not close stream for file." + zipFileName); } } } } } } catch (final FileUploadException fileUploadException) { log.error("Unable to read the form contents." + fileUploadException, fileUploadException); printWriter.write("Unable to read the form contents. Please try again."); } tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf(CoreCommonConstant.DOT)) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (final Exception exception) { log.error("Unable to unzip the file." + exception, exception); printWriter.write("Unable to unzip the file. Please try again."); tempZipFile.delete(); } } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } if (tempZipFile != null) { tempZipFile.delete(); } printWriter.append(SystemConfigSharedConstants.FILE_PATH).append(tempOutputUnZipDir); //printWriter.append("filePath:").append(tempOutputUnZipDir); printWriter.append(CoreCommonConstant.PIPE); printWriter.flush(); }