List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:edu.si.services.beans.edansidora.IdsPushBean.java
public void createAndPush(Exchange exchange) throws EdanIdsException { try {//from w w w .ja va2 s. c o m out = exchange.getIn(); inputLocation = new File(out.getHeader("CamelFileAbsolutePath", String.class)); // get a list of files from current directory if (inputLocation.isFile()) { inputLocation = inputLocation.getParentFile(); LOG.debug("Input File Location: " + inputLocation); } deploymentId = out.getHeader("SiteId", String.class); String assetName = "ExportEmammal_emammal_image_" + deploymentId; String pushDirPath = pushLocation + "/" + assetName + "/"; File assetXmlFile = new File(pushDirPath + assetName + ".xml"); if (!assetXmlFile.getParentFile().exists()) { assetXmlFile.getParentFile().mkdirs(); } else { LOG.warn("IDS files for deployment: {} already exists!!", deploymentId); } LOG.debug("IDS Write Asset Files to: {}", assetXmlFile); LOG.debug("IDS inputLocation = {}", inputLocation); LOG.debug("IDS deploymentId = {}", deploymentId); File files[] = inputLocation.listFiles(); LOG.debug("Input file list: " + Arrays.toString(files)); int completed = 0; StringBuilder assetXml = new StringBuilder(); assetXml.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<Assets>"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(assetXmlFile))) { for (int i = 0; i < files.length; i++) { String fileName = files[i].getName(); LOG.debug("Started file: {} has ext = {}", files[i], FilenameUtils.getExtension(fileName)); // Do not include the manifest file if (!FilenameUtils.getExtension(fileName).contains("xml") && !ignored.containsKey(FilenameUtils.getBaseName(fileName))) { LOG.debug("Adding File {}", fileName); File sourceImageFile = new File(files[i].getPath()); File destImageFile = new File(pushDirPath + "emammal_image_" + fileName); LOG.debug("Copying image asset from {} to {}", sourceImageFile, destImageFile); FileUtils.copyFile(sourceImageFile, destImageFile); assetXml.append("\r\n <Asset Name=\""); assetXml.append(FilenameUtils.getName(destImageFile.getPath())); assetXml.append( "\" IsPublic=\"Yes\" IsInternal=\"No\" MaxSize=\"3000\" InternalMaxSize=\"4000\">"); assetXml.append(FilenameUtils.getBaseName(destImageFile.getPath())); assetXml.append("</Asset>"); } else { LOG.debug("Deployment Manifest XML Found! Skipping {}", files[i]); } } assetXml.append("\r\n</Assets>"); writer.write(assetXml.toString()); LOG.info("Completed: {} of {}, Wrote Asset XML File to: {}", completed++, files.length, assetXmlFile); out.setHeader("idsPushDir", assetXmlFile.getParent()); } catch (Exception e) { throw new EdanIdsException("IdsPushBean error during createAndPush", e); } } catch (Exception e) { throw new EdanIdsException(e); } }
From source file:com.pieframework.runtime.utils.ArtifactManager.java
public static String generateDeployPath(String basePath, boolean unArchive, String query) { String result = null;/*from w w w . ja v a 2 s . c o m*/ //Locate the files in the local artifact cache Configuration.log().debug("artifact location:" + basePath + " query:" + query); List<File> flist = ResourceLoader.findPath(basePath, query); //System.out.println(flist.size() +" "+basePath +" "+query); if (!flist.isEmpty()) { String archivePath = getArchivePath(flist); if (!StringUtils.empty(archivePath)) { //Create a temp location File archiveFile = new File(archivePath); String tmpPath = ResourceLoader.getDeployRoot() + ResourceLoader.getResourceName(query) + File.separatorChar + TimeUtils.getCurrentTimeStamp() + File.separatorChar + FilenameUtils.getName(archiveFile.getParent()); File tmpDir = new File(tmpPath); if (tmpDir.isDirectory() && !tmpDir.exists()) { tmpDir.mkdirs(); } //Unarchive the file try { Zipper.unzip(archivePath, tmpPath); result = tmpPath; } catch (Exception e) { //TODO throw error e.printStackTrace(); } } else { result = getCommonPathRoot(flist); } } else { throw new RuntimeException( "Failed locating path for artifact. searchroot:" + basePath + " query:" + query); } return result; }
From source file:edu.cornell.med.icb.goby.modes.SplitFastaMode.java
/** * Split a fasta / fastq file by (a) readlength and (b) the maximum number of * entries per file. This will output the files that are written to stdout * @throws IOException error reading / writing files. *//*from ww w .j av a 2 s . c om*/ @Override public void execute() throws IOException { final FastXReader reader = new FastXReader(inputFile); final Int2ObjectMap<PrintStream> outputMap = new Int2ObjectOpenHashMap<PrintStream>(); final Int2IntMap entriesPerReadLen = new Int2IntOpenHashMap(); final Int2IntMap filesPerReadLen = new Int2IntOpenHashMap(); final List<String> removeExt = Arrays.asList("gz", "fa", "mpfa", "fna", "fsa", "fas", "fasta", "fq", "mpfq", "fnq", "fsq", "fas", "fastq"); String inputName = FilenameUtils.getName(inputFile); while (true) { // Remove the unwanted extensions from the file name final String ext = FilenameUtils.getExtension(inputName); if (!removeExt.contains(ext)) { break; } inputName = FilenameUtils.getBaseName(inputName); } final String outputFilenameTemplate = FilenameUtils.getFullPath(inputFile) + inputName + "._READLENGTH_._PART_." + reader.getFileType(); final NumberFormat nf3 = NumberFormat.getInstance(); nf3.setMinimumIntegerDigits(3); final NumberFormat nf2 = NumberFormat.getInstance(); nf2.setMinimumIntegerDigits(2); for (final FastXEntry entry : reader) { final int readLen = Math.min(fastxSplitMaxLength, roundReadLen(entry.getReadLength(), splitReadsMod)); PrintStream out = outputMap.get(readLen); if (out == null) { filesPerReadLen.put(readLen, 1); entriesPerReadLen.put(readLen, 0); String outputFilename = outputFilenameTemplate.replaceAll("_READLENGTH_", nf3.format(readLen)); outputFilename = outputFilename.replaceAll("_PART_", nf2.format(1)); System.out.println(outputFilename); out = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFilename))); outputMap.put(readLen, out); } int numEntries = entriesPerReadLen.get(readLen); if (numEntries == maxReadsPerFile) { out.close(); numEntries = 0; int numFiles = filesPerReadLen.get(readLen); numFiles++; filesPerReadLen.put(readLen, numFiles); String outputFilename = outputFilenameTemplate.replaceAll("_READLENGTH_", nf3.format(readLen)); outputFilename = outputFilename.replaceAll("_PART_", nf2.format(numFiles)); System.out.println(outputFilename); out = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFilename))); outputMap.put(readLen, out); } out.println(entry.getEntry()); entriesPerReadLen.put(readLen, numEntries + 1); } for (final PrintStream out : outputMap.values()) { out.close(); } outputMap.clear(); reader.close(); }
From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java
/** * Export the specified institutional collection. * //from ww w . jav a 2s . c o m * @param collection - collection to export * @param includeChildren - if true children should be exported * @param zipFileDestination - zip file destination to store the collection information * @throws IOException */ public void export(InstitutionalCollection collection, boolean includeChildren, File zipFileDestination) throws IOException { // create the path if it doesn't exist String path = FilenameUtils.getPath(zipFileDestination.getCanonicalPath()); if (!path.equals("")) { File pathOnly = new File(FilenameUtils.getFullPath(zipFileDestination.getCanonicalPath())); FileUtils.forceMkdir(pathOnly); } List<InstitutionalCollection> collections = new LinkedList<InstitutionalCollection>(); collections.add(collection); File collectionXmlFile = temporaryFileCreator.createTemporaryFile(extension); Set<FileInfo> allPictures = createXmlFile(collectionXmlFile, collections, includeChildren); FileOutputStream out = new FileOutputStream(zipFileDestination); ArchiveOutputStream os = null; try { os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out); os.putArchiveEntry(new ZipArchiveEntry("collection.xml")); FileInputStream fis = null; try { log.debug("adding xml file"); fis = new FileInputStream(collectionXmlFile); IOUtils.copy(fis, os); } finally { if (fis != null) { fis.close(); fis = null; } } log.debug("adding pictures size " + allPictures.size()); for (FileInfo fileInfo : allPictures) { File f = new File(fileInfo.getFullPath()); String name = FilenameUtils.getName(fileInfo.getFullPath()); name = name + '.' + fileInfo.getExtension(); log.debug(" adding name " + name); os.putArchiveEntry(new ZipArchiveEntry(name)); try { log.debug("adding input stream"); fis = new FileInputStream(f); IOUtils.copy(fis, os); } finally { if (fis != null) { fis.close(); fis = null; } } } os.closeArchiveEntry(); out.flush(); } catch (ArchiveException e) { throw new IOException(e); } finally { if (os != null) { os.close(); os = null; } } FileUtils.deleteQuietly(collectionXmlFile); }
From source file:com.qcadoo.plugin.internal.descriptorparser.DefaultPluginDescriptorParser.java
@Override public InternalPlugin parse(final Resource resource) { try {/*from w w w . ja v a2 s. c om*/ LOG.info("Parsing descriptor for:" + resource); boolean ignoreModules = false; URL url = ResourceUtils.extractJarFileURL(resource.getURL()); return parse(resource.getInputStream(), ignoreModules, FilenameUtils.getName(url.toString())); } catch (IOException e) { throw new PluginException(e.getMessage(), e); } catch (Exception e) { throw new PluginException(e.getMessage(), e); } }
From source file:cdc.util.Upload.java
public boolean anexos(HttpServletRequest request, HttpServletResponse response) throws Exception { if (ServletFileUpload.isMultipartContent(request)) { int cont = 0; ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = null; try {/* w w w . j av a2 s . c o m*/ fileItemsList = servletFileUpload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } String optionalFileName = ""; FileItem fileItem = null; Iterator it = fileItemsList.iterator(); do { //cont++; FileItem fileItemTemp = (FileItem) it.next(); if (fileItemTemp.isFormField()) { if (fileItemTemp.getFieldName().equals("file")) { optionalFileName = fileItemTemp.getString(); } } else { fileItem = fileItemTemp; } if (cont != (fileItemsList.size())) { if (fileItem != null) { String fileName = fileItem.getName(); if (fileItem.getSize() > 0) { if (optionalFileName.trim().equals("")) { fileName = FilenameUtils.getName(fileName); } else { fileName = optionalFileName; } String dirName = request.getServletContext().getRealPath(pasta); File saveTo = new File(dirName + fileName); //System.out.println("caminho: " + saveTo.toString() ); try { fileItem.write(saveTo); } catch (Exception e) { } } } } cont++; } while (it.hasNext()); return true; } else { return false; } }
From source file:net.bsrc.cbod.core.util.DBInitializeUtil.java
private static List<ImageModel> createImageModels(final String imageFolderPath, final boolean isTestImage, final EObjectType objectType) { List<ImageModel> resultList = new ArrayList<ImageModel>(); for (String filePath : CBODUtil.getFileList(imageFolderPath, CBODConstants.JPEG_SUFFIX)) { ImageModel imgModel = new ImageModel(); imgModel.setImagePath(filePath); imgModel.setImageName(FilenameUtils.getName(filePath)); imgModel.setTestImage(isTestImage); imgModel.setObjectType(objectType); resultList.add(imgModel);/*from www . j a v a 2 s . c o m*/ } return resultList; }
From source file:com.splunk.shuttl.archiver.archive.ArchiveConfigurationTest.java
public void getTmpDirectory_givenArchiverRootUri_pathIsAChildOfTheArchivingRootURI() { String archiverRoot = "valid:/uri/archiver/data"; when(mBean.getArchiverRootURI()).thenReturn(archiverRoot); URI tmpDirectory = createConfiguration().getTmpDirectory(); String tmpDirectoryName = FilenameUtils.getName(tmpDirectory.getPath()); URI expected = URI.create(archiverRoot + "/" + tmpDirectoryName); assertEquals(expected, tmpDirectory); }
From source file:de.thischwa.pmcms.view.context.object.GalleryLinkTool.java
/** * Getting the link tool to the zip file containing the {@link Image}s of the desired gallery. The zip file will * be built.//www . java 2 s .c o m * * @param gallery * @param siteRelativePath * @return Link tool to the zip file containing the {@link Image}s of the desired gallery. * @throws RenderingException */ public GalleryLinkTool getLinkToZip(final Gallery gallery, final String siteRelativePath) throws RenderingException { if (isExportView && CollectionUtils.isNotEmpty(gallery.getImages())) { String urlPathToZip = PathTool.getURLRelativePathToRoot(gallery.getParent()).concat(siteRelativePath) .concat("/").concat(gallery.getName()).concat(".zip"); setLink(urlPathToZip); Map<File, String> zipEntries = new HashMap<File, String>(); for (Image image : gallery.getImages()) { // TODO check it: order the images, if not, the hash of the zip is always different VirtualImage imageFile = new VirtualImage(PoInfo.getSite(gallery), false, true); imageFile.constructFromImage(image); zipEntries.put(imageFile.getBaseFile(), "/".concat(FilenameUtils.getName(imageFile.getBaseFile().getAbsolutePath()))); } try { String zipName = siteRelativePath.concat(File.separator).concat(gallery.getName()).concat(".zip"); File zipFile = new File(PoPathInfo.getSiteExportDirectory(PoInfo.getSite(gallery)), zipName); zipFile.getParentFile().mkdirs(); Zip.compressFiles(zipFile.getAbsoluteFile(), zipEntries); } catch (IOException e) { throw new RenderingException("While creating image zip file: ".concat(e.getMessage()), e); } } else { setLink("javascript:alert('Zip will be constructed not until export!');"); } return this; }
From source file:edu.ku.brc.specify.tools.LocalizerSearchHelper.java
/** * @param baseDir/*from w ww . ja v a 2 s. co m*/ * @return */ public Vector<Pair<String, String>> findOldL10NKeys(final String[] fileNames) { initLucene(true); //if (srcCodeFilesDir == null) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (srcCodeFilesDir != null) { chooser.setSelectedFile(new File(FilenameUtils.getName(srcCodeFilesDir.getAbsolutePath()))); chooser.setSelectedFile(new File(srcCodeFilesDir.getParent())); } if (chooser.showOpenDialog(UIRegistry.getMostRecentWindow()) == JFileChooser.APPROVE_OPTION) { srcCodeFilesDir = new File(chooser.getSelectedFile().getAbsolutePath()); } else { return null; } } indexSourceFiles(); Vector<Pair<String, String>> fullNotFoundList = new Vector<Pair<String, String>>(); try { ConversionLogger convLogger = new ConversionLogger(); convLogger.initialize("resources", "Resources"); for (String fileName : fileNames) { Vector<Pair<String, String>> notFoundList = new Vector<Pair<String, String>>(); Vector<String> terms = new Vector<String>(); String propFileName = baseDir.getAbsolutePath() + "/" + fileName; File resFile = new File(propFileName + ".properties"); if (resFile.exists()) { List<?> lines = FileUtils.readLines(resFile); for (String line : (List<String>) lines) { if (!line.startsWith("#")) { int inx = line.indexOf("="); if (inx > -1) { String[] toks = StringUtils.split(line, "="); if (toks.length > 1) { terms.add(toks[0]); } } } } } else { System.err.println("Doesn't exist: " + resFile.getAbsolutePath()); } String field = "contents"; QueryParser parser = new QueryParser(Version.LUCENE_36, field, analyzer); for (String term : terms) { Query query; try { if (term.equals("AND") || term.equals("OR")) continue; query = parser.parse(term); String subTerm = null; int hits = getTotalHits(query, 10); if (hits == 0) { int inx = term.indexOf('.'); if (inx > -1) { subTerm = term.substring(inx + 1); hits = getTotalHits(parser.parse(subTerm), 10); if (hits == 0) { int lastInx = term.lastIndexOf('.'); if (lastInx > -1 && lastInx != inx) { subTerm = term.substring(lastInx + 1); hits = getTotalHits(parser.parse(subTerm), 10); } } } } if (hits == 0 && !term.endsWith("_desc")) { notFoundList.add(new Pair<String, String>(term, subTerm)); log.debug("'" + term + "' was not found " + (subTerm != null ? ("SubTerm[" + subTerm + "]") : "")); } } catch (ParseException e) { e.printStackTrace(); } } String fullName = propFileName + ".html"; TableWriter tblWriter = convLogger.getWriter(FilenameUtils.getName(fullName), propFileName); tblWriter.startTable(); tblWriter.logHdr("Id", "Full Key", "Sub Key"); int cnt = 1; for (Pair<String, String> pair : notFoundList) { tblWriter.log(Integer.toString(cnt++), pair.first, pair.second != null ? pair.second : " "); } tblWriter.endTable(); fullNotFoundList.addAll(notFoundList); if (notFoundList.size() > 0 && resFile.exists()) { List<String> lines = (List<String>) FileUtils.readLines(resFile); Vector<String> linesCache = new Vector<String>(); for (Pair<String, String> p : notFoundList) { linesCache.clear(); linesCache.addAll(lines); int lineInx = 0; for (String line : linesCache) { if (!line.startsWith("#")) { int inx = line.indexOf("="); if (inx > -1) { String[] toks = StringUtils.split(line, "="); if (toks.length > 1) { if (toks[0].equals(p.first)) { lines.remove(lineInx); break; } } } } lineInx++; } } FileUtils.writeLines(resFile, linesCache); } } convLogger.closeAll(); } catch (IOException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(LocalizerSearchHelper.class, ex); ex.printStackTrace(); } return fullNotFoundList; }