List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:com.frostwire.android.gui.transfers.DesktopTransfer.java
@Override public String getDisplayName() { if (items.size() == 1) { return FilenameUtils.getName(fd.filePath); } else {/* ww w .j a v a 2 s . c o m*/ return dur.computerName; } }
From source file:com.googlecode.psiprobe.controllers.deploy.UploadWarController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;// ww w. j a v a2 s . com String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // // parse multipart request and extract the file // FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding("UTF8"); try { for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) { FileItem fi = (FileItem) it.next(); if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.fatal("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists()) { tmpWar.delete(); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); // // pass the name of the newly deployed context to the presentation layer // using this name the presentation layer can render a url to view compilation details // String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating " + contextName + ": removing the old copy"); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // // move the .war to tomcat application base dir // String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // // let Tomcat know that the file is there // getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:" + destWar.toURI().toURL().toString() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } tmpWar.delete(); } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:com.atlassian.theplugin.util.CodeNavigationUtil.java
/** * Note: must be run from event dispatch thread or inside read-action only! *///from w w w. j a v a2 s. c om @Nullable public static PsiFile guessCorrespondingPsiFile(final Project project, final String filepath) { final PsiFile[] psifiles = IdeaVersionFacade.getInstance().getFiles(FilenameUtils.getName(filepath), project); return CodeNavigationUtil.guessMatchingFile(filepath, psifiles, project.getBaseDir()); }
From source file:com.github.walterfan.util.http.URLHelper.java
public static void URL2File(String strUrl, String filename) { OutputStream output = null;/*from w ww . j a v a2 s . com*/ try { if (null == filename) { URL url = new URL(strUrl); filename = FilenameUtils.getName(url.getFile()); } System.out.println("write " + filename); File file = new File(filename); output = new FileOutputStream(file); URL2Stream(strUrl, output); } catch (MalformedURLException ex) { System.err.println(ex); } catch (FileNotFoundException ex) { System.err.println("Failed to open stream to URL: " + ex); } catch (IOException ex) { System.err.println("Error reading URL content: " + ex); } finally { IOUtils.closeQuietly(output); } }
From source file:de.uzk.hki.da.convert.PublishCLIConversionStrategy.java
@Override public List<Event> convertFile(WorkArea wa, ConversionInstruction ci ) throws FileNotFoundException { if (pkg == null) throw new IllegalStateException("Package not set"); List<Event> results = new ArrayList<Event>(); for (String audience : audiences) { String audience_lc = audience.toLowerCase(); String repName = WorkArea.TMP_PIPS + "/" + audience_lc; Path.make(wa.dataPath(), repName, ci.getTarget_folder()).toFile().mkdirs(); String[] commandAsArray = assemble(wa, ci, repName); if (!cliConnector.execute(commandAsArray)) throw new RuntimeException("convert did not succeed"); String targetSuffix = ci.getConversion_routine().getTarget_suffix(); if (targetSuffix.equals("*")) targetSuffix = FilenameUtils.getExtension(wa.toFile(ci.getSource_file()).getAbsolutePath()); DAFile result = new DAFile(repName, ci.getTarget_folder() + "/" + FilenameUtils.removeExtension(Matcher.quoteReplacement( FilenameUtils.getName(wa.toFile(ci.getSource_file()).getAbsolutePath()))) + "." + targetSuffix); Event e = new Event(); e.setType("CONVERT"); e.setDetail(StringUtilities.createString(commandAsArray)); e.setSource_file(ci.getSource_file()); e.setTarget_file(result);/*ww w.j a v a 2 s . co m*/ e.setDate(new Date()); results.add(e); } return results; }
From source file:hoot.services.ingest.MultipartSerializer.java
protected void _serializeFGDB(List<FileItem> fileItemsList, String jobId, Map<String, String> uploadedFiles, Map<String, String> uploadedFilesPaths) throws Exception { Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); Map<String, String> folderMap = new HashMap<String, String>(); while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); String fileName = fileItem.getName(); String relPath = FilenameUtils.getPath(fileName); if (relPath.endsWith("/")) { relPath = relPath.substring(0, relPath.length() - 1); }//ww w . j a va2s . c o m fileName = FilenameUtils.getName(fileName); String fgdbFolderPath = homeFolder + "/upload/" + jobId + "/" + relPath; String pathVal = folderMap.get(fgdbFolderPath); if (pathVal == null) { File folderPath = new File(fgdbFolderPath); FileUtils.forceMkdir(folderPath); folderMap.put(fgdbFolderPath, relPath); } if (fileName == null) { ResourceErrorHandler.handleError("A valid file name was not specified.", Status.BAD_REQUEST, log); } String uploadedPath = fgdbFolderPath + "/" + fileName; File file = new File(uploadedPath); fileItem.write(file); } Iterator it = folderMap.entrySet().iterator(); while (it.hasNext()) { String nameOnly = ""; Map.Entry pairs = (Map.Entry) it.next(); String fgdbName = pairs.getValue().toString(); String[] nParts = fgdbName.split("\\."); for (int i = 0; i < nParts.length - 1; i++) { if (nameOnly.length() > 0) { nameOnly += "."; } nameOnly += nParts[i]; } uploadedFiles.put(nameOnly, "GDB"); uploadedFilesPaths.put(nameOnly, fgdbName); } }
From source file:com.dhenton9000.file.FileWatchers.java
/** * generate a runnable that will process a file on a thread * * @param file file to process//from w ww .j a va 2s . co m * @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()); } } }; }
From source file:com.rogiel.httpchannel.service.AbstractHttpDownloader.java
protected InputStreamDownloadChannel download(Request request) throws IOException { final HttpResponse response = request.request(); if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED || response.getStatusLine().getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT)) throw new DownloadLinkNotFoundException(); final String filename = FilenameUtils.getName(request.getURI()); final long contentLength = getContentLength(response); return createInputStreamChannel(response.getEntity().getContent(), contentLength, filename); }
From source file:com.frostwire.gui.library.DownloadTask.java
@Override public void run() { if (!isRunning()) { return;/*from w w w. j a va 2 s .c om*/ } File lastFile = null; try { setProgress(0); if (!savePath.exists()) { savePath.mkdirs(); } long totalBytes = getTotalBytes(); long totalWritten = 0; for (int i = 0; i < fds.length; i++) { if (!isRunning()) { return; } currentFD = fds[i]; GUIMediator.safeInvokeLater(new Runnable() { public void run() { String status = String.format("%s from %s - %s", I18n.tr("Downloading"), device.getName(), currentFD.title); LibraryMediator.instance().getLibrarySearch().pushStatus(status); } }); URL url = new URL(device.getDownloadURL(currentFD)); InputStream is = null; OutputStream fos = null; try { is = url.openStream(); String filename = OSUtils.escapeFilename(FilenameUtils.getName(currentFD.filePath)); File file = buildFile(savePath, filename); Path incompleteFile = buildIncompleteFile(file).toPath(); lastFile = file.getAbsoluteFile(); fos = Files.newOutputStream(incompleteFile, StandardOpenOption.CREATE);// new FileOutputStream(incompleteFile); byte[] buffer = new byte[4 * 1024]; int n = 0; while ((n = is.read(buffer, 0, buffer.length)) != -1) { if (!isRunning()) { return; } fos.write(buffer, 0, n); fos.flush(); totalWritten += n; setProgress((int) ((totalWritten * 100) / totalBytes)); if (getProgress() % 5 == 0) { GUIMediator.safeInvokeLater(new Runnable() { public void run() { String status = String.format("%d%% %s from %s - %s", getProgress(), I18n.tr("Downloading"), device.getName(), currentFD.title); LibraryMediator.instance().getLibrarySearch().pushStatus(status); } }); } //System.out.println("Progress: " + getProgress() + " Total Written: " + totalWritten + " Total Bytes: " + totalBytes); } close(fos); Files.move(incompleteFile, file.toPath(), StandardCopyOption.REPLACE_EXISTING); } finally { close(is); close(fos); } } setProgress(100); } catch (Throwable e) { e.printStackTrace(); onError(e); GUIMediator.safeInvokeLater(new Runnable() { public void run() { LibraryMediator.instance().getLibrarySearch() .pushStatus(I18n.tr("Wi-Fi download error. Please try again.")); } }); } finally { GUIMediator.safeInvokeLater(new Runnable() { public void run() { LibraryMediator.instance().getLibrarySearch().revertStatus(); } }); if (lastFile != null) { GUIMediator.launchExplorer(lastFile); } } stop(); }
From source file:io.github.retz.executor.DummyExecutorDriver.java
private Protos.ExecutorInfo buildExecutorInfo(TemporaryFolder folder, Protos.FrameworkInfo frameworkInfo) { // Copied from Applications.Application URL jarUrl = DummyExecutorDriver.class.getProtectionDomain().getCodeSource().getLocation(); String jarFile = FilenameUtils.getName(jarUrl.toString()); String[] appFilesArray = { "file://foo/bar/baz.tar.gz", "http://example.com:4242/day/of/gluttony.tgz" }; List<String> appFiles = Arrays.asList(appFilesArray); String appName = "dummy-executor-driver-dummy-app"; // Actually this is not used as this is just a test String cmd = "java -cp " + jarFile + " " + MesosExecutorLauncher.getFullClassName(); Protos.CommandInfo.Builder commandInfoBuilder = Protos.CommandInfo.newBuilder() .setEnvironment(Protos.Environment.newBuilder().addVariables( Protos.Environment.Variable.newBuilder().setName("ASAKUSA_HOME").setValue(".").build())) .setValue(cmd).setShell(true) .addUris(Protos.CommandInfo.URI.newBuilder().setValue(jarUrl.toString()).setCache(false)); // In production, set this true for (String file : appFiles) { commandInfoBuilder.addUris(Protos.CommandInfo.URI.newBuilder().setValue(file).setCache(true)); }//www . j av a2 s . c om Protos.ExecutorInfo executorInfo = Protos.ExecutorInfo.newBuilder().setCommand(commandInfoBuilder.build()) .setExecutorId(Protos.ExecutorID.newBuilder().setValue(appName).build()) .setFrameworkId(frameworkInfo.getId()).build(); return executorInfo; }