List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:com.orange.matosweb.MatosCampaign.java
/** * Upload.// w w w . j av a 2 s .c o m * * @param file the file * @return the file */ private File upload(UploadedFile file) { if (file == null) return null; String name = FilenameUtils.getName(file.getName()); File tempFile = new File(privateFolder, name); try { InputStream is = file.getInputStream(); try { copyTo(is, tempFile); } finally { is.close(); } } catch (IOException e) { tempFile = null; } return tempFile; }
From source file:analyzer.code.FXMLAnalyzerController.java
@FXML private void openProjectMenuItem() throws FileNotFoundException, IOException { source.clear();//from w w w .j a v a 2s . c o m DirectoryChooser chooser = new DirectoryChooser(); chooser.setTitle("C project"); File selectedDirectory = chooser.showDialog(null); if (null != selectedDirectory) { File[] files = selectedDirectory.listFiles(); for (File file : files) { if (FilenameUtils.getExtension(file.getAbsolutePath()).equals("java")) { analyzer = new AnalyzerC(); curLang = C; countOperatorsEnable = true; levelNestEnable = true; middleLenIdentEnable = true; tableMetric.setVisible(true); tableDescript.setVisible(true); labelDesc.setVisible(true); labelMetrics.setVisible(true); button.setVisible(true); Scanner scanner = new Scanner(file); nameFile.add(FilenameUtils.getName(file.getAbsolutePath())); String tmpSource = new String(); while (scanner.hasNext()) { tmpSource += scanner.nextLine() + '\n'; } source.add(tmpSource); } } } }
From source file:com.librelio.activity.BillingActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wait_bar);/* w w w . ja va 2 s . co m*/ setResult(RESULT_CANCELED); if (!isNetworkConnected()) { showAlertDialog(CONNECTION_ALERT); } else { Intent iapIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); iapIntent.setPackage("com.android.vending"); getContext().bindService(iapIntent, mServiceConn, Context.BIND_AUTO_CREATE); if (getIntent().getExtras() != null) { fileName = getIntent().getExtras().getString(FILE_NAME_KEY); title = getIntent().getExtras().getString(TITLE_KEY); subtitle = getIntent().getExtras().getString(SUBTITLE_KEY); // Using Locale.US to avoid different results in different // locales productId = FilenameUtils.getName(fileName).toLowerCase(Locale.US); productId = productId.substring(0, productId.indexOf("_.pdf")); } } }
From source file:com.librelio.products.ui.ProductsBillingActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wait_bar);/* w w w . j ava 2s. c o m*/ setResult(RESULT_CANCELED); if (!isNetworkConnected()) { showAlertDialog(CONNECTION_ALERT); } else { Intent iapIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); iapIntent.setPackage("com.android.vending"); getContext().bindService(iapIntent, mServiceConn, Context.BIND_AUTO_CREATE); if (getIntent().getExtras() != null) { fileName = getIntent().getExtras().getString(FILE_NAME_KEY); title = getIntent().getExtras().getString(TITLE_KEY); subtitle = getIntent().getExtras().getString(SUBTITLE_KEY); // Using Locale.US to avoid different results in different // locales productId = FilenameUtils.getName(fileName).toLowerCase(Locale.US); productId = productId.substring(0, productId.indexOf("_.sqlite")); } } }
From source file:com.ikon.servlet.admin.ReportServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = ""; String userId = request.getRemoteUser(); updateSessionManager(request);// w w w . j a v a 2 s.co m try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Report rp = new Report(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("rp_id")) { rp.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("rp_name")) { rp.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("rp_active")) { rp.setActive(true); } } else { is = item.getInputStream(); rp.setFileName(FilenameUtils.getName(item.getName())); rp.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); rp.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is))); is.close(); } } if (action.equals("create")) { long id = ReportDAO.create(rp); // Activity log UserActivity.log(userId, "ADMIN_REPORT_CREATE", Long.toString(id), null, rp.toString()); list(userId, request, response); } else if (action.equals("edit")) { Report tmp = ReportDAO.findByPk(rp.getId()); tmp.setActive(rp.isActive()); tmp.setFileContent(rp.getFileContent()); tmp.setFileMime(rp.getFileMime()); tmp.setFileName(rp.getFileName()); tmp.setName(rp.getName()); ReportDAO.update(tmp); // Activity log UserActivity.log(userId, "ADMIN_REPORT_EDIT", Long.toString(rp.getId()), null, rp.toString()); list(userId, request, response); } else if (action.equals("delete")) { ReportDAO.delete(rp.getId()); // Activity log UserActivity.log(userId, "ADMIN_REPORT_DELETE", Long.toString(rp.getId()), null, null); list(userId, request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:com.amour.imagecrawler.ImagesManager.java
private void saveFileToDisk(String imageUrl, String destinationFileDir, Images imagedetails, BufferedImage imBuff) throws IOException { String fileName = FilenameUtils.getName(imageUrl); /* Path path = Paths.get(imageUrl); String fileName = path.getFileName().toString();*/ String destinationFile = IO_Utils.pathCombine(destinationFileDir, fileName); imagedetails.setImageondisk(destinationFile.getBytes()); File outputfile = new File(destinationFile); ImageIO.write(imBuff, IO_Utils.getFileExtension(outputfile), outputfile); }
From source file:it.geosolutions.geobatch.ftpserver.server.GeoBatchFtplet.java
protected FtpletResult fireGeoBatchFileAdd(FtpSession session, FtpRequest request) throws FtpException, IOException { String userPath = session.getUser().getHomeDirectory(); String currDirPath = session.getFileSystemView().getWorkingDirectory().getAbsolutePath(); String filename = request.getArgument(); File dirFile = new File(userPath, currDirPath); File targetFile = new File(dirFile, filename); String flowid = FilenameUtils.getName(currDirPath); if (LOGGER.isInfoEnabled()) LOGGER.info("File upload/append finished: - session working dir: ''{}'' - file: ''{}''", new Object[] { currDirPath, filename }); Catalog catalog = CatalogHolder.getCatalog(); // CHECKME FIXME next call won't work: flowid are set as the file name, // not the config id // FileBasedFlowManager fm = catalog.getFlowManager(flowid, // FileBasedFlowManager.class); // CHECKME TODO this has to be made more // general/* ww w . j a va 2 s . c o m*/ FileBasedFlowManager fm = null; StringBuilder availFmSb = new StringBuilder("Available FlowManagers: "); for (FileBasedFlowManager fmloop : catalog.getFlowManagers(FileBasedFlowManager.class)) { availFmSb.append('(').append(fmloop.getId()).append(',').append(fmloop.getName()).append(')'); if (fmloop.getConfiguration().getId().equals(flowid)) { fm = fmloop; } } if (fm != null) { LOGGER.info("Firing FILEADDED event to {}", fm); fm.postEvent(new FileSystemEvent(targetFile, FileSystemEventType.FILE_ADDED)); } else { LOGGER.error("No FlowManager ''{}'' to notify about {} -- {}", new Object[] { flowid, targetFile, availFmSb }); } return FtpletResult.DEFAULT; }
From source file:edu.umn.msi.tropix.webgui.server.UploadController.java
@ServiceMethod(secure = true) public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception { LOG.debug("In UploadController.handleRequest"); //final String userId = securityProvider.getUserIdForSessionId(request.getParameter("sessionId")); //Preconditions.checkState(userId != null); final String userId = userSession.getGridId(); LOG.debug("Upload by user with id " + userId); String clientId = request.getParameter("clientId"); if (!StringUtils.hasText(clientId)) { clientId = UUID.randomUUID().toString(); }/*from ww w .ja v a 2 s .co m*/ final String endStr = request.getParameter("end"); final String startStr = request.getParameter("start"); final String zipStr = request.getParameter("zip"); final String lastUploadStr = request.getParameter("lastUpload"); final boolean isZip = StringUtils.hasText("zip") ? Boolean.parseBoolean(zipStr) : false; final boolean lastUploads = StringUtils.hasText(lastUploadStr) ? Boolean.parseBoolean(lastUploadStr) : true; LOG.trace("Upload request with startStr " + startStr); final StringWriter rawJsonWriter = new StringWriter(); final JSONWriter jsonWriter = new JSONWriter(rawJsonWriter); final FileItemFactory factory = new DiskFileItemFactory(); final long requestLength = StringUtils.hasText(endStr) ? Long.parseLong(endStr) : request.getContentLength(); long bytesWritten = StringUtils.hasText(startStr) ? Long.parseLong(startStr) : 0L; final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // Deal with international file names final FileItemIterator iter = upload.getItemIterator(request); // Setup message conditionalSampleComponent to track upload progress... final ProgressMessageSupplier supplier = new ProgressMessageSupplier(); supplier.setId(userId + "/" + clientId); supplier.setName("Upload File(s) to Web Application"); final ProgressTrackerImpl progressTracker = new ProgressTrackerImpl(); progressTracker.setUserGridId(userId); progressTracker.setCometPusher(cometPusher); progressTracker.setProgressMessageSupplier(supplier); jsonWriter.object(); jsonWriter.key("result"); jsonWriter.array(); while (iter.hasNext()) { final FileItemStream item = iter.next(); if (item.isFormField()) { continue; } File destination; InputStream inputStream = null; OutputStream outputStream = null; if (!isZip) { final String fileName = FilenameUtils.getName(item.getName()); // new File(item.getName()).getName(); LOG.debug("Handling upload of file with name " + fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(fileName); recordJsonInfo(jsonWriter, info); destination = info.getTempLocation(); } else { destination = FILE_UTILS.createTempFile(); } try { inputStream = item.openStream(); outputStream = FILE_UTILS.getFileOutputStream(destination); bytesWritten += progressTrackingIoUtils.copy(inputStream, outputStream, bytesWritten, requestLength, progressTracker); if (isZip) { ZipUtilsFactory.getInstance().unzip(destination, new Function<String, File>() { public File apply(final String fileName) { final String cleanedUpFileName = FilenameUtils.getName(fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(cleanedUpFileName); recordJsonInfo(jsonWriter, info); return info.getTempLocation(); } }); } } finally { IO_UTILS.closeQuietly(inputStream); IO_UTILS.closeQuietly(outputStream); if (isZip) { FILE_UTILS.deleteQuietly(destination); } } } if (lastUploads) { progressTracker.complete(); } jsonWriter.endArray(); jsonWriter.endObject(); // response.setStatus(200); final String json = rawJsonWriter.getBuffer().toString(); LOG.debug("Upload json response " + json); response.setContentType("text/html"); // GWT was attaching <pre> tag to result without this response.getOutputStream().println(json); return null; }
From source file:com.frostwire.android.gui.fragments.ImageViewerFragment.java
public void updateData(final FileDescriptor fd, int position) { this.fd = fd; this.position = position; async(this, ImageViewerFragment::loadSurroundingFileDescriptors); if (actionModeCallback == null) { actionModeCallback = new ImageViewerActionModeCallback(this.fd, position); startActionMode(actionModeCallback); }/* w ww. j a v a2s . c o m*/ actionModeCallback.getActionMode().setTitle(FilenameUtils.getName(fd.filePath)); fileUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, fd.id); progressBar.setVisibility(View.VISIBLE); highResLoaded = false; // under the assumption that the main image view to render the // picture will cover the main screen, or even go to full screen, // then using the display size as a target is a good idea Point size = displaySize(); // load high res version ImageLoader.Params params = new ImageLoader.Params(); params.targetWidth = size.x; params.targetHeight = size.y; params.placeholderResId = R.drawable.picture_placeholder; params.centerInside = true; params.noCache = true; params.callback = new LoadImageCallback(this); imageLoader.load(fileUri, imageViewHighRes, params); }
From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4jZippedInstaller.java
@Override public void performInstall(IProgressMonitor monitor, IPath dirPath) throws IOException { if (monitor == null) { monitor = new NullProgressMonitor(); }/* w ww. j a v a2 s .com*/ InputStream urlStream = null; try { URL url = getUrl(); URLConnection connection = url.openConnection(); connection.setConnectTimeout(TIMEOUT); connection.setReadTimeout(TIMEOUT); int length = connection.getContentLength(); monitor.beginTask(NLS.bind("Reading from {1}", getVersion(), getUrl().toString()), length >= 0 ? length : IProgressMonitor.UNKNOWN); urlStream = connection.getInputStream(); ZipInputStream zipStream = new ZipInputStream(urlStream); byte[] buffer = new byte[1024 * 8]; long start = System.currentTimeMillis(); int total = length; int totalRead = 0; ZipEntry entry; float kBps = -1; while ((entry = zipStream.getNextEntry()) != null) { if (monitor.isCanceled()) break; String fullFilename = entry.getName(); IPath fullFilenamePath = new Path(fullFilename); int secsRemaining = (int) ((total - totalRead) / 1024 / kBps); String textRemaining = secsToText(secsRemaining); monitor.subTask(NLS.bind("{0} remaining. Reading {1}", textRemaining.length() > 0 ? textRemaining : "unknown time", StringUtils .abbreviateMiddle(fullFilenamePath.removeFirstSegments(1).toString(), "...", 45))); int entrySize = (int) entry.getCompressedSize(); OutputStream output = null; try { int len = 0; int read = 0; String action = null; if (jarFiles.contains(fullFilename)) { action = "Copying"; String filename = FilenameUtils.getName(fullFilename); output = new FileOutputStream(dirPath.append(filename).toOSString()); } else { action = "Skipping"; output = new NullOutputStream(); } int secs = (int) ((System.currentTimeMillis() - start) / 1000); kBps = (float) totalRead / 1024 / secs; while ((len = zipStream.read(buffer)) > 0) { if (monitor.isCanceled()) break; read += len; monitor.subTask(NLS.bind("{0} remaining. {1} {2} at {3}KB/s ({4}KB / {5}KB)", new Object[] { String.format("%s", textRemaining.length() > 0 ? textRemaining : "unknown time"), action, StringUtils.abbreviateMiddle( fullFilenamePath.removeFirstSegments(1).toString(), "...", 45), String.format("%,.1f", kBps), String.format("%,.1f", (float) read / 1024), String.format("%,.1f", (float) entry.getSize() / 1024) })); output.write(buffer, 0, len); } totalRead += entrySize; monitor.worked(entrySize); } finally { IOUtils.closeQuietly(output); } } } finally { IOUtils.closeQuietly(urlStream); monitor.done(); } }