List of usage examples for org.apache.commons.io FilenameUtils getBaseName
public static String getBaseName(String filename)
From source file:it.geosolutions.tools.compress.file.Compressor.java
/** * @param outputDir/*ww w.j a v a2s .c om*/ * The directory where the zipfile will be created * @param zipFileBaseName * The basename of hte zip file (i.e.: a .zip will be appended) * @param folder * The folder that will be compressed * @return The created zipfile, or null if an error occurred. * @deprecated TODO UNTESTED */ public static File deflate(final File outputDir, final String zipFileBaseName, final File folder) { // Create a buffer for reading the files byte[] buf = new byte[4096]; // Create the ZIP file final File outZipFile = new File(outputDir, zipFileBaseName + ".zip"); if (outZipFile.exists()) { if (LOGGER.isInfoEnabled()) LOGGER.info("The output file already exists: " + outZipFile); return outZipFile; } ZipOutputStream out = null; BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(outZipFile); bos = new BufferedOutputStream(fos); out = new ZipOutputStream(bos); Collector c = new Collector(null); List<File> files = c.collect(folder); // Compress the files for (File file : files) { FileInputStream in = null; try { in = new FileInputStream(file); if (file.isDirectory()) { out.putNextEntry(new ZipEntry(Path.toRelativeFile(folder, file).getPath())); } else { // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(FilenameUtils.getBaseName(file.getName()))); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } } finally { try { // Complete the entry out.closeEntry(); } catch (IOException e) { } IOUtils.closeQuietly(in); } } } catch (IOException e) { LOGGER.error(e.getLocalizedMessage(), e); return null; } finally { // Complete the ZIP file IOUtils.closeQuietly(bos); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(out); } return outZipFile; }
From source file:com.frochr123.helper.CachedFileDownloader.java
public synchronized static SimpleEntry<String, SimpleEntry<String, File>> downloadFile(String url, String commaSeperatedAllowedFileTypes) throws IOException { // On invalid URL return null if (url == null || url.isEmpty()) { return null; }/* w ww. jav a 2 s . c o m*/ // Prepare check file extensions String allowedFileTypesString = commaSeperatedAllowedFileTypes; // Fallback to default allowed file types if (allowedFileTypesString == null || allowedFileTypesString.isEmpty()) { allowedFileTypesString = CACHE_DOWNLOADER_DEFAULT_FILETYPES; } // Get seperate file types from string and normalize to lowercase String[] allowedFileTypesArray = allowedFileTypesString.split(","); if (allowedFileTypesArray.length > 0) { // Normalize file extensions to lower case for (int i = 0; i < allowedFileTypesArray.length; ++i) { if (allowedFileTypesArray[i] != null && !allowedFileTypesArray[i].isEmpty()) { allowedFileTypesArray[i] = allowedFileTypesArray[i].toLowerCase(); } } } File file = null; String finalUrl = null; String fileExtension = null; String fileBaseName = null; SimpleEntry<String, File> innerResult = null; SimpleEntry<String, SimpleEntry<String, File>> finalResult = null; // Check if URL is already stored in cache map if (cacheMap.containsKey(url)) { if (cacheMap.get(url) != null) { innerResult = cacheMap.get(url); file = (File) (cacheMap.get(url).getValue()); } } // URL is not stored in cache, download and store it in cache else { // Resize cache if needed, LinkedHashMap keeps insertion order, oldest entries are first entries // Temporary store keys in list and remove afterwards to avoid read / write issues // Get one free space for new download LinkedList<String> deleteKeys = new LinkedList<String>(); for (Entry<String, SimpleEntry<String, File>> cacheEntry : cacheMap.entrySet()) { if ((cacheMap.size() - deleteKeys.size()) >= CACHE_DOWNLOADER_MAX_ENTRIES) { deleteKeys.add(cacheEntry.getKey()); } else { break; } } // Remove keys if (!deleteKeys.isEmpty()) { for (String key : deleteKeys) { // Delete old files if (cacheMap.get(key) != null && cacheMap.get(key).getValue() != null) { cacheMap.get(key).getValue().delete(); } // Remove entry in cache map cacheMap.remove(key); } } // Download file SimpleEntry<String, ByteArrayOutputStream> download = getResultFromURL(url); if (download == null || download.getKey() == null || download.getKey().isEmpty() || download.getValue() == null) { return null; } // Check for file type if (allowedFileTypesArray.length > 0) { finalUrl = download.getKey(); fileExtension = FilenameUtils.getExtension(finalUrl); // Check for valid fileExtension if (fileExtension == null || fileExtension.isEmpty()) { return null; } // Check if fileExtension is contained in allowed file extensions // Normalize file extensions to lower case boolean foundAllowedFileExtension = false; for (int i = 0; i < allowedFileTypesArray.length; ++i) { if (allowedFileTypesArray[i].equals(fileExtension)) { foundAllowedFileExtension = true; break; } } // File extension was not found, abort if (!foundAllowedFileExtension) { return null; } } // Write result to file, it is allowed file type fileBaseName = FilenameUtils.getBaseName(finalUrl); file = FileUtils.getNonexistingWritableFile(fileBaseName + "." + fileExtension); file.deleteOnExit(); FileOutputStream filestream = new FileOutputStream(file); download.getValue().writeTo(filestream); // Insert into cache and result variable innerResult = new SimpleEntry<String, File>(finalUrl, file); cacheMap.put(url, innerResult); } if (innerResult != null) { finalResult = new SimpleEntry<String, SimpleEntry<String, File>>(url, innerResult); } return finalResult; }
From source file:edu.scripps.fl.pubchem.xmltool.gui.PubChemXMLExtractorGUI.java
private File extract(URL template) throws Exception { String xml = jtfFileXML.getText(); InputStream is = null;/*from w w w.j a v a 2s. c o m*/ if (FilenameUtils.getExtension(xml).equals("xml")) { is = new FileInputStream(new File(xml)); xml = FilenameUtils.getBaseName(xml); } else if (FilenameUtils.getExtension(xml).equals("gz")) { is = new GZIPInputStream(new FileInputStream(new File(xml))); xml = FilenameUtils.getBaseName(xml); } else { Integer aid = Integer.parseInt(xml); is = PubChemFactory.getInstance().getPubChemXmlDesc(aid); if (is == null) is = pcDep.getPubChemAID(aid); } File fileExcelOutput = new XMLExtractorController().extractPubChemXML(template, is); return fileExcelOutput; }
From source file:com.groupdocs.viewer.samples.spring.model.Utilities.java
/** * Make image path file.//from w w w. j ava 2 s. co m * @param path the path * @param imageName the image name * @return the file */ public static File makeImagePath(String path, String imageName) { final File directory = new File(path + "\\images\\"); if (!directory.exists() && !directory.mkdirs()) { System.out.println("Can't create directory for images! " + directory.getAbsolutePath()); } return new File( directory.getAbsolutePath() + File.separator + FilenameUtils.getBaseName(imageName) + ".png"); }
From source file:com.epam.catgenome.manager.wig.WigManager.java
/** * Saves a {@code WigFile} on the server. File metadata is saved in the database * @param request/*from ww w .j ava2 s .co m*/ * @return */ public WigFile registerWigFile(final FileRegistrationRequest request) { Assert.notNull(request, MessagesConstants.ERROR_NULL_PARAM); final String requestPath = request.getPath(); Assert.notNull(requestPath, getMessage(MessagesConstants.WRONG_WIG_FILE)); Assert.notNull(request.getReferenceId(), getMessage(MessageCode.NO_SUCH_REFERENCE)); WigFile wigFile = null; try { Assert.isTrue(parseWig(requestPath), getMessage(MessagesConstants.WRONG_WIG_FILE)); if (request.getType() == null) { request.setType(BiologicalDataItemResourceType.FILE); } switch (request.getType()) { case FILE: wigFile = fillWigFile(requestPath, request.getName(), request.getPrettyName(), request.getReferenceId()); break; case DOWNLOAD: final File newFile = downloadFileManager.downloadFromURL(requestPath); request.setName( request.getName() != null ? request.getName() : FilenameUtils.getBaseName(requestPath)); wigFile = fillWigFile(newFile.getPath(), request.getName(), request.getPrettyName(), request.getReferenceId()); break; default: throw new IllegalArgumentException(getMessage(MessagesConstants.ERROR_INVALID_PARAM)); } long id = wigFileManager.createWigFileId(); biologicalDataItemManager.createBiologicalDataItem(wigFile); wigFile.setBioDataItemId(wigFile.getId()); wigFile.setId(id); fileManager.makeWigDir(wigFile.getId(), AuthUtils.getCurrentUserId()); splitWigFile(wigFile); wigFileManager.save(wigFile); } catch (IOException e) { throw new RegistrationException(getMessage(MessagesConstants.ERROR_REGISTER_FILE, request.getName()), e); } finally { if (wigFile != null && wigFile.getId() != null && wigFileManager.loadWigFile(wigFile.getId()) == null) { biologicalDataItemManager.deleteBiologicalDataItem(wigFile.getBioDataItemId()); try { fileManager.deleteFeatureFileDirectory(wigFile); } catch (IOException e) { LOGGER.error("Unable to delete directory for " + wigFile.getName(), e); } } } return wigFile; }
From source file:ch.entwine.weblounge.common.impl.site.I18nDictionaryImpl.java
/** * Adds the the dictionary found in <code>file</code> to the current i18n * definitions. The implementation tries to derive the language from the * filename, which is expected to be of the form * <code><name>_<language>.xml</code>, where <language> is * the ISO language identifier.// w ww . ja v a 2s .co m * * @param url * the i18n dictionary */ public void addDictionary(URL url) { String name = FilenameUtils.getBaseName(url.getFile()); Language language = null; String languageId = null; int lidstart = name.indexOf('_') + 1; if (lidstart > 0 && lidstart < name.length()) { languageId = name.substring(lidstart); language = LanguageUtils.getLanguage(languageId); } addDictionary(url, language); }
From source file:edu.ku.brc.specify.utilapps.morphbank.BaseFileNameParser.java
@Override public boolean isNameValid(final String fileName, boolean getBaseName) { UIFieldFormatterIFace fmtr = fldInfo.getFormatter(); String fieldNameValue = fileName; if (fmtr != null) { fieldNameValue = getTrimmedFileName(getBaseName ? FilenameUtils.getBaseName(fileName) : fileName); if (!fmtr.isValid(fieldNameValue)) { fieldNameValue = null;//w ww. j a v a 2 s . c om return false; } return true; } if (fieldNameValue.length() > fldInfo.getLength()) { fieldNameValue = fieldNameValue.substring(0, fldInfo.getLength()); } return true; }
From source file:net.certiv.antlr.project.regen.ReGen.java
private int evaluateUnit(Map<String, Unit> units, File rootDir, File file) { Unit unit = new Unit(); unit.modelFilename = file.getName(); unit.modelRoot = ""; unit.modelPackage = ""; if (rootDir != null) { unit.modelRoot = rootDir.getName(); unit.modelPackage = config.packageOf(file.getParent(), rootDir.getPath()); }//from w w w. j av a 2 s . c o m if (config.isExcludedPackage(unit.modelPackage)) { Log.debug(this, "Excluded package file: " + unit.modelFilename); return 0; } config.basePackage(unit.modelPackage); config.findGrammarName(unit.modelFilename); unit.unitName = FilenameUtils.getBaseName(unit.modelFilename); if (unit.unitName.length() == 0) { unit.unitName = FilenameUtils.getExtension(unit.modelFilename); unit.unitName = Strings.initialUC(unit.unitName); } if (units.containsKey(unit.unitName)) { Unit eUnit = units.get(unit.unitName); if (eUnit.modelFilename.equals(unit.modelFilename) && eUnit.modelPackage.equals(unit.modelPackage) && eUnit.modelRoot.equals(unit.modelRoot)) { // mark as existing physical file eUnit.primary = true; return 1; } unit.unitName += "1"; } unit.primary = true; unit.license = null; unit.unitType = TypeOf.util; unit.templateVars = new ArrayList<String>(); unit.parts = new ArrayList<String>(); unit.templateGroup = "Unknown"; Log.info(this, "Adding: " + Strings.concat(unit.modelRoot, unit.modelPackage, unit.modelFilename)); units.put(unit.unitName, unit); return 1; }
From source file:com.epam.catgenome.manager.DownloadFileManager.java
private String createPathFromUrlString(final String urlString) { final String hash = Utils.getHashFromUrlString(urlString); final String dir = downloadDirPath + Utils.getPathFromHash(hash); makeDir(dir);//w ww . j av a2 s . c o m return dir + DELIMITER + FilenameUtils.getBaseName(urlString) + hash + FilenameUtils.getExtension(urlString); }