List of usage examples for org.apache.commons.io FilenameUtils getBaseName
public static String getBaseName(String filename)
From source file:ch.unibas.charmmtools.gui.step1.mdAssistant.CHARMM_GUI_InputAssistant.java
private File convertWithBabel(File xyz) { String parent = FilenameUtils.getFullPath(xyz.getAbsolutePath()); String basename = FilenameUtils.getBaseName(xyz.getAbsolutePath()); File pdbOut = new File(parent + basename + ".pdb"); BabelConverterAPI babelc = new BabelConverterAPI("xyz", "pdb"); babelc.convert(xyz, pdbOut);/* w w w .j a v a2s . c o m*/ if (pdbOut.exists()) { try { logger.info("Content of pdb file obtained from babel : \n" + Files.readAllBytes(Paths.get(pdbOut.getAbsolutePath()))); } catch (IOException ex) { } } return pdbOut; }
From source file:com.googlecode.fascinator.portal.services.cache.JythonCacheEntryFactory.java
/** * Creates a jython object instance for the script cache. * /*from ww w.j a v a2 s . c o m*/ * @param key the path to the jython script * @return an instantiated jython object * @throws Exception if the jython object failed to be instantiated */ @Override public Object createEntry(Object key) throws Exception { // log.debug("createEntry({})", key); String path = key.toString(); int qmarkPos = path.lastIndexOf("?"); if (qmarkPos != -1) { path = path.substring(0, qmarkPos); } int slashPos = path.indexOf("/"); String portalId = path.substring(0, slashPos); PyObject scriptObject = null; InputStream in = velocityService.getResource(path); if (in == null) { log.debug("Failed to load script: '{}'", path); } else { // add current and default portal directories to python sys.path addSysPaths(portalId, Py.getSystemState()); // setup the python interpreter PythonInterpreter python = PythonInterpreter.threadLocalStateInterpreter(null); // expose services for backward compatibility - deprecated python.set("Services", scriptingServices); // python.setLocals(scriptObject); JythonLogger jythonLogger = new JythonLogger(path); python.setOut(jythonLogger); python.setErr(jythonLogger); python.execfile(in, path); String scriptClassName = StringUtils.capitalize(FilenameUtils.getBaseName(path)) + "Data"; PyObject scriptClass = python.get(scriptClassName); if (scriptClass != null) { scriptObject = scriptClass.__call__(); } else { log.debug("Failed to find class '{}'", scriptClassName); } python.cleanup(); } return scriptObject; }
From source file:edu.cornell.med.icb.goby.modes.RunParallelMode.java
public void execute() throws IOException { final Slice slices[] = new Slice[numParts]; File file = new File(input); if (!(file.isFile() && file.exists() && file.canRead())) { System.err.println("Input file cannot be read: " + input); System.exit(1);/*from w w w .j a v a 2s . c om*/ } int i = 0; for (final Slice slice : slices) { slices[i++] = new Slice(); } final long fileLength = file.length(); final long sliceLength = fileLength / numParts; long currentOffset = 0; for (final Slice slice : slices) { slice.startOffset = currentOffset; slice.endOffset = currentOffset + sliceLength; currentOffset = slice.endOffset; } final ObjectOpenHashSet<String> allOutputs = new ObjectOpenHashSet<String>(); final ObjectOpenHashSet<String> allFastq = new ObjectOpenHashSet<String>(); final DoInParallel loop = new DoInParallel(numParts) { IsDone done = new IsDone(); @Override public void action(final DoInParallel forDataAccess, final String inputBasename, final int loopIndex) { try { CompactToFastaMode ctfm = new CompactToFastaMode(); ctfm.setInputFilename(input); ctfm.setOutputFormat(CompactToFastaMode.OutputFormat.FASTQ); ctfm.setStartPosition(slices[loopIndex].startOffset); ctfm.setEndPosition(slices[loopIndex].endOffset); String s = FilenameUtils.getBaseName(FilenameUtils.removeExtension(input)) + "-" + Integer.toString(loopIndex); String fastqFilename = s + "-input.fq"; allFastq.add(fastqFilename); File tmp1 = new File(s + "-tmp"); tmp1.deleteOnExit(); File output = new File(s + "-out"); output.deleteOnExit(); ctfm.setOutputFilename(fastqFilename); LOG.info(String.format("Extracting FASTQ for slice [%d-%d] loopIndex=%d %n", slices[loopIndex].startOffset, slices[loopIndex].endOffset, loopIndex)); ctfm.execute(); if (loopIndex > 0) { while (!done.isDone()) { // wait a bit to give the first thread the time to load the database and establish shared memory pool // System.out.println("sleep 5 thread "+loopIndex); sleep(5); } System.out.println("Thread " + loopIndex + " can now start."); } final Map<String, String> replacements = new HashMap<String, String>(); final String outputFilename = output.getName(); replacements.put("%read.fastq%", fastqFilename); replacements.put("%tmp1%", tmp1.getName()); replacements.put("%output%", outputFilename); final String transformedCommand = transform(processPartCommand, replacements); final DefaultExecutor executor = new DefaultExecutor(); OutputStream logStream = null; try { logStream = new LoggingOutputStream(getClass(), Level.INFO, ""); executor.setStreamHandler( new PumpStreamHandler(new StreamSignal(done, "scanning", logStream))); final CommandLine parse = CommandLine.parse(transformedCommand, replacements); LOG.info("About to execute: " + parse); final int exitValue = executor.execute(parse); LOG.info("Exit value = " + exitValue); if (new File(outputFilename + ".header").exists()) { // found output alignment: System.out.println("found output file: " + outputFilename); allOutputs.add(outputFilename + ".header"); } else { System.out.println("Warning: did not find output alignment: " + outputFilename); } } finally { IOUtils.closeQuietly(logStream); // remove the fastq file new File(fastqFilename).delete(); } } catch (IOException e) { LOG.error("Error processing index " + loopIndex + ", " + inputBasename, e); } } }; String[] parts = new String[numParts]; for (int j = 0; j < numParts; j++) { parts[j] = Integer.toString(j); } try { loop.execute(true, parts); } catch (Exception e) { System.err.println("An error occurred executing a parallel command: "); e.printStackTrace(); } System.out.printf("Preparing to concatenate %d outputs..%n", allOutputs.size()); final ConcatenateAlignmentMode concat = new ConcatenateAlignmentMode(); concat.setInputFileNames(allOutputs.toArray(new String[allOutputs.size()])); concat.setOutputFilename(output); concat.setAdjustQueryIndices(false); concat.setAdjustSampleIndices(false); concat.execute(); }
From source file:gov.nih.nci.caarray.plugins.agilent.AgilentXmlDesignFileHandler.java
/** * {@inheritDoc}// w ww . jav a 2 s.c o m */ @Override public void load(ArrayDesign arrayDesign) throws PlatformFileReadException { try { arrayDesign.setName(FilenameUtils.getBaseName(this.designFile.getName())); arrayDesign.setLsidForEntity( String.format("%s:%s:%s", LSID_AUTHORITY, LSID_NAMESPACE, arrayDesign.getName())); getArrayDao().save(arrayDesign); } catch (final Exception e) { throw new PlatformFileReadException(this.fileOnDisk, "Unexpected error while loading " + this.designFile.getName(), e); } }
From source file:de.mpg.imeji.logic.storage.util.MediaUtils.java
/** * Remove the files created by imagemagick. * // w ww . j a va 2 s . co m * @param path */ private static void removeFilesCreatedByImageMagick(String path) { int count = 0; String dir = FilenameUtils.getFullPath(path); String pathBase = FilenameUtils.getBaseName(path); File f = new File(dir + pathBase + "-" + count + ".jpg"); while (f.exists()) { String newPath = f.getAbsolutePath().replace("-" + count, "-" + Integer.valueOf(count + 1)); f.delete(); f = new File(newPath); count++; } }
From source file:dialog.DialogFunctionUser.java
private void actionEditUserNoController() { if (!isValidData()) { return;// ww w. j av a 2 s . c om } tfUsername.setEditable(false); String username = tfUsername.getText(); String fullname = tfFullname.getText(); String password = mUser.getPassword(); if (tfPassword.getPassword().length == 0) { password = new String(tfPassword.getPassword()); password = LibraryString.md5(password); } int role = cbRole.getSelectedIndex(); User objUser; if (mAvatar != null) { objUser = new User(mUser.getIdUser(), username, password, fullname, role, new Date(System.currentTimeMillis()), mAvatar.getPath()); if ((new ModelUser()).editItem(objUser)) { String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "." + FilenameUtils.getExtension(mAvatar.getName()); Path source = Paths.get(mAvatar.toURI()); Path destination = Paths.get("files/" + fileName); Path pathOldAvatar = Paths.get(mUser.getAvatar()); try { Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); Files.deleteIfExists(pathOldAvatar); } catch (IOException ex) { Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex); } ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png")); JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success", JOptionPane.INFORMATION_MESSAGE, icon); } else { JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail", JOptionPane.ERROR_MESSAGE); } } else { objUser = new User(mUser.getIdUser(), username, password, fullname, role, new Date(System.currentTimeMillis()), mUser.getAvatar()); if (mControllerUser.editItem(objUser, mRow)) { ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png")); JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success", JOptionPane.INFORMATION_MESSAGE, icon); } else { JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail", JOptionPane.ERROR_MESSAGE); } } mUser = objUser; this.dispose(); }
From source file:com.consol.citrus.admin.service.TestCaseService.java
/** * Finds all tests case declarations in given source files. Method is loading tests by their annotation presence of @CitrusTest or @CitrusXmlTest. * @param project/* w ww. j a v a 2 s . c om*/ * @param sourceFiles */ private List<Test> findTests(Project project, List<File> sourceFiles) { List<Test> tests = new ArrayList<>(); for (File sourceFile : sourceFiles) { String className = FilenameUtils.getBaseName(sourceFile.getName()); String testPackageName = sourceFile.getPath() .substring(project.getJavaDirectory().length(), sourceFile.getPath().length() - sourceFile.getName().length()) .replace(File.separatorChar, '.'); if (testPackageName.endsWith(".")) { testPackageName = testPackageName.substring(0, testPackageName.length() - 1); } tests.addAll(findTests(sourceFile, testPackageName, className)); } return tests; }
From source file:it.geosolutions.geobatch.actions.ds2ds.Ds2dsAction.java
/** * Imports data from the source DataStore to the output one * transforming the data as configured.//from w w w . j ava 2 s. co m */ @Override public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { // return object final Queue<EventObject> outputEvents = new LinkedList<EventObject>(); while (events.size() > 0) { final EventObject ev; try { if ((ev = events.remove()) != null) { listenerForwarder.started(); updateTask("Working on incoming event: " + ev.getSource()); Queue<FileSystemEvent> acceptableFiles = acceptableFiles(unpackCompressedFiles(ev)); if (ev instanceof FileSystemEvent && ((FileSystemEvent) ev).getEventType().equals(FileSystemEventType.POLLING_EVENT)) { String fileType = getFileType((FileSystemEvent) ev); EventObject output = null; if ("feature".equalsIgnoreCase(fileType)) { configuration.getOutputFeature().setTypeName( FilenameUtils.getBaseName(((FileSystemEvent) ev).getSource().getName())); output = buildOutputEvent(); updateImportProgress(1, 1, "Completed"); } else { output = importFile((FileSystemEvent) ev); } outputEvents.add(output); } else { if (acceptableFiles.size() == 0) { failAction("No file to process"); } else { List<ActionException> exceptions = new ArrayList<ActionException>(); for (FileSystemEvent fileEvent : acceptableFiles) { try { String fileType = getFileType(fileEvent); EventObject output = null; if ("feature".equalsIgnoreCase(fileType)) { configuration.getOutputFeature().setTypeName(FilenameUtils .getBaseName(((FileSystemEvent) ev).getSource().getName())); output = buildOutputEvent(); updateImportProgress(1, 1, "Completed"); } else { output = importFile(fileEvent); } if (output != null) { // add the event to the return outputEvents.add(output); } else { if (LOGGER.isWarnEnabled()) { LOGGER.warn("No output produced"); } } } catch (ActionException e) { exceptions.add(e); } } if (acceptableFiles.size() == exceptions.size()) { throw new ActionException(this, exceptions.get(0).getMessage()); } else if (exceptions.size() > 0) { if (LOGGER.isWarnEnabled()) { for (ActionException ex : exceptions) { LOGGER.warn("Error in action: " + ex.getMessage()); } } } } } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Encountered a NULL event: SKIPPING..."); } continue; } } catch (ActionException ioe) { failAction("Unable to produce the output, " + ioe.getLocalizedMessage(), ioe); } catch (Exception ioe) { failAction("Unable to produce the output: " + ioe.getLocalizedMessage(), ioe); } } return outputEvents; }
From source file:com.vectorcast.plugins.vectorcastexecution.job.BaseJob.java
/** * Constructor//from w w w .ja v a 2 s. co m * @param request request object * @param response response object * @param useSavedData use saved data true/false * @throws ServletException exception * @throws IOException exception */ protected BaseJob(final StaplerRequest request, final StaplerResponse response, boolean useSavedData) throws ServletException, IOException { instance = Jenkins.getInstance(); this.request = request; this.response = response; JSONObject json = request.getSubmittedForm(); manageProjectName = json.optString("manageProjectName"); if (!manageProjectName.isEmpty()) { // Force unix style path to avoid problems later manageProjectName = manageProjectName.replace('\\', '/'); } baseName = FilenameUtils.getBaseName(manageProjectName); this.useSavedData = useSavedData; if (useSavedData) { // Data will be set later } else { this.usingSCM = false; environmentSetupWin = json.optString("environmentSetupWin"); executePreambleWin = json.optString("executePreambleWin"); environmentTeardownWin = json.optString("environmentTeardownWin"); environmentSetupUnix = json.optString("environmentSetupUnix"); executePreambleUnix = json.optString("executePreambleUnix"); environmentTeardownUnix = json.optString("environmentTeardownUnix"); optionUseReporting = json.optBoolean("optionUseReporting", true); optionErrorLevel = json.optString("optionErrorLevel", "Unstable"); optionHtmlBuildDesc = json.optString("optionHtmlBuildDesc", "HTML"); optionExecutionReport = json.optBoolean("optionExecutionReport", true); optionClean = json.optBoolean("optionClean", false); waitTime = json.optLong("waitTime", 5); waitLoops = json.optLong("waitLoops", 2); jobName = json.optString("jobName", null); nodeLabel = json.optString("nodeLabel", ""); } }
From source file:com.frostwire.transfers.YouTubeDownload.java
private static File buildTempFile(FileSystem fs, String filename, String ext) { String name = FilenameUtils.getBaseName(filename); return buildFile(fs, Platforms.temp(), name + "." + ext); }