List of usage examples for org.apache.commons.io FilenameUtils getExtension
public static String getExtension(String filename)
From source file:dialog.DialogFunctionUser.java
private void actionAddUserNoController() { if (!isValidData()) { return;/* www .j a v a 2s .c o m*/ } if (isExistUsername(tfUsername.getText())) { JOptionPane.showMessageDialog(null, "Username tn ti", "Error", JOptionPane.ERROR_MESSAGE); return; } String username = tfUsername.getText(); String fullname = tfFullname.getText(); String password = new String(tfPassword.getPassword()); password = LibraryString.md5(password); int role = cbRole.getSelectedIndex(); User objUser; if (mAvatar != null) { objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role, new Date(System.currentTimeMillis()), mAvatar.getPath()); String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "." + FilenameUtils.getExtension(mAvatar.getName()); Path source = Paths.get(mAvatar.toURI()); Path destination = Paths.get("files/" + fileName); try { Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex); } } else { objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role, new Date(System.currentTimeMillis()), ""); } if ((new ModelUser()).addItem(objUser)) { ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png")); JOptionPane.showMessageDialog(this.getParent(), "Thm thnh cng", "Success", JOptionPane.INFORMATION_MESSAGE, icon); } else { JOptionPane.showMessageDialog(this.getParent(), "Thm tht bi", "Fail", JOptionPane.ERROR_MESSAGE); } this.dispose(); }
From source file:com.liferay.maven.arquillian.importer.LiferayPluginTestCase.java
protected static void setupPortalMinimal() { System.setProperty("liferay.version", LIFERAY_VERSION); System.setProperty("liferay.auto.deploy.dir", PORTAL_AUTO_DEPLOY_DIR); System.setProperty("liferay.app.server.deploy.dir", PORTAL_SERVER_DEPLOY_DIR); System.setProperty("liferay.app.server.lib.global.dir", PORTAL_SERVER_LIB_GLOBAL_DIR); System.setProperty("liferay.app.server.portal.dir", SERVER_PORTAL_DIR); try {/* w ww.j a va 2 s . c o m*/ ArchiverManager archiverManager = plexusContainer.lookup(ArchiverManager.class); assertNotNull(archiverManager); FileUtils.forceMkdir(new File(PORTAL_AUTO_DEPLOY_DIR)); FileUtils.forceMkdir(new File(PORTAL_SERVER_DEPLOY_DIR)); FileUtils.forceMkdir(new File(PORTAL_SERVER_LIB_GLOBAL_DIR)); FileUtils.forceMkdir(new File(SERVER_PORTAL_DIR)); final MavenResolverSystem mavenResolverSystem = Maven.configureResolver() .fromClassloaderResource("settings.xml"); File[] dependencies = mavenResolverSystem.loadPomFromClassLoaderResource("liferay-setup.xml") .importRuntimeAndTestDependencies().resolve().withoutTransitivity().asFile(); File warFile = null; for (File file : dependencies) { String fileName = file.getName(); String fileExtension = FilenameUtils.getExtension(fileName); if ("jar".equalsIgnoreCase(fileExtension)) { FileUtils.copyFile(file, new File(PORTAL_SERVER_LIB_GLOBAL_DIR, file.getName())); } else if ("war".equalsIgnoreCase(fileExtension) && fileName.contains("portal-web")) { warFile = file; } } assertNotNull(warFile); // extract portal war UnArchiver unArchiver = archiverManager.getUnArchiver(warFile); unArchiver.setDestDirectory(new File(SERVER_PORTAL_DIR)); unArchiver.setSourceFile(warFile); unArchiver.setOverwrite(false); unArchiver.extract(); setup = true; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.arcbees.bourseje.server.upload.CloudStorageUploadService.java
private void verifyFileExtension(String name) { String extension = FilenameUtils.getExtension(name); if (!containsExtension(extension)) { throw new RuntimeException("The provided file in not an image"); }//from w w w .java2s .c o m }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractServiceProviderLogoController.java
private void logoResponse(String imagePath, String defaultImagePath, HttpServletResponse response) { FileInputStream fileinputstream = null; String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath); if (rootImageDir != null && !rootImageDir.trim().equals("")) { try {/*from www . ja v a2s . c om*/ if (imagePath != null && !imagePath.trim().equals("")) { String absoluteImagePath = FilenameUtils.concat(rootImageDir, imagePath); fileinputstream = new FileInputStream(absoluteImagePath); if (fileinputstream != null) { int numberBytes = fileinputstream.available(); byte bytearray[] = new byte[numberBytes]; fileinputstream.read(bytearray); response.setContentType("image/" + FilenameUtils.getExtension(imagePath)); // TODO:Set Cache headers for browser to force browser to cache to reduce load OutputStream outputStream = response.getOutputStream(); response.setContentLength(numberBytes); outputStream.write(bytearray); outputStream.flush(); outputStream.close(); fileinputstream.close(); return; } } } catch (FileNotFoundException e) { logger.debug("###File not found in retrieving logo"); } catch (IOException e) { logger.debug("###IO Error in retrieving logo"); } } response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", defaultImagePath); }
From source file:com.cedarsoft.file.FileNameTest.java
License:asdf
@Test public void testFileNameUtils() { assertEquals("", FilenameUtils.getExtension("asdf")); assertEquals("", FilenameUtils.getExtension("asdf.")); assertEquals("asdf", FilenameUtils.getBaseName("asdf.")); }
From source file:ch.cyberduck.core.transfer.normalizer.DownloadRootPathsNormalizer.java
@Override public List<TransferItem> normalize(final List<TransferItem> roots) { final List<TransferItem> normalized = new ArrayList<TransferItem>(); for (final TransferItem download : roots) { boolean duplicate = false; for (Iterator<TransferItem> iter = normalized.iterator(); iter.hasNext();) { TransferItem n = iter.next(); if (download.remote.isChild(n.remote)) { // The selected file is a child of a directory already included duplicate = true;/* w w w .j ava 2s . co m*/ break; } if (n.remote.isChild(download.remote)) { iter.remove(); } if (download.local.equals(n.local)) { // The selected file has the same name; if downloaded as a root element // it would overwrite the earlier final String parent = download.local.getParent().getAbsolute(); final String filename = download.remote.getName(); String proposal; int no = 0; Local local; do { proposal = String.format("%s-%d", FilenameUtils.getBaseName(filename), ++no); if (StringUtils.isNotBlank(FilenameUtils.getExtension(filename))) { proposal += String.format(".%s", FilenameUtils.getExtension(filename)); } local = LocalFactory.get(parent, proposal); } while (local.exists()); if (log.isInfoEnabled()) { log.info(String.format("Changed local name from %s to %s", filename, local.getName())); } download.local = local; } } // Prunes the list of selected files. Files which are a child of an already included directory // are removed from the returned list. if (!duplicate) { normalized.add(new TransferItem(download.remote, download.local)); } } return normalized; }
From source file:FeatureExtraction.FeatureExtractorOOXMLStructuralPathsDisk.java
/** * Extracts structural paths from the given folder * * @param folderPath path of a folder/*from w w w .ja va 2s . c om*/ * @param structuralPaths the Map to add the extracted features to */ private void ExtractFolderStructuralPaths(String folderPath, Map<String, Integer> structuralPaths) { ArrayList<String> directoryPaths = Directories.GetDirectoryFilesPaths(folderPath); String fileExtension; for (String path : directoryPaths) { if (!path.equals(folderPath)) { AddStructuralPath(path, structuralPaths); if (Files.isRegularFile(Paths.get(path))) { fileExtension = FilenameUtils.getExtension(path); if (fileExtension.equals("rels") || fileExtension.equals("xml")) { AddXMLStructuralPaths(path, structuralPaths); } } } } }
From source file:com.github.dozermapper.core.config.resolvers.YAMLSettingsResolver.java
private Map<String, Map> processFile() { Map<String, Map> answer = new HashMap<>(); String extension = FilenameUtils.getExtension(configFile); if (!(extension.equalsIgnoreCase("yaml") || extension.equalsIgnoreCase("yml"))) { LOG.info("Ignoring, as file extension is not correct for: {}", configFile); } else {//from w w w.ja v a2 s .co m LOG.info("Trying to find Dozer configuration file: {}", configFile); URL url = classLoader.loadResource(configFile); if (url == null) { LOG.info("Failed to find {} via {}.", configFile, getClass().getName()); } else { LOG.info("Using URL [{}] for Dozer settings", url); try (InputStream inputStream = url.openStream()) { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); answer = (Map<String, Map>) mapper.readValue(inputStream, Map.class); } catch (IOException ex) { LOG.error("Failed to load: {} because: {}", configFile, ex.getMessage()); LOG.debug("Exception: ", ex); } } } return answer; }
From source file:de.uzk.hki.da.format.PublishCLIConversionStrategy.java
@Override public List<Event> convertFile(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 = "dip/" + audience_lc; Path.make(object.getDataPath(), repName, ci.getTarget_folder()).toFile().mkdirs(); String[] commandAsArray = assemble(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(ci.getSource_file().toRegularFile().getAbsolutePath()); DAFile result = new DAFile(pkg, repName, ci.getTarget_folder() + "/" + FilenameUtils.removeExtension(Matcher.quoteReplacement( FilenameUtils.getName(ci.getSource_file().toRegularFile().getAbsolutePath()))) + "." + targetSuffix); Event e = new Event(); e.setType("CONVERT"); e.setDetail(Utilities.createString(commandAsArray)); e.setSource_file(ci.getSource_file()); e.setTarget_file(result);/*from www . j av a 2 s. co m*/ e.setDate(new Date()); results.add(e); } return results; }
From source file:controladores.prueba.java
public void save() { try {/*from w w w. ja v a2s.c o m*/ for (UploadedFile f : files) { // DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date dateobj = new Date(); // String nombreFecha = ("chiting" + "-" + df.format(dateobj).replaceAll(":", "-")).trim(); // File directorio = new File("d:/Postgrado/inscripciones/requisitos/" + nombreFecha); // if (!directorio.exists()) { // directorio.mkdir(); // } // String filename = f.getFileName(); String extension = FilenameUtils.getExtension(filename); // Path ruta = Paths.get(directorio + filename); // // try (InputStream input = f.getInputstream()) { // Files.copy(input, ruta, StandardCopyOption.REPLACE_EXISTING); // } FacesMessage message = new FacesMessage("Succesful", filename + " is uploaded.-- " + extension); FacesContext.getCurrentInstance().addMessage(null, message); } } catch (Exception ex) { FacesMessage message = new FacesMessage("Error", ex.toString()); FacesContext.getCurrentInstance().addMessage(null, message); } }