List of usage examples for org.apache.commons.io FilenameUtils getBaseName
public static String getBaseName(String filename)
From source file:edu.si.services.camel.extractor.ExtractorProducer.java
@Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn();/*from ww w. java 2 s . c o m*/ File archiveFile = in.getBody(File.class); LOG.debug("Archive file to extract: {}", archiveFile.getName()); String archiveFileBaseName = FilenameUtils.getBaseName(archiveFile.getName()); String archiveFileExt = FilenameUtils.getExtension(archiveFile.getName()); LOG.debug("Found archive file baseName={}, ext= {}", archiveFileBaseName, archiveFileExt); if (archiveFileExt == null || archiveFileExt.isEmpty()) { errorMsg = new StringBuilder(); errorMsg.append("Improperly formatted file. No, file extension found for " + archiveFile.getName()); LOG.error(errorMsg.toString()); throw new ExtractorException(errorMsg.toString()); } //Set location to extract to File cameraTrapDataOutputDir = new File(this.endpoint.getLocation(), archiveFileBaseName); //The ArchiveFactory can detect archive types based on file extensions and hand you the correct Archiver. Archiver archiver = ArchiverFactory.createArchiver(archiveFile); LOG.debug("Archive type: {}", archiver.getFilenameExtension()); //Stream the archive rather then extracting directly to the file system. ArchiveStream archiveStream = archiver.stream(archiveFile); ArchiveEntry entry; //Extract each archive entry and check for the existence of a compressed folder otherwise create one while ((entry = archiveStream.getNextEntry()) != null) { LOG.debug("ArchiveStream Current Entry Name = {}, isDirectory = {}", entry.getName(), entry.isDirectory()); //Check for a compressed folder if (entry.isDirectory()) { errorMsg = new StringBuilder(); errorMsg.append("Extracting archive '" + archiveFile.getName() + "' failed! "); errorMsg.append("Directory '" + entry.getName() + "' found in archive!"); log.error(errorMsg.toString()); throw new ExtractorException(errorMsg.toString()); } else { entry.extract(cameraTrapDataOutputDir); //extract the file } } archiveStream.close(); LOG.debug("File path to be returned on exchange body: {}", cameraTrapDataOutputDir); String parent = null; if (cameraTrapDataOutputDir.getParentFile() != null) { parent = cameraTrapDataOutputDir.getParentFile().getName(); LOG.debug("CamelFileParent: {}", cameraTrapDataOutputDir.getParentFile()); } Map<String, Object> headers = in.getHeaders(); headers.put("CamelFileLength", cameraTrapDataOutputDir.length()); headers.put("CamelFileLastModified", cameraTrapDataOutputDir.lastModified()); headers.put("CamelFileNameOnly", cameraTrapDataOutputDir.getName()); headers.put("CamelFileNameConsumed", cameraTrapDataOutputDir.getName()); headers.put("CamelFileName", cameraTrapDataOutputDir.getName()); headers.put("CamelFileRelativePath", cameraTrapDataOutputDir.getPath()); headers.put("CamelFilePath", cameraTrapDataOutputDir.getPath()); headers.put("CamelFileAbsolutePath", cameraTrapDataOutputDir.getAbsolutePath()); headers.put("CamelFileAbsolute", false); headers.put("CamelFileParent", parent); LOG.debug("Headers: {}", headers); exchange.getOut().setBody(cameraTrapDataOutputDir, File.class); exchange.getOut().setHeaders(headers); }
From source file:net.sf.firemox.AbstractMainForm.java
/** * Initialize the components of this form. *///from w w w.java 2 s .c o m protected void initAbstractMenu() { // "TBS" menu tbsMenu = UIHelper.buildMenu("menu_options_tbs"); ButtonGroup group4 = new ButtonGroup(); final MdbListener mdbListener = new MdbListener(this); final File[] mdbs = MToolKit.getFile(IdConst.TBS_DIR) .listFiles((FileFilter) FileFilterUtils.suffixFileFilter("xml")); String defaultTbs = MToolKit.tbsName; for (File mdb : mdbs) { String mdbName = FilenameUtils.getBaseName(mdb.getName()); JRadioButtonMenuItem itemChck = new JRadioButtonMenuItem(); MToolKit.tbsName = mdbName; updateMdbMenu(mdbName, itemChck); itemChck.setActionCommand(mdbName); itemChck.setFont(MToolKit.defaultFont); itemChck.addActionListener(mdbListener); group4.add(itemChck); tbsMenu.add(itemChck); if (mdbName.equals(defaultTbs)) { itemChck.setSelected(true); } } MToolKit.tbsName = defaultTbs; tbsMenu.add(new JSeparator()); // "More TBS" menu item tbsMenu.add(UIHelper.buildMenu("menu_options_tbs_more", mdbListener)); tbsMenu.add(new JSeparator()); final JMenuItem updateMdbMenu = UIHelper.buildMenu("menu_options_tbs_update", mdbListener); updateMdbMenu.setEnabled(false); tbsMenu.add(updateMdbMenu); tbsMenu.add(UIHelper.buildMenu("menu_options_tbs_rebuild", mdbListener)); optionMenu.add(new JSeparator()); optionMenu.add(tbsMenu); }
From source file:com.bt.download.android.gui.adapters.menu.RenameFileMenuAction.java
private void renameFile(String newFileName) { String newPath = Librarian.instance().renameFile(fd, newFileName); fd.filePath = newPath;//from www. j av a 2 s . co m fd.title = FilenameUtils.getBaseName(newFileName); }
From source file:de.uzk.hki.da.format.PublishAudioConversionStrategy.java
@Override public List<Event> convertFile(ConversionInstruction ci) throws FileNotFoundException { if (object == null) throw new IllegalStateException("object not set"); if (cliConnector == null) throw new IllegalStateException("cliConnector not set"); Path.makeFile(object.getDataPath(), pips, "public", ci.getTarget_folder()).mkdirs(); Path.makeFile(object.getDataPath(), pips, "institution", ci.getTarget_folder()).mkdirs(); List<Event> results = new ArrayList<Event>(); for (String audience : audiences) { Path source = Path.make(ci.getSource_file().toRegularFile().getAbsolutePath()); Path target = Path.make(object.getDataPath(), pips, audience.toLowerCase(), ci.getTarget_folder(), FilenameUtils.getBaseName(ci.getSource_file().toRegularFile().getAbsolutePath()) + ".mp3"); logger.debug(/*from w ww. j av a2s. c o m*/ "source:" + FilenameUtils.getBaseName(ci.getSource_file().toRegularFile().getAbsolutePath())); String cmdPUBLIC[] = new String[] { "sox", source.toString(), target.toString() }; logger.debug("source:" + source); logger.debug("target:" + target); if (!cliConnector.execute( (String[]) ArrayUtils.addAll(cmdPUBLIC, getDurationRestrictionsForAudience(audience)))) { throw new RuntimeException("command not succeeded"); } DAFile f1 = new DAFile(object.getLatestPackage(), pips + "/" + audience.toLowerCase(), Utilities.slashize(ci.getTarget_folder()) + FilenameUtils.getBaseName(ci.getSource_file().toRegularFile().getAbsolutePath()) + ".mp3"); Event e = new Event(); e.setType("CONVERT"); e.setSource_file(ci.getSource_file()); e.setTarget_file(f1); e.setDetail(Utilities.createString(cmdPUBLIC)); e.setDate(new Date()); results.add(e); } return results; }
From source file:net.sf.firemox.xml.tbs.Card.java
/** * <ul>// ww w . j a v a 2 s. c om * Structure of stream : Data[size] * <li>card model</li> * </ul> * * @param node * the XML card structure * @param out * output stream where the card structure will be saved * @return the amount of written action in the output. * @see net.sf.firemox.clickable.target.card.MCard * @throws IOException * error while writing. */ public final int buildMdb(Node node, OutputStream out) throws IOException { // card name String cardName = node.getAttribute("name"); if (cardName == null || cardName.length() == 0) { XmlConfiguration.error("Null card name found in '" + node.getAttribute("xmlFile") + "'"); cardName = FilenameUtils.getBaseName(node.getAttribute("xmlFile")).toLowerCase(); } String xmlFile = node.getAttribute("xmlFile"); if (xmlFile != null && !FilenameUtils.getBaseName(xmlFile).toLowerCase() .equalsIgnoreCase(MToolKit.getKeyName(cardName))) { XmlConfiguration.error("Card '" + cardName + "' should be definied in it's own file, not '" + node.getAttribute("xmlFile") + "'"); } // Write the card name using the pager XmlTbs.cardPager.addReference(out, cardName); // credits final Node credits = node.get("rules-author-comment"); if (credits != null && credits.get(0) != null) { if (credits.get(0).toString().startsWith("Oracle2Xml")) { XmlConfiguration.uncompleted(); } MToolKit.writeString(out, credits.get(0).toString()); } else { MToolKit.writeString(out, null); } // keywords Node keywords = node.get("keywords"); if (keywords != null && keywords.get(0) != null) { String[] words = keywords.get(0).toString().split(" "); out.write(words.length); for (String keyword : words) { MToolKit.writeString(out, keyword); } } else { out.write(0); } final Node init = node.get("init"); // initialize the additional modifier list final List<Node> modifierNodes = new ArrayList<Node>(); // registers byte[] registersBytes = new byte[IdTokens.CARD_REGISTER_SIZE]; if (init != null) { Node registers = init.get("registers"); if (registers != null) { final List<Node> list = registers.getNodes("register"); for (Node register : list) { if (register.getAttribute("value") == null) { // add this node that should contain a register modifier modifierNodes.add(register); } else { registersBytes[XmlTools.getInt(register.getAttribute("index"))] = (byte) XmlTools .getInt(register.getAttribute("value")); } } } } out.write(registersBytes); // id card int idCard = 0; int decr = 0; if (init != null) { Node idcards = init.get("idcards"); if (idcards != null && idcards.get(0) != null) { String list = ((String) idcards.get(0)).trim(); String[] arrayid = list.split(" "); for (String id : arrayid) { if (id.trim().length() > 0) { idCard |= XmlTools.getIdCard(id); } } } } MToolKit.writeInt16(out, idCard); // color int idColor = 0; if (init != null) { Node colors = init.get("colors"); if (colors != null && colors.get(0) != null) { String list = ((String) colors.get(0)).trim(); String[] arrayid = list.split(" "); for (String id : arrayid) { if (id.trim().length() > 0) { idColor |= XmlTools.getColor(id); } } } } out.write(idColor); // properties if (init != null) { Node properties = init.get("properties"); if (properties == null) { out.write(0); } else { Object strProperties = properties.get(0); String list = null; if (strProperties == null) { list = ""; } else { list = ((String) strProperties).trim(); } String[] arrayid = list.split(" "); decr = 0; for (int i = arrayid.length; i-- > 0;) { arrayid[i] = arrayid[i].trim(); if (arrayid[i].length() == 0) { decr++; } } int[] arrayIdSorted = new int[arrayid.length - decr]; out.write(arrayIdSorted.length); // get int values associated to properties name decr = 0; for (String id : arrayid) { if (id.length() > 0) { arrayIdSorted[decr++] = XmlTools.getInt(id); } } // sort the properties values Arrays.sort(arrayIdSorted); // write the sorted properties values for (int id : arrayIdSorted) { MToolKit.writeInt16(out, id); } } } else { out.write(0); } // actions Node actions = node.get("actions"); if (actions != null) { for (Object obj : actions) { if (obj instanceof Node) { String ref = ((Node) obj).getAttribute("reference-name"); List<Node> actionList = new ArrayList<Node>(); for (Object actionI : (Node) obj) { if (actionI instanceof Node) { // add action to the action list ((Node) actionI).addAttribute(new XmlParser.Attribute("name", ref)); actionList.add((Node) actionI); } } // add this reference if (XmlTbs.referencedActions == null) { XmlTbs.referencedActions = new HashMap<String, List<Node>>(); } XmlTbs.referencedActions.put(ref, actionList); } } } // abilities Node abilities = node.get("abilities"); if (abilities == null) { out.write(0); } else { out.write(abilities.getNbNodes()); for (Object obj : abilities) { if (obj instanceof Node) { Node ability = (Node) obj; String ref = ability.getAttribute("reference-name"); if (ref != null && ref.length() > 0) { if (XmlTbs.referencedAbilities == null) { XmlTbs.referencedAbilities = new HashMap<String, Node>(); } XmlTbs.referencedAbilities.put(ref, (Node) obj); } XmlTbs.getTbsComponent(ability.getTag()).buildMdb(ability, out); // add this reference } } } // register indirections Node modifiers = node.get("modifiers"); if (modifiers == null) { out.write(modifierNodes.size()); } else { out.write(modifiers.getNbNodes() + modifierNodes.size()); // explicitly declared modifiers for (Object obj : modifiers) { if (obj instanceof Node) { XmlModifier.getModifier(((Node) obj).getTag()).buildMdb((Node) obj, out); } } } if (!modifierNodes.isEmpty()) { // there are some additional register indirections to add for (Node nodeModifier : modifierNodes) { if (nodeModifier.get("value") != null) { // this indirection has as value a counter boolean oldValue = XmlTools.defaultOnMeTag; XmlTools.defaultOnMeTag = false; XmlModifier.getModifier("register-indirection").buildMdb(nodeModifier, out); XmlTools.defaultOnMeTag = oldValue; } else { XmlConfiguration.error("The specified modifier for this register is unknown; " + nodeModifier); return 0; } } } // attachment Node attachment = node.get("attachment"); if (attachment == null) { out.write(0); } else { out.write(1); Node referenceModifiers = null; if (attachment.getAttribute("ref") != null) { referenceModifiers = attachment.get("modifiers"); attachment = XmlTbs.getReferencedAttachment(attachment.getAttribute("ref")); } if (attachment == null) // reference error return 0; Node attachmentModifiers = attachment.get("modifiers"); if (referenceModifiers == null) { if (attachmentModifiers == null) { out.write(0); } else { out.write(attachmentModifiers.getNbNodes()); } } else { if (attachmentModifiers == null) out.write(referenceModifiers.getNbNodes()); else { out.write(attachmentModifiers.getNbNodes() + referenceModifiers.getNbNodes()); } // macro modifiers for (Object obj : referenceModifiers) { if (obj instanceof Node) { XmlModifier.getModifier(((Node) obj).getTag()).buildMdb((Node) obj, out); } } } // explicitly declared modifiers if (attachmentModifiers != null) { for (Object obj : attachmentModifiers) { if (obj instanceof Node) { XmlModifier.getModifier(((Node) obj).getTag()).buildMdb((Node) obj, out); } } } XmlTest.getTest("test").buildMdb(attachment.get("valid-target"), out); XmlTest.getTest("test").buildMdb(attachment.get("valid-attachment"), out); } return 0; }
From source file:com.salsaw.msalsa.HomePagePresenter.java
@Override public void buttonClick(File file) throws SALSAException, IOException, InterruptedException { // Get path to correct Clustal process switch (salsaParameters.getClustalType()) { case CLUSTAL_W: salsaParameters.setClustalPath(//ww w.j ava 2s. c om ConfigurationManager.getInstance().getServerConfiguration().getClustalW().getAbsolutePath()); break; case CLUSTAL_O: salsaParameters.setClustalPath( ConfigurationManager.getInstance().getServerConfiguration().getClustalO().getAbsolutePath()); break; } salsaParameters.setClustalWPath( ConfigurationManager.getInstance().getServerConfiguration().getClustalW().getAbsolutePath()); // Create M-SALSA output file name salsaParameters.setInputFile(file.getAbsolutePath()); String inputFileName = FilenameUtils.getBaseName(file.getAbsolutePath()); salsaParameters.setOutputFile( Paths.get(ConfigurationManager.getInstance().getServerConfiguration().getTemporaryFilePath(), inputFileName + "-msalsa-aln.fasta").toString()); SalsaAlgorithmExecutor.callClustal(salsaParameters); // Store path where files has been generated ClustalFileMapper clustalFileMapper = new ClustalFileMapper(file.getAbsolutePath()); clustalFileMapper.setAlignmentFilePath(salsaParameters.getOutputFile()); clustalFileMapper.setPhylogeneticTreeFile( Paths.get(ConfigurationManager.getInstance().getServerConfiguration().getTemporaryFilePath(), inputFileName + "-msalsa-aln.ph").toString()); // Show view with results final PhylogeneticTreeView testTreeView = new PhylogeneticTreeView(clustalFileMapper); navigator.addView(PROCESSED, testTreeView); navigator.navigateTo(PROCESSED); }
From source file:com.frostwire.search.youtube2.YouTubeCrawledSearchResult.java
private String buildDisplayName(String filename2) { String fname = FilenameUtils.getBaseName(filename); if (fname.indexOf(AAC_HIGH_QUALITY) > 0) { return AAC_HIGH_QUALITY + " " + fname.replace(AAC_HIGH_QUALITY, ""); } else if (fname.indexOf(AAC_LOW_QUALITY) > 0) { return AAC_LOW_QUALITY + " " + fname.replace(AAC_LOW_QUALITY, ""); }//from w w w . j ava 2 s . co m return fname; }
From source file:cu.uci.uengine.runner.impl.FileRunner.java
@Override public RunnerResult run(Runnable runnable, RunnerContext runnerContext) throws IOException, InterruptedException { String command = buildCommand(runnable.getLanguageName(), runnable.getRunnableFile().getAbsolutePath(), runnerContext.getTemporaryDirectory().getAbsolutePath()); log.debug("Running dataset " + runnerContext.getInputFile().getName()); String name = FilenameUtils.getBaseName(runnerContext.getInputFile().getName()); File outFile = new File(runnerContext.getTemporaryDirectory(), name + ".out"); File errFile = new File(runnerContext.getTemporaryDirectory(), name + ".err"); ProcessBuilder pb = buildProcessBuilder(runnable.getLimits(), runnable.getLanguageName(), runnerContext.getInputFile().getAbsolutePath(), outFile, errFile, command, String.valueOf(runnable.getId()), runnable.isTrusted()); Process process = pb.start(); process.waitFor();//from w ww . ja v a 2 s. c o m if (process.exitValue() != 0) { byte[] processError = new byte[process.getErrorStream().available()]; process.getErrorStream().read(processError); return new RunnerResult(RunnerResult.Result.IE, FileUtils.readFileToString(errFile) + new String(processError)); } // result,usertime,cputime,memory String[] results = IOUtils.toString(process.getInputStream()).split(","); // el resultado OK significa que no dio problema ejecutar // con libsandbox. Los demas resultados son errores internos // o resultados que no precisan que se siga ejecutando (TLE, // MLE, etc.) // En OK se debe seguir con el proximo juego de datos, los // demas resultados ya detienen la ejecucion. RunnerResult result = null; String resultCode = results[SandboxResults.RESULT]; switch (resultCode) { case "OK": result = new RunnerResult(RunnerResult.Result.OK, name, Long.valueOf(results[SandboxResults.USER_TIME]), Long.valueOf(results[SandboxResults.CPU_TIME]), Long.valueOf(results[SandboxResults.MEMORY]) * 1024); break; case "AT": result = new RunnerResult(RunnerResult.Result.RT); result.messageConcat(FileUtils.readFileToString(errFile)); break; case "TL": result = new RunnerResult(RunnerResult.Result.CTL); break; case "RF": case "ML": case "OL": case "RT": case "IE": case "BP": case "PD": result = new RunnerResult(RunnerResult.Result.valueOf(resultCode)); result.messageConcat(FileUtils.readFileToString(errFile)); break; } if (outFile.length() > runnable.getLimits().getMaxOutput()) { result = new RunnerResult(RunnerResult.Result.OL); } return result; }
From source file:MSUmpire.DIA.RTMappingExtLib.java
public void GenerateModel() throws IOException { XYPointCollection points = new XYPointCollection(); XYSeries series = new XYSeries("Peptide ions"); XYSeriesCollection xySeriesCollection = new XYSeriesCollection(); FileWriter writer = new FileWriter(FilenameUtils.getFullPath(TargetLCMS.mzXMLFileName) + "/" + FilenameUtils.getBaseName(TargetLCMS.mzXMLFileName) + "_" + libManager.LibID + "_RTMapPoints.txt"); for (String pepkey : libManager.PeptideFragmentLib.keySet()) { if (TargetLCMS.GetPepIonList().containsKey(pepkey)) { PepFragmentLib peplib = libManager.GetFragmentLib(pepkey); for (float rt : peplib.RetentionTime) { float y = TargetLCMS.GetPepIonList().get(pepkey).GetRT(); points.AddPoint(rt, y);/*from w ww . ja va2 s. co m*/ series.add(new XYDataItem(rt, y)); writer.write(rt + "\t" + y + "\n"); } } } writer.close(); regression = new PiecewiseRegression(parameter.MaxCurveRTRange, parameter.MaxCurveRTRange); regression.SetData(points); float R2 = regression.GetR2(); Logger.getRootLogger() .info("Retention time prediction model:(" + FilenameUtils.getBaseName(TargetLCMS.mzXMLFileName) + "..R2=" + R2 + "(No. of commonly identified peptide ions=" + points.PointCount() + ")"); GenerateRTMapPNG(xySeriesCollection, series, R2); }
From source file:com.dhenton9000.file.FileWatchers.java
/** * generate a runnable that will process a file on a thread * * @param file file to process//w ww . j a va 2 s . c om * @return the constructed runnable */ private Runnable getRunnable(final File file, final IReaderSink sink) { return new Runnable() { @Override public void run() { //move from inputDir to tempDir File tempFile = new File(tempDir, FilenameUtils.getBaseName(file.getAbsolutePath()) + "_tmp.txt"); String simpleName = FilenameUtils.getName(tempFile.getAbsolutePath()); try { FileUtils.copyFile(file, tempFile); FileUtils.deleteQuietly(file); } catch (IOException ex) { LOG.error("problem moving to temp " + ex.getMessage()); } LOG.info("$#$move done " + simpleName); try { LOG.info("$#$processing " + tempFile.getAbsolutePath()); FileReader in = new FileReader(tempFile); BufferedReader bRead = new BufferedReader(in); String line = bRead.readLine(); //skipping the header //output the line while (line != null) { line = bRead.readLine(); if (line != null) { LOG.debug(simpleName + " " + line.substring(0, 10) + "..."); if (sink != null) { sink.report(line); } } } // parse each file into individual events // } catch (Exception e) { LOG.error("$#$tried to process csv " + e.getClass().getName() + " " + e.getMessage()); } } }; }