List of usage examples for org.apache.commons.io FilenameUtils getBaseName
public static String getBaseName(String filename)
From source file:de.uzk.hki.da.convert.PublishImageConversionStrategy.java
/** *//*from www. j a va2 s . c o m*/ @Override public List<Event> convertFile(WorkArea wa, ConversionInstruction ci) throws FileNotFoundException { if (cliConnector == null) throw new IllegalStateException("cliConnector not set"); if (ci.getConversion_routine() == null) throw new IllegalStateException("conversionRoutine not set"); if (ci.getConversion_routine().getTarget_suffix() == null || ci.getConversion_routine().getTarget_suffix().isEmpty()) throw new IllegalStateException("target suffix in conversionRoutine not set"); List<Event> results = new ArrayList<Event>(); // connect dafile to package String input = wa.toFile(ci.getSource_file()).getAbsolutePath(); // Convert ArrayList<String> commandAsList = null; for (String audience : audiences) { Path.makeFile(wa.dataPath(), pips, audience.toLowerCase(), ci.getTarget_folder()).mkdirs(); commandAsList = new ArrayList<String>(); commandAsList.add("convert"); String sourceFileName = wa.toFile(ci.getSource_file()).getAbsolutePath() + "[0]"; commandAsList.add(sourceFileName); logger.debug(commandAsList.toString()); commandAsList = assembleResizeDimensionsCommand(commandAsList, audience); commandAsList = assembleWatermarkCommand(commandAsList, audience); commandAsList = assembleFooterTextCommand(commandAsList, audience, wa.toFile(ci.getSource_file()).getAbsolutePath()); DAFile target = new DAFile(pips + "/" + audience.toLowerCase(), StringUtilities.slashize(ci.getTarget_folder()) + FilenameUtils.getBaseName(input) + "." + ci.getConversion_routine().getTarget_suffix()); String targetFileName = wa.toFile(target).getAbsolutePath(); commandAsList.add(targetFileName); logger.debug(commandAsList.toString()); String[] commandAsArray = new String[commandAsList.size()]; commandAsArray = commandAsList.toArray(commandAsArray); FormatCmdLineExecutor cle = new FormatCmdLineExecutor(cliConnector, knownErrors); cle.setPruneExceptions(prune); String prunedError = ""; try { cle.execute(commandAsArray); } catch (UserFileFormatException ufe) { if (!prune) { throw ufe; } prunedError = " " + ufe.getKnownError().getError_name() + " ISSUED WAS PRUNED BY USER!"; } Event e = new Event(); e.setDetail(StringUtilities.createString(commandAsList) + prunedError); e.setSource_file(ci.getSource_file()); e.setTarget_file(target); e.setType("CONVERT"); e.setDate(new Date()); results.add(e); } return results; }
From source file:edu.cornell.med.icb.goby.modes.TallyBasesMode.java
/** * Configure./* w ww . ja va2 s . co m*/ * * @param args command line arguments * @return this object for chaining * @throws IOException error parsing * @throws JSAPException error parsing */ @Override public AbstractCommandLineMode configure(final String[] args) throws IOException, JSAPException { final JSAPResult jsapResult = parseJsapArguments(args); inputFilenames = jsapResult.getStringArray("input"); basenames = AlignmentReaderImpl.getBasenames(inputFilenames); alternativeCountArhive = jsapResult.getString("alternative-count-archive"); outputFilename = jsapResult.getString("output"); genomeFilename = jsapResult.getString("genome"); genomeCacheFilename = jsapResult.getString("genome-cache"); offsetString = jsapResult.getString("offset"); cutoff = jsapResult.getDouble("cutoff"); sampleRate = jsapResult.getDouble("sample-rate", 100d) / 100d; if (sampleRate == 0d) { System.err.println("Sample rate must be larger than zero or no positions will be reported."); System.exit(1); } if ("auto".equals(genomeCacheFilename)) { String filename = FilenameUtils.getBaseName(genomeFilename); filename = FilenameUtils.removeExtension(filename); genomeCacheFilename = filename + "-cache"; } final String includeReferenceNameCommas = jsapResult.getString("include-reference-names"); if (includeReferenceNameCommas != null) { includeReferenceNames = new ObjectOpenHashSet<String>(); includeReferenceNames.addAll(Arrays.asList(includeReferenceNameCommas.split("[,]"))); System.out.println("Will tally bases for the following sequences:"); for (final String name : includeReferenceNames) { System.out.println(name); } } return this; }
From source file:net.sourceforge.dita4publishers.tools.ditadxpmappackager.DitaDxpMapPackager.java
/** * @throws Exception //from w w w .j a va2 s . c o m * */ private void run() throws Exception { String mapFilepath = commandLine.getOptionValue("i"); File mapFile = new File(mapFilepath).getAbsoluteFile(); checkExistsAndCanReadSystemExit(mapFile); DitaDxpOptions dxpOptions = new DitaDxpOptions(); handleCommonBosProcessorOptions(dxpOptions); if (!dxpOptions.isQuiet()) System.err.println("Processing map \"" + mapFile.getAbsolutePath() + "\"..."); File outputZipFile = null; String outputFilepath = null; if (commandLine.hasOption(OUTPUT_OPTION_ONE_CHAR)) { outputFilepath = commandLine.getOptionValue(OUTPUT_OPTION_ONE_CHAR); outputZipFile = new File(outputFilepath).getAbsoluteFile(); } else { File parentDir = mapFile.getParentFile(); String nameBase = FilenameUtils.getBaseName(mapFile.getName()); outputZipFile = new File(parentDir, nameBase + DXP_EXTENSION); } File parentFile = outputZipFile.getParentFile(); parentFile.mkdirs(); if (!outputZipFile.getParentFile().canWrite()) { throw new RuntimeException("File " + outputZipFile.getAbsolutePath() + " cannot be written to."); } Document rootMap = null; BosConstructionOptions bosOptions = new BosConstructionOptions(log, new HashMap<URI, Document>()); bosOptions.setQuiet(dxpOptions.isQuiet()); boolean failOnAddressingFailure = false; if (commandLine.hasOption(ADDRESSING_FAILURE_OPTION_ONE_CHAR)) failOnAddressingFailure = true; bosOptions.setFailOnAddressResolutionFailure(failOnAddressingFailure); setupCatalogs(bosOptions); try { URL rootMapUrl = mapFile.toURI().toURL(); rootMap = DomUtil.getDomForUri(new URI(rootMapUrl.toExternalForm()), bosOptions); Date startTime = TimingUtils.getNowTime(); DitaBoundedObjectSet mapBos = DitaBosHelper.calculateMapBos(bosOptions, log, rootMap); if (!dxpOptions.isQuiet()) System.err.println("Map BOS construction took " + TimingUtils.reportElapsedTime(startTime)); // Do packaging here DitaDxpHelper.zipMapBos(mapBos, outputZipFile, dxpOptions); } catch (Exception e) { e.printStackTrace(); } finally { // Do final stuff here. } }
From source file:com.seleniumtests.reporter.logger.Snapshot.java
/** * Rename HTML and PNG files so that they do not present an uuid * New name is <test_name>_<step_idx>_<snapshot_idx>_<step_name>_<uuid> * @param testStep// www . ja v a2s. c o m * @param stepIdx number of this step * @param snapshotIdx number of this snapshot for this step * @param userGivenName name specified by user, rename to this name */ public void rename(final TestStep testStep, final int stepIdx, final int snapshotIdx, final String userGivenName) { String newBaseName; if (userGivenName == null) { newBaseName = String.format("%s_%d-%d_%s-", StringUtility.replaceOddCharsFromFileName(CommonReporter.getTestName(testStep.getTestResult())), stepIdx, snapshotIdx, StringUtility.replaceOddCharsFromFileName(testStep.getName())); } else { newBaseName = StringUtility.replaceOddCharsFromFileName(userGivenName); } if (screenshot.getHtmlSourcePath() != null) { String oldFullPath = screenshot.getFullHtmlPath(); String oldPath = screenshot.getHtmlSourcePath(); File oldFile = new File(oldPath); String folderName = ""; if (oldFile.getParent() != null) { folderName = oldFile.getParent().replace(File.separator, "/") + "/"; } String newName = newBaseName + FilenameUtils.getBaseName(oldFile.getName()); newName = newName.substring(0, Math.min(50, newName.length())) + "." + FilenameUtils.getExtension(oldFile.getName()); // if file cannot be moved, go back to old name try { oldFile = new File(oldFullPath); if (SeleniumTestsContextManager.getGlobalContext().getOptimizeReports()) { screenshot.setHtmlSourcePath(folderName + newName + ".zip"); oldFile = FileUtility.createZipArchiveFromFiles(Arrays.asList(oldFile)); } else { screenshot.setHtmlSourcePath(folderName + newName); } FileUtils.copyFile(oldFile, new File(screenshot.getFullHtmlPath())); new File(oldFullPath).delete(); } catch (IOException e) { screenshot.setHtmlSourcePath(oldPath); } } if (screenshot.getImagePath() != null) { String oldFullPath = screenshot.getFullImagePath(); String oldPath = screenshot.getImagePath(); File oldFile = new File(oldPath); String folderName = ""; if (oldFile.getParent() != null) { folderName = oldFile.getParent().replace(File.separator, "/") + "/"; } String newName = newBaseName + FilenameUtils.getBaseName(oldFile.getName()); newName = newName.substring(0, Math.min(50, newName.length())) + "." + FilenameUtils.getExtension(oldFile.getName()); screenshot.setImagePath(folderName + newName); // if file cannot be moved, go back to old name try { Files.move(Paths.get(oldFullPath), Paths.get(screenshot.getFullImagePath()), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { screenshot.setImagePath(oldPath); } } }
From source file:net.sourceforge.atunes.kernel.actions.LoadPlayListAction.java
@Override protected void executeAction() { IFileSelectorDialog dialog = this.dialogFactory.newDialog(IFileSelectorDialog.class); dialog.setFileFilter(this.playListIOService.getAllAcceptedPlaylistsFileFilter()); File file = dialog.loadFile(this.statePlaylist.getLoadPlaylistPath()); if (file != null) { // If exists... if (file.exists()) { this.statePlaylist.setLoadPlaylistPath(FileUtils.getPath(file.getParentFile())); if (this.playListIOService.isDynamicPlayList(file)) { this.playListIOService.readDynamicPlayList(file); } else { // Read file names List<String> filesToLoad = this.playListIOService.read(file); // Background loading - but only when returned array is not // null // (Progress dialog hangs otherwise) if (filesToLoad != null) { LoadPlayListProcess process = (LoadPlayListProcess) this.processFactory .getProcessByName("loadPlayListProcess"); process.setFilenamesToLoad(filesToLoad); process.setReplacePlayList(this.replacePlayList); process.setPlayListName(FilenameUtils.getBaseName(file.getName())); process.execute();/* ww w . j a v a2s. c om*/ } } } else { this.dialogFactory.newDialog(IErrorDialog.class) .showErrorDialog(I18nUtils.getString("FILE_NOT_FOUND")); } } }
From source file:logic.Export.java
public boolean convertXls() throws IOException, FileNotFoundException, IllegalArgumentException, ParseException { FileInputStream tamplateFile = new FileInputStream(templatePath); XSSFWorkbook workbook = new XSSFWorkbook(tamplateFile); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("#,##")); double hours = 0.0; NumberFormat format = NumberFormat.getInstance(Locale.FRANCE); Number number;/* w w w.j a v a2 s.c om*/ XSSFSheet sheet; XSSFSheet sheet2; Cell cell = null; ConvertData cd = new ConvertData(); for (int i = 0; i < cd.getSheetnames().size(); i++) { sheet2 = workbook.cloneSheet(0, cd.sheetnames.get(i)); sheet = workbook.getSheetAt(i + 1); //formate sheets sheet.getPrintSetup().setLandscape(true); sheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); cell = sheet.getRow(0).getCell(1); cell.setCellValue(cd.sheetnames.get(i)); ArrayList<String[]> convert = cd.convert(cd.sheetnames.get(i)); //setPrintArea workbook.setPrintArea(i + 1, //sheet index 0, //start column Spalte 6, //end column 0, //start row zeile convert.size() + 8 //end row ); for (int Row = 0; Row < convert.size(); Row++) { for (int Cell = 0; Cell < convert.get(Row).length; Cell++) { cell = sheet.getRow(9 + Row).getCell(Cell); if (Cell == 3) { if ("true".equals(convert.get(Row)[Cell])) { XSSFCellStyle style1 = workbook.createCellStyle(); style1 = (XSSFCellStyle) cell.getCellStyle(); style1 = (XSSFCellStyle) style1.clone(); style1.setFillBackgroundColor(HSSFColor.RED.index); style1.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); XSSFColor myColor = new XSSFColor(Color.RED); style1.setFillForegroundColor(myColor); sheet.getRow(9 + Row).getCell(6).setCellStyle(style1); } } else { cell.setCellValue(convert.get(Row)[Cell]); } } } } workbook.removeSheetAt(0); tamplateFile.close(); File exportFile = newPath.getSelectedFile(); if (FilenameUtils.getExtension(exportFile.getName()).equalsIgnoreCase("xlsx")) { } else { exportFile = new File(exportFile.getParentFile(), FilenameUtils.getBaseName(exportFile.getName()) + ".xlsx"); } FileOutputStream outFile = new FileOutputStream(exportFile); workbook.write(outFile); outFile.close(); tamplateFile.close(); return true; }
From source file:com.nuvolect.securesuite.util.OmniUtil.java
/** * Return a unique file given the current file as a model. * Example if file exists: /Picture/mypic.jpg > /Picture/mypic~.jpg * @return//from w ww .j av a 2 s. c o m */ public static OmniFile makeUniqueName(OmniFile initialFile) { String path = initialFile.getPath(); String basePath = FilenameUtils.getFullPath(path); // path without name String baseName = FilenameUtils.getBaseName(path); // name without extension String extension = FilenameUtils.getExtension(path); // extension String volumeId = initialFile.getVolumeId(); String dot = "."; if (extension.isEmpty()) dot = ""; OmniFile file = initialFile; while (file.exists()) { // LogUtil.log("File exists: "+file.getPath()); baseName += "~"; String fullPath = basePath + baseName + dot + extension; file = new OmniFile(volumeId, fullPath); } // LogUtil.log("File unique: "+file.getPath()); return file; }
From source file:com.dattack.naming.loader.NamingLoader.java
/** * Scans a directory hierarchy looking for <code>*.properties</code> files. Creates a subcontext for each directory * in the hierarchy and binds a new resource for each <code>*.properties</code> file with a * <code>ResourceFactory</code> associated. * * * @param directory//from w w w .j a v a2 s . c o m * the directory to scan * @param ctxt * the Context to populate * @param extraClasspath * additional paths to include to the classpath * @throws NamingException * if a naming exception is encountered * @throws IOException * if an I/O error occurs */ public void loadDirectory(final File directory, final Context ctxt, final Collection<File> extraClasspath) throws NamingException, IOException { if (!directory.isDirectory()) { throw new IllegalArgumentException(String.format("'%s' isn't a directory", directory)); } final File[] files = directory.listFiles(); if (files == null) { return; } for (final File file : files) { if (file.isDirectory()) { final Context subcontext = ctxt.createSubcontext(file.getName()); loadDirectory(file, subcontext, extraClasspath); } else { final String fileName = file.getName(); if (FilenameUtils.isExtension(fileName, EXTENSIONS)) { final String baseName = FilenameUtils.getBaseName(fileName); try (FileInputStream fin = new FileInputStream(file)) { final Properties properties = new Properties(); properties.load(fin); createAndBind(properties, ctxt, baseName, extraClasspath); } } } } }
From source file:com.nabla.wapp.report.server.handler.AddReportHandler.java
@Override protected int add(AddReport record, IUserSessionContext ctx) throws DispatchException, SQLException { int id;/*from w w w. jav a2s . c o m*/ final Connection conn = ctx.getWriteConnection(); final PreparedStatement stmt = StatementFormat.prepare(ctx.getReadConnection(), "SELECT * FROM import_data WHERE id=?;", record.getFileId()); try { final ResultSet rs = stmt.executeQuery(); try { if (!rs.next()) throw new ActionException(CommonServerErrors.NO_DATA); if (!ctx.getSessionId().equals(rs.getString("userSessionId"))) throw new ActionException(CommonServerErrors.ACCESS_DENIED); final ConnectionTransactionGuard guard = new ConnectionTransactionGuard(conn); try { if (ReportZipFile.acceptContentType(rs.getString("content_type"))) { final ReportZipFile zip = new ReportZipFile(rs.getBinaryStream("content")); try { final ZipArchiveEntry design = zip.getReportDesign(); if (design == null) throw new DispatchException(ReportErrors.ADD_REPORT_NO_REPORT_DESIGN_FOUND); id = reportManager.addReport(conn, design.getName(), zip.getInputStream(design), zip.getInputStream(design)); for (Enumeration<ZipArchiveEntry> iter = zip .getEntries(ReportManager.PROPERTIES_FILE_EXTENSION); iter.hasMoreElements();) { final ZipArchiveEntry e = iter.nextElement(); reportManager.loadLocaleReportName(conn, id, e.getName(), zip.getInputStream(e)); } for (Enumeration<ZipArchiveEntry> iter = zip .getEntries(ReportManager.RESOURCE_FILE_EXTENSIONS); iter.hasMoreElements();) { final ZipArchiveEntry e = iter.nextElement(); reportManager.loadReportResource(conn, id, e.getName(), zip.getInputStream(e)); } } finally { zip.close(); } } else { id = reportManager.addReport(conn, FilenameUtils.getBaseName(rs.getString("file_name")), rs.getBinaryStream("content"), rs.getBinaryStream("content")); } guard.setSuccess(); } finally { guard.close(); } } finally { rs.close(); } } finally { stmt.close(); } Database.executeUpdate(conn, "DELETE FROM import_data WHERE id=?;", record.getFileId()); return id; }
From source file:com.frostwire.search.youtube.YouTubeSearchPerformer.java
/** * Picks the highest quality audio link at the lowest size possible. * @param list//from w w w. j ava 2 s . c o m * @return */ private YouTubeDownloadLink getAudioLink(List<YouTubeDownloadLink> list) { YouTubeDownloadLink result = null; YouTubeDownloadLink result1 = null; YouTubeDownloadLink result2 = null; YouTubeDownloadLink result3 = null; String qualityStr = null; for (YouTubeDownloadLink link : list) { int iTag = link.getITag(); if (iTag == 22) { result1 = link; } if (iTag == 37) { result2 = link; } if (iTag == 18) { result3 = link; } } if (result1 != null) { result = result1; qualityStr = "_192k.m4a"; } else if (result2 != null) { result = result2; qualityStr = "_192k.m4a"; } else if (result3 != null) { result = result3; qualityStr = "_96k.m4a"; } if (result != null) { String filename = FilenameUtils.getBaseName(result.getFilename()) + qualityStr; result = new YouTubeDownloadLink(filename, result.getSize(), result.getDownloadUrl(), result.getITag(), true); } return result; }