List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:io.github.retz.cli.CommandGetFile.java
private OutputStream tentativeOutputStream(Client c, String resultDir, String filename) throws FileNotFoundException { if ("-".equals(resultDir)) { return System.out; } else {// w w w . j a va 2 s .c om String basename = FilenameUtils.getName(filename); String path = resultDir + "/" + basename; LOG.info("Saving {} to {}", filename, path); return new FileOutputStream(path); } }
From source file:controllers.PictureController.java
private void reziseImage(String fileLocation) { BufferedImage img = null;//from ww w . ja v a 2 s.c o m String extension = FilenameUtils.getExtension(fileLocation); String fileName = FilenameUtils.getName(fileLocation); File file = new File(fileLocation); try { img = ImageIO.read(file); BufferedImage webPic = resize(img, 1024); BufferedImage thumbnail = resize(img, Method.SPEED, Mode.FIT_TO_WIDTH, 150, 100, OP_ANTIALIAS); ImageIO.write(webPic, extension, new File("public/pictures/" + fileName)); ImageIO.write(thumbnail, extension, new File("public/pictures/thumbs/" + fileName)); } catch (IOException e) { } }
From source file:edu.umn.msi.tropix.proteomics.conversion.Scan.java
public void setParentFileName(final String parentFilePath) { this.parentFileName = FilenameUtils.getName(parentFilePath); if (DtaNameUtils.isDtaName(parentFileName)) { final DtaNameSummary summary = DtaNameUtils.getDtaNameSummary(parentFileName); this.parentName = summary.getBasename(); alt = summary.getStart();// ww w .j a v a2 s . com if (precursorCharge == 0) { precursorCharge = summary.getCharge(); } } else { this.parentName = FilenameUtils.getBaseName(parentFileName); } }
From source file:de.iai.ilcd.model.dao.SourceDao.java
private boolean saveDigitalFiles(Source source, PrintWriter out) { EntityManager em = PersistenceUtil.getEntityManager(); File directory = null;/*from w w w .ja v a 2 s .com*/ EntityTransaction t = em.getTransaction(); try { // OK, now let's handle the files if any if ((source.getFiles().size() > 0) && (source.getId() > 0)) { // we have files and the source has a valid // id // first let's check if the source has already a file directory to save binary files String directoryPath = source.getFilesDirectory(); directory = new File(directoryPath); if (!directory.exists()) { directory.mkdirs(); // OK, create the directory and all parents } // OK, now that we verified that we have a directory, let's copy the files to the directory for (DigitalFile digitalFile : source.getFiles()) { String sourcePath = digitalFile.getFileName(); logger.info("have to save digital file {}", sourcePath); File file = new File(sourcePath); if (file.canRead()) { // copy file only if we have a real file and not only a URL File dest = new File(directory, file.getName()); if (!file.copyTo(dest)) { if (out != null) { out.println("cannot copy file " + file.getName() + " of source data set " + source.getName().getDefaultValue() + " to database file firectory"); } logger.error("cannot copy digital file {} to source directory {}", file.getName(), directoryPath); } // now, replace name in digitalFile with just the name of the file digitalFile.setFileName(FilenameUtils.getName(sourcePath)); } else { if (!file.getName().startsWith("http:") || !file.getName().startsWith("https:")) { // there are sometimes URL refs in source which don't have http:// prepended if (!file.getName().matches(".+\\....") && file.getName().contains(".")) { // looks like a URL with no http:// in front; try to fix that digitalFile.setFileName("http://" + file.getName()); } else { // we have a file which we cannot find digitalFile.setFileName(FilenameUtils.getName(sourcePath)); out.println("warning: digital file " + FilenameUtils.getName(sourcePath) + " of source data set " + source.getName().getDefaultValue() + " cannot be found in external_docs directory"); logger.warn( "warning: digital file {} of source data set {} cannot be found in external_docs directory; will be ignored", file.getName(), source.getName().getDefaultValue()); } } } t.begin(); em.persist(digitalFile); t.commit(); } } } catch (Exception e) { // OK, let's delete the digital files and rollback the whole transaction to remove database items logger.error("cannot save digital file", e); if (t.isActive()) { t.rollback(); } this.deleteDigitalFiles(source); return false; } return true; }
From source file:com.isomorphic.maven.packaging.Downloads.java
/** * Obtains a list of hyperlinks, downloads the file/s represented by each, and links it/them to the given distribution. * /* w w w. jav a 2 s . com*/ * @param distribution * @throws MojoExecutionException */ private void download(Distribution distribution) throws MojoExecutionException { String[] links = list(distribution); for (String link : links) { String filename = FilenameUtils.getName(link); File file = new File(toFolder, filename); if (file.exists() && !overwriteExistingFiles) { LOGGER.info("Existing archive found at '{}'. Skipping download.", file.getAbsolutePath()); distribution.getFiles().add(file); continue; } HttpGet httpget = new HttpGet(link); HttpResponse response; try { response = httpClient.execute(host, httpget); } catch (Exception e) { throw new MojoExecutionException("Error issuing GET request for bundle at '" + httpget + "'", e); } HttpEntity entity = response.getEntity(); if (!toFolder.mkdirs() && !toFolder.exists()) { throw new MojoExecutionException( "Could not create specified working directory '" + toFolder.getAbsolutePath() + "'"); } FileUtils.deleteQuietly(file); OutputStream outputStream = null; try { LOGGER.info("Downloading file to '{}'", file.getAbsolutePath()); outputStream = new LoggingCountingOutputStream(new FileOutputStream(file), entity.getContentLength()); entity.writeTo(outputStream); distribution.getFiles().add(file); } catch (Exception e) { throw new MojoExecutionException("Error writing file to '" + file.getAbsolutePath() + "'", e); } finally { IOUtils.closeQuietly(outputStream); } } }
From source file:de.uzk.hki.da.convert.TiffConversionStrategy.java
/** * Generate target file path.//from w ww.j av a 2 s. c om * * @param ci * the ci * @return the string */ public String generateTargetFilePath(WorkArea wa, ConversionInstruction ci) { String input = wa.toFile(ci.getSource_file()).getAbsolutePath(); return wa.dataPath() + "/" + object.getNameOfLatestBRep() + "/" + StringUtilities.slashize(ci.getTarget_folder()) + FilenameUtils.getName(input); }
From source file:com.ephesoft.gxt.admin.server.ExportBatchClassDownloadServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { BatchClassService batchClassService = this.getSingleBeanOfType(BatchClassService.class); BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class); BatchClass batchClass = batchClassService.getLoadedBatchClassByIdentifier(req.getParameter(IDENTIFIER)); String exportLearning = req.getParameter(EXPORT_LEARNING); if (batchClass == null) { log.error("Incorrect batch class identifier specified."); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Incorrect batch class identifier specified."); } else {// w ww . j a v a2 s. c o m // Marking exported batch class as 'Advance' as this batch has some advance feature like new FPR.rsp file. batchClass.setAdvancedBatchClass(Boolean.TRUE); Calendar cal = Calendar.getInstance(); String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); SimpleDateFormat formatter = new SimpleDateFormat("MMddyy"); String formattedDate = formatter.format(new Date()); String zipFileName = batchClass.getIdentifier() + "_" + formattedDate + "_" + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.SECOND); String tempFolderLocation = exportSerailizationFolderPath + File.separator + zipFileName; File copiedFolder = new File(tempFolderLocation); if (copiedFolder.exists()) { copiedFolder.delete(); } copiedFolder.mkdirs(); BatchClassUtil.copyModules(batchClass); BatchClassUtil.copyDocumentTypes(batchClass); BatchClassUtil.copyConnections(batchClass); BatchClassUtil.copyScannerConfig(batchClass); BatchClassUtil.exportEmailConfiguration(batchClass); BatchClassUtil.exportUserGroups(batchClass); BatchClassUtil.exportBatchClassField(batchClass); BatchClassUtil.exportCMISConfiguration(batchClass); // BatchClassUtil.decryptAllPasswords(batchClass); File serializedExportFile = new File( tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT); try { SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile)); File originalFolder = new File( batchSchemaService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier()); if (originalFolder.isDirectory()) { String[] folderList = originalFolder.list(); Arrays.sort(folderList); for (int i = 0; i < folderList.length; i++) { if (folderList[i].endsWith(SERIALIZATION_EXT)) { // skip previous ser file since new is created. } else if (FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getTestKVExtractionFolderName()) || FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getTestTableFolderName()) || FilenameUtils.getName(folderList[i]).equalsIgnoreCase( batchSchemaService.getFileboundPluginMappingFolderName())) { // Skip this folder continue; } else if (FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName()) && Boolean.parseBoolean(exportLearning)) { FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]), new File(copiedFolder, folderList[i])); } else if (FilenameUtils.getName(folderList[i]).equalsIgnoreCase( batchSchemaService.getSearchSampleName()) && Boolean.parseBoolean(exportLearning)) { FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]), new File(copiedFolder, folderList[i])); } else if (!(FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName()) || FilenameUtils.getName(folderList[i]) .equalsIgnoreCase(batchSchemaService.getSearchSampleName()))) { FileUtils.copyDirectoryWithContents(new File(originalFolder, folderList[i]), new File(copiedFolder, folderList[i])); } } } } catch (FileNotFoundException e) { // Unable to read serializable file log.error("Error occurred while creating the serializable file." + e, e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while creating the serializable file."); } catch (IOException e) { // Unable to create the temporary export file(s)/folder(s) log.error("Error occurred while creating the serializable file." + e, e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while creating the serializable file.Please try again"); } resp.setContentType("application/x-zip\r\n"); resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n"); ServletOutputStream out = null; ZipOutputStream zout = null; try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(tempFolderLocation, zout, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (IOException e) { // Unable to create the temporary export file(s)/folder(s) log.error("Error occurred while creating the zip file." + e, e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again."); } finally { // clean up code if (zout != null) { zout.close(); } if (out != null) { out.flush(); } FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder); } } }
From source file:com.photon.maven.plugins.android.standalonemojos.PullMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { parseConfiguration();/* ww w.j av a 2 s . c o m*/ doWithDevices(new DeviceCallback() { public void doWithDevice(final IDevice device) throws MojoExecutionException { // message will be set later according to the processed files String message = ""; try { SyncService syncService = device.getSyncService(); FileListingService fileListingService = device.getFileListingService(); FileEntry sourceFileEntry = getFileEntry(parsedSource, fileListingService); if (sourceFileEntry.isDirectory()) { // pulling directory File destinationDir = new File(parsedDestination); if (!destinationDir.exists()) { getLog().info("Creating destination directory " + destinationDir); destinationDir.mkdirs(); destinationDir.mkdir(); } String destinationDirPath = destinationDir.getAbsolutePath(); FileEntry[] fileEntries; if (parsedDestination.endsWith(File.separator)) { // pull source directory directly fileEntries = new FileEntry[] { sourceFileEntry }; } else { // pull the children of source directory only fileEntries = fileListingService.getChildren(sourceFileEntry, true, null); } message = "Pull of " + parsedSource + " to " + destinationDirPath + " from "; syncService.pull(fileEntries, destinationDirPath, new LogSyncProgressMonitor(getLog())); } else { // pulling file File parentDir = new File(FilenameUtils.getFullPath(parsedDestination)); if (!parentDir.exists()) { getLog().info("Creating destination directory " + parentDir); parentDir.mkdirs(); } String destinationFileName; if (parsedDestination.endsWith(File.separator)) { // keep original filename destinationFileName = FilenameUtils.getName(parsedSource); } else { // rename filename destinationFileName = FilenameUtils.getName(parsedDestination); } File destinationFile = new File(parentDir, destinationFileName); String destionationFilePath = destinationFile.getAbsolutePath(); message = "Pull of " + parsedSource + " to " + destionationFilePath + " from "; syncService.pullFile(sourceFileEntry, destionationFilePath, new LogSyncProgressMonitor(getLog())); } getLog().info(message + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ") successful."); } catch (SyncException e) { throw new MojoExecutionException( message + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ") failed.", e); } catch (IOException e) { throw new MojoExecutionException( message + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ") failed.", e); } catch (TimeoutException e) { throw new MojoExecutionException( message + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ") failed.", e); } catch (AdbCommandRejectedException e) { throw new MojoExecutionException( message + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ") failed.", e); } } }); }
From source file:com.jayway.maven.plugins.android.standalonemojos.PullMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { ConfigHandler configHandler = new ConfigHandler(this, this.session, this.execution); configHandler.parseConfiguration();// ww w . j a v a 2 s .c o m doWithDevices(new DeviceCallback() { public void doWithDevice(final IDevice device) throws MojoExecutionException { String deviceLogLinePrefix = DeviceHelper.getDeviceLogLinePrefix(device); // message will be set later according to the processed files String message = ""; try { SyncService syncService = device.getSyncService(); FileListingService fileListingService = device.getFileListingService(); FileEntry sourceFileEntry = getFileEntry(parsedSource, fileListingService); if (sourceFileEntry.isDirectory()) { // pulling directory File destinationDir = new File(parsedDestination); if (!destinationDir.exists()) { getLog().info("Creating destination directory " + destinationDir); destinationDir.mkdirs(); destinationDir.mkdir(); } String destinationDirPath = destinationDir.getAbsolutePath(); FileEntry[] fileEntries; if (parsedDestination.endsWith(File.separator)) { // pull source directory directly fileEntries = new FileEntry[] { sourceFileEntry }; } else { // pull the children of source directory only fileEntries = fileListingService.getChildren(sourceFileEntry, true, null); } message = deviceLogLinePrefix + "Pull of " + parsedSource + " to " + destinationDirPath + " from "; syncService.pull(fileEntries, destinationDirPath, new LogSyncProgressMonitor(getLog())); } else { // pulling file File parentDir = new File(FilenameUtils.getFullPath(parsedDestination)); if (!parentDir.exists()) { getLog().info(deviceLogLinePrefix + "Creating destination directory " + parentDir); parentDir.mkdirs(); } String destinationFileName; if (parsedDestination.endsWith(File.separator)) { // keep original filename destinationFileName = FilenameUtils.getName(parsedSource); } else { // rename filename destinationFileName = FilenameUtils.getName(parsedDestination); } File destinationFile = new File(parentDir, destinationFileName); String destinationFilePath = destinationFile.getAbsolutePath(); message = deviceLogLinePrefix + "Pull of " + parsedSource + " to " + destinationFilePath + " from " + DeviceHelper.getDescriptiveName(device); syncService.pullFile(sourceFileEntry, destinationFilePath, new LogSyncProgressMonitor(getLog())); } getLog().info(message + " successful."); } catch (SyncException e) { throw new MojoExecutionException(message + " failed.", e); } catch (IOException e) { throw new MojoExecutionException(message + " failed.", e); } catch (TimeoutException e) { throw new MojoExecutionException(message + " failed.", e); } catch (AdbCommandRejectedException e) { throw new MojoExecutionException(message + " failed.", e); } } }); }
From source file:com.andyasprou.webcrawler.Utilities.GenericSiteMapParser.java
/** * Parse a sitemap, given the content bytes and the URL. * * @param content// w w w. j av a2s.com * raw bytes of sitemap file * @param url * URL to sitemap file * @return Extracted SiteMap/SiteMapIndex * @throws UnknownFormatException if there is an error parsing the sitemap * @throws IOException if there is an error reading in the site map {@link java.net.URL} */ public AbstractSiteMap parseSiteMap(byte[] content, URL url) throws UnknownFormatException, IOException { if (url == null) { return null; } String filename = FilenameUtils.getName(url.getPath()); String contentType = TIKA.detect(content, filename); return parseSiteMap(contentType, content, url); }