List of usage examples for org.apache.commons.io FilenameUtils getBaseName
public static String getBaseName(String filename)
From source file:aurelienribon.gdxsetupui.Helper.java
public static String getSource(List<String> files, String file) { String path = FilenameUtils.getFullPath(file); String name = FilenameUtils.getBaseName(file); String ext = FilenameUtils.getExtension(file); if (files.contains(path + name + "-source." + ext)) return path + name + "-source." + ext; if (files.contains(path + name + "-sources." + ext)) return path + name + "-sources." + ext; if (files.contains(path + name + "-src." + ext)) return path + name + "-src." + ext; return null;/* www .java 2 s. c om*/ }
From source file:au.edu.uws.eresearch.cr8it.TransformationHandler.java
/** * Actual Spring Integration transformation handler. * * @param inputMessage Spring Integration input message * @return New Spring Integration message with updated headers *//*from w w w.j ava2 s . co m*/ @Transformer public Message<String> handleFile(final Message<File> inputMessage) { final File inputFile = inputMessage.getPayload(); final String filename = inputFile.getName(); final String fileExtension = FilenameUtils.getExtension(filename); //populate this with json-ld data final String inputAsString; String finalString = ""; if ("zip".equals(fileExtension)) { inputAsString = getJsonData(inputFile, FilenameUtils.getName(filename)); try { finalString = getJsonMapping(inputAsString); } catch (IOException | ParseException e) { e.printStackTrace(); } if (finalString.length() > 0) { final Message<String> message = MessageBuilder.withPayload(finalString) .setHeader(FileHeaders.FILENAME, FilenameUtils.getBaseName(filename) + ".json") .setHeader(FileHeaders.ORIGINAL_FILE, inputFile) .setHeader("file_size", finalString.length()).setHeader("file_extension", "json").build(); return message; } else { System.out.println("Empty json string."); return null; } } else { System.out.println("Invalid file format"); return null; } }
From source file:de.uzk.hki.da.convert.PublishAudioConversionStrategy.java
@Override public List<Event> convertFile(WorkArea wa, ConversionInstruction ci) throws FileNotFoundException { if (object == null) throw new IllegalStateException("object not set"); if (cliConnector == null) throw new IllegalStateException("cliConnector not set"); Path.makeFile(wa.dataPath(), pips, "public", ci.getTarget_folder()).mkdirs(); Path.makeFile(wa.dataPath(), pips, "institution", ci.getTarget_folder()).mkdirs(); List<Event> results = new ArrayList<Event>(); for (String audience : audiences) { Path source = Path.make(wa.toFile(ci.getSource_file()).getAbsolutePath()); Path target = Path.make(wa.dataPath(), pips, audience.toLowerCase(), ci.getTarget_folder(), FilenameUtils.getBaseName(wa.toFile(ci.getSource_file()).getAbsolutePath()) + ".mp3"); logger.debug("source:" + FilenameUtils.getBaseName(wa.toFile(ci.getSource_file()).getAbsolutePath())); String cmdPUBLIC[] = new String[] { "sox", source.toString(), target.toString() }; logger.debug("source:" + source); logger.debug("target:" + target); ProcessInformation pi = null;/* w w w. j av a2 s .c o m*/ try { pi = cliConnector.runCmdSynchronously( (String[]) ArrayUtils.addAll(cmdPUBLIC, getDurationRestrictionsForAudience(audience))); } catch (IOException e1) { throw new RuntimeException("command not succeeded, not found!"); } if (pi.getExitValue() != 0) throw new RuntimeException("command not succeeded"); DAFile f1 = new DAFile(pips + "/" + audience.toLowerCase(), StringUtilities.slashize(ci.getTarget_folder()) + FilenameUtils.getBaseName(wa.toFile(ci.getSource_file()).getAbsolutePath()) + ".mp3"); Event e = new Event(); e.setType("CONVERT"); e.setSource_file(ci.getSource_file()); e.setTarget_file(f1); e.setDetail(StringUtilities.createString(cmdPUBLIC)); e.setDate(new Date()); results.add(e); } return results; }
From source file:br.univali.celine.lms.core.commands.ImportCourseCommand.java
public String executar(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = (User) request.getSession().getAttribute(UserImpl.USER); userName = user.getName();/* ww w. j a v a2 s . c o m*/ AjaxInterface ajaxInterface = AjaxInterface.getInstance(); ajaxInterface.updateProgress(userName, 0.0); ajaxInterface.updateStatus(userName, 1); MultipartRequestProcessor mrp = MultipartRequestProcessor.getInstance(); mrp.setProgressListener(this); mrp.processRequest(request); String coursesFolder = LMSConfig.getInstance().getCompleteCoursesFolder(); coursesFolder = coursesFolder.replaceAll("file:", ""); String title = mrp.getParameter("title", true); // TODO: esse title nao deveria vir do formulario, mas ser extraido do contentpackage !!! String id = mrp.getParameter("id", true); // TODO: esse id nao deveria vir do formulario, mas ser extraido do contentpackage !!! while (mrp.hasFiles()) { FileItem item = mrp.getNextFile(); String fileFolder = FilenameUtils.getBaseName(item.getName()).replaceAll(".zip", ""); fileFolder = fileFolder.replace('.', '_'); File dir = new File(coursesFolder + fileFolder); while (dir.exists()) { fileFolder = "_" + fileFolder; dir = new File(coursesFolder + fileFolder); } logger.info("mkdirs " + dir.getAbsolutePath()); dir.mkdirs(); logger.info("done mkdirs"); ajaxInterface.updateProgress(userName, 0.0); ajaxInterface.updateStatus(userName, 2); byte[] buffer = new byte[1024]; long totalBytes = 0; int bytesRead = 0; File zipFile = new File(dir + "\\" + FilenameUtils.getName(item.getName())); FileOutputStream fos = new FileOutputStream(zipFile); InputStream is = item.getInputStream(); while ((bytesRead = is.read(buffer, 0, buffer.length)) > 0) { fos.write(buffer, 0, bytesRead); totalBytes = totalBytes + bytesRead; ajaxInterface.updateProgress(userName, (100 * totalBytes) / item.getSize()); } fos.close(); is.close(); ajaxInterface.updateProgress(userName, 0.0); ajaxInterface.updateStatus(userName, 3); Zip zip = new Zip(); zip.setListener(this); zip.unzip(zipFile, dir); zipFile.delete(); ajaxInterface.removeProgress(userName); ajaxInterface.removeStatus(userName); LMSControl control = LMSControl.getInstance(); CourseImpl course = new CourseImpl(id, fileFolder, title, false, false); logger.info("Inserting course"); control.insertCourse(course); } Map<String, Object> mparams = mrp.getParameters(); String params = ""; for (String name : mparams.keySet()) { params += "&" + name + "=" + mparams.get(name); } params = params.substring(1); return HTMLBuilder.buildRedirect(mrp.getParameter("nextURL", true) + "?" + params); }
From source file:com.consol.citrus.admin.service.TestCaseServiceImpl.java
@Override public List<TestCaseData> getTests(Project project) { List<TestCaseData> tests = new ArrayList<TestCaseData>(); List<File> testFiles = FileUtils.getTestFiles(getTestDirectory(project)); for (File file : testFiles) { String testName = FilenameUtils.getBaseName(file.getName()); String testPackageName = file.getPath().substring(getTestDirectory(project).length(), file.getPath().length() - file.getName().length()).replace(File.separatorChar, '.'); if (testPackageName.endsWith(".")) { testPackageName = testPackageName.substring(0, testPackageName.length() - 1); }//from w ww . ja v a2 s . c om TestCaseData testCase = new TestCaseData(); testCase.setType(TestCaseType.XML); testCase.setName(testName); testCase.setPackageName(testPackageName); testCase.setFile(file.getParentFile().getAbsolutePath() + File.separator + FilenameUtils.getBaseName(file.getName())); testCase.setLastModified(file.lastModified()); tests.add(testCase); } try { Resource[] javaSources = new PathMatchingResourcePatternResolver().getResources( "file:" + FilenameUtils.separatorsToUnix(getJavaDirectory(project)) + "**/*.java"); for (Resource resource : javaSources) { File file = resource.getFile(); String testName = FilenameUtils.getBaseName(file.getName()); String testPackage = file.getParentFile().getAbsolutePath() .substring(getJavaDirectory(project).length()).replace(File.separatorChar, '.'); if (knownToClasspath(testPackage, testName)) { tests.addAll(getTestCaseInfoFromClass(testPackage, testName, file)); } else { tests.addAll(getTestCaseInfoFromFile(testPackage, testName, file)); } } } catch (IOException e) { log.warn("Failed to read Java source files - list of test cases for this project is incomplete", e); } return tests; }
From source file:it.baywaylabs.jumpersumo.robot.ServerPolling.java
/** * This method is called when invoke <b>execute()</b>.<br /> * Do not invoke manually. Use: new ServerPolling().execute(url1, url2, url3); * * @param sUrl List of Url that will be download. * @return null if all is going ok./*from w w w .j a v a 2 s. c o m*/ */ @Override protected String doInBackground(String... sUrl) { InputStream input = null; OutputStream output = null; File folder = new File(Constants.DIR_ROBOT); String baseName = FilenameUtils.getBaseName(sUrl[0]); String extension = FilenameUtils.getExtension(sUrl[0]); Log.d(TAG, "FileName: " + baseName + " - FileExt: " + extension); if (!folder.exists()) { folder.mkdir(); } HttpURLConnection connection = null; if (!f.isUrl(sUrl[0])) return "Url malformed!"; try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); // expect HTTP 200 OK, so we don't mistakenly save error report // instead of the file if (!sUrl[0].endsWith(".csv") && connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage(); } // this will be useful to display download percentage // might be -1: server did not report the length int fileLength = connection.getContentLength(); // download the file input = connection.getInputStream(); output = new FileOutputStream(folder.getAbsolutePath() + "/" + baseName + "." + extension); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { // allow canceling with back button if (isCancelled()) { input.close(); return null; } total += count; // publishing the progress.... if (fileLength > 0) // only if total length is known publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } } catch (Exception e) { Log.e(TAG, e.getMessage()); return e.toString(); } finally { try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) { } if (connection != null) connection.disconnect(); } return null; }
From source file:com.beaconhill.yqd.DataDir.java
List<String> getSymbols(String directoryPath) { File dir = new File(directoryPath); String[] children = dir.list(); // It is also possible to filter the list of returned files. // This example does not return any files that start with `.'. FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { String lname = name.toLowerCase(); return lname.endsWith(".csv"); }//from w w w . ja v a 2s . c o m }; children = dir.list(filter); List<String> rtn = new ArrayList<String>(); for (String s : children) { try { rtn.add(FilenameUtils.getBaseName((new File(s).getCanonicalPath()).toUpperCase())); } catch (IOException ioEx) { System.err.println(ioEx.getMessage()); } } return rtn; }
From source file:br.com.pontocontrol.controleponto.controller.impl.ArquivoController.java
@Override public List<Integer> getAvalableYearFolders() { String pathUsuario = SessaoManager.getInstance().getUsuarioAutenticado().getPathUsuario(); File dir = new File(pathUsuario); List<Integer> saida = new ArrayList<Integer>(); if (dir.exists()) { for (String path : dir.list()) { File file = new File(format("%s/%s", pathUsuario, path)); if (file.isDirectory()) { final String nomeDir = FilenameUtils.getBaseName(file.getName()); final String[] dirSplit = nomeDir.split(ARQUIVO_SPLITTER); if (dirSplit.length == 2 && PREFIXO_PASTAS.equalsIgnoreCase(dirSplit[0])) { String anoStr = dirSplit[1]; try { saida.add(Integer.valueOf(anoStr)); } catch (NumberFormatException ex) { LOG.log(Level.SEVERE, format( "Erro ao executar parse da pasta \"%s\", o padro \"%s\" no um ano vlido.", nomeDir, anoStr), ex); }/*from w ww . j a v a 2 s . c o m*/ } } } } return saida; }
From source file:mycontrollers.MyCarController.java
public String submit() { // setCurrent(new Car()); // getFacade().create(getCurrent()); final String fileName = getFile().getName(); InputStream filecontent;/* ww w .ja v a 2 s . c om*/ byte[] bytes = null; try { filecontent = getFile().getInputStream(); int read = 0; // IOUtils.toByteArray(filecontent); // Apache commons IO. getCurrent().setImage(IOUtils.toByteArray(filecontent)); //while ((read = filecontent.read(current.getImage())) != -1) { // } getFacade().edit(getCurrent()); } catch (IOException ex) { Logger.getLogger(MyCarController.class.getName()).log(Level.SEVERE, null, ex); } setFilename(FilenameUtils.getBaseName(getFile().getSubmittedFileName())); setExtension(FilenameUtils.getExtension(getFile().getSubmittedFileName())); return "jsfUpload"; }
From source file:com.cedarsoft.serialization.serializers.jackson.registry.FileBasedObjectsAccess.java
@Nonnull @Override/*from ww w .java 2s . c om*/ public Set<? extends String> getIds() throws IOException { assert baseDir.exists(); File[] files = baseDir.listFiles((FileFilter) new SuffixFileFilter(extension)); if (files == null) { throw new FileNotFoundException("Could not list files in " + baseDir.getAbsolutePath()); } Set<String> ids = new HashSet<String>(); for (File file : files) { ids.add(FilenameUtils.getBaseName(file.getName())); } return ids; }