List of usage examples for org.apache.commons.io FilenameUtils separatorsToUnix
public static String separatorsToUnix(String path)
From source file:eu.scape_project.tb.lsdr.seqfileutility.SequenceFileWriter.java
private void writeFileContent(File file) throws IOException { long fileLength = file.length(); if (fileLength <= Integer.MAX_VALUE) { Text key = new Text(); String filePath = file.getAbsolutePath(); String keyPath = FilenameUtils.separatorsToUnix(filePath); key.set(keyPath);//from w ww . jav a 2s .c o m FileInputStream fis = new FileInputStream(file); byte[] byteArray = new byte[(int) fileLength]; byte[] buf = new byte[BUFFER_SIZE]; int bytesRead = fis.read(buf); int offset = 0; int chunk_count = 0; while (bytesRead != -1) { System.arraycopy(buf, 0, byteArray, offset, bytesRead); offset += bytesRead; bytesRead = fis.read(buf); chunk_count++; } BytesWritable value = new BytesWritable(byteArray); int len = (int) fileLength; value.setSize(len); filecount++; logger.info(this.getId() + ": " + filecount + ":" + key); writer.append(key, value); fis.close(); } else { logger.warn("File " + file.getAbsolutePath() + " is too large to be " + "added to a sequence file (skipped)."); } }
From source file:de.undercouch.vertx.lang.typescript.TestExamplesRunner.java
private void compile(File script, TypeScriptCompiler compiler, SourceFactory parentSourceFactory, File pathToTypings) throws IOException { String name = FilenameUtils.separatorsToUnix(script.getPath().replaceFirst("\\.js$", ".ts")); compiler.compile(name, new SourceFactory() { @Override/*from w w w. j a v a 2 s. c o m*/ public Source getSource(String filename, String baseFilename) throws IOException { if (FilenameUtils.equalsNormalized(filename, name)) { Source src = Source.fromFile(script, StandardCharsets.UTF_8); String srcStr = src.toString(); // find all required vertx modules Pattern requireVertx = Pattern .compile("var\\s+.+?=\\s*require\\s*\\(\\s*\"(vertx-.+?)\"\\s*\\)"); Matcher requireVertxMatcher = requireVertx.matcher(srcStr); List<String> modules = new ArrayList<>(); modules.add("vertx-js/vertx.d.ts"); modules.add("vertx-js/java.d.ts"); while (requireVertxMatcher.find()) { String mod = requireVertxMatcher.group(1); modules.add(mod); } // add default type definitions Path relPathToTypings = script.toPath().getParent().relativize(pathToTypings.toPath()); for (String mod : modules) { srcStr = "/// <reference path=\"" + FilenameUtils.separatorsToUnix(relPathToTypings.resolve(mod).toString()) + "\" />\n" + srcStr; } // replace 'var x = require("...")' by 'import x = require("...")' srcStr = srcStr.replaceAll("var\\s+(.+?=\\s*require\\s*\\(.+?\\))", "import $1"); return new Source(script.toURI(), srcStr); } return parentSourceFactory.getSource(filename, baseFilename); } }); }
From source file:com.silverpeas.silvercrawler.servlets.DragAndDrop.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SilverTrace.info("silverCrawler", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD"); HttpRequest request = HttpRequest.decorate(req); request.setCharacterEncoding("UTF-8"); if (!request.isContentInMultipart()) { res.getOutputStream().println("SUCCESS"); return;//from w w w. j a va2s . c o m } try { String sessionId = request.getParameter("SessionId"); String instanceId = request.getParameter("ComponentId"); String ignoreFolders = request.getParameter("IgnoreFolders"); SessionManagementFactory factory = SessionManagementFactory.getFactory(); SessionManagement sessionManagement = factory.getSessionManagement(); SessionInfo session = sessionManagement.getSessionInfo(sessionId); SilverCrawlerSessionController sessionController = session .getAttribute("Silverpeas_SilverCrawler_" + instanceId); // build report UploadReport report = sessionController.getLastUploadReport(); if (report == null) { report = new UploadReport(); sessionController.setLastUploadReport(report); } // if first part of upload, needs to generate temporary path File savePath = report.getRepositoryPath(); if (report.getRepositoryPath() == null) { savePath = FileUtils.getFile(FileRepositoryManager.getTemporaryPath(), "tmpupload", ("SilverWrawler_" + System.currentTimeMillis())); report.setRepositoryPath(savePath); } // Loop items List<FileItem> items = request.getFileItems(); for (FileItem item : items) { if (!item.isFormField()) { String fileUploadId = item.getFieldName().substring(4); String unixParentPath = FilenameUtils.separatorsToUnix( FileUploadUtil.getParameter(items, "relpathinfo" + fileUploadId, null)); File parentPath = FileUtils.getFile(unixParentPath); // if ignoreFolder is activated, no folders are permitted if (StringUtil.isDefined(parentPath.getName()) && StringUtil.getBooleanValue(ignoreFolders)) { report.setFailed(true); report.setForbiddenFolderDetected(true); break; } // Get the file path and name File fileName = FileUtils.getFile(parentPath, FileUploadUtil.getFileName(item)); // Logging the name of the file SilverTrace.info("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", "fileName = " + fileName.getName()); // Registering in the temporary location File fileToSave = FileUtils.getFile(savePath, fileName.getPath()); fileToSave.getParentFile().mkdirs(); item.write(fileToSave); // Save info into report UploadItem uploadItem = new UploadItem(); uploadItem.setFileName(fileName.getName()); uploadItem.setParentRelativePath(fileName.getParentFile()); report.addItem(uploadItem); } else { SilverTrace.info("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", "item = " + item.getFieldName() + " - " + item.getString()); } } } catch (Exception e) { SilverTrace.debug("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", e); res.getOutputStream().println("ERROR"); return; } res.getOutputStream().println("SUCCESS"); }
From source file:com.silverpeas.silvercrawler.model.FileFolder.java
public FileFolder(String rootPath, String path, boolean isAdmin, String componentId) { this.path = path; files = new ArrayList<FileDetail>(0); folders = new ArrayList<FileDetail>(0); try {//from w ww . ja va2 s.com SilverTrace.debug("silverCrawler", "FileFolder.FileFolder()", "root.MSG_GEN_PARAM_VALUE", "Starting constructor for FileFolder. Path = " + path); File f = new File(path); SilverTrace.debug("silverCrawler", "FileFolder.FileFolder()", "root.MSG_GEN_PARAM_VALUE", "isExists " + f.exists() + " isFile=" + f.isFile()); writable = f.canWrite(); if (f.exists()) { this.name = f.getName(); this.readable = f.canRead(); File[] children = f.listFiles(); IndexReader reader = null; boolean isIndexed = false; if (isAdmin) { // ouverture de l'index Directory indexPath = FSDirectory .open(new File(IndexFileManager.getAbsoluteIndexPath("", componentId))); if (IndexReader.indexExists(indexPath)) { reader = IndexReader.open(indexPath); } } if (children != null && children.length > 0) { for (File childFile : children) { SilverTrace.debug("silverCrawler", "FileFolder.FileFolder()", "root.MSG_GEN_PARAM_VALUE", "Name = " + childFile.getName()); isIndexed = false; if (isAdmin) { // rechercher si le rpertoire (ou le fichier) est index String pathIndex = componentId + "|"; if (childFile.isDirectory()) { pathIndex = pathIndex + "LinkedDir" + "|"; } else { pathIndex = pathIndex + "LinkedFile" + "|"; } pathIndex = pathIndex + FilenameUtils.separatorsToUnix(childFile.getPath()); SilverTrace.debug("silverCrawler", "FileFolder.FileFolder()", "root.MSG_GEN_PARAM_VALUE", "pathIndex = " + pathIndex); Term term = new Term("key", pathIndex); if (reader != null && reader.docFreq(term) == 1) { isIndexed = true; } } if (childFile.isDirectory()) { folders.add(new FileDetail(childFile.getName(), childFile.getPath(), null, childFile.length(), true, isIndexed)); } else { String childPath = FileUtils.getFile(childFile.getPath().substring(rootPath.length())) .getPath(); files.add(new FileDetail(childFile.getName(), childPath, childFile.getPath(), childFile.length(), false, isIndexed)); } } } // fermeture de l'index if (reader != null && isAdmin) { reader.close(); } } } catch (Exception e) { throw new SilverCrawlerRuntimeException("FileFolder.FileFolder()", SilverpeasRuntimeException.ERROR, "silverCrawler.IMPOSSIBLE_DACCEDER_AU_REPERTOIRE", e); } }
From source file:com.centeractive.ws.ResourceUtils.java
private static String constructResourcePath(String packagePath, String resourceName) { String resourcePath = String.format("/%s/%s", packagePath, resourceName); String resourcePathUnixSeparators = FilenameUtils.separatorsToUnix(resourcePath); String resourcePathNoLeadingSeparators = removeLeadingUnixSeparators(resourcePathUnixSeparators); String normalizedResourcePath = FilenameUtils.normalizeNoEndSeparator(resourcePathNoLeadingSeparators); return normalizedResourcePath; }
From source file:com.consol.citrus.admin.service.TestCaseServiceImpl.java
@Override public Long getTestCount(Project project) { Long testCount = Long.valueOf(FileUtils.getTestFiles(getTestDirectory(project)).size()); try {/*from ww w. java 2 s . c o m*/ Resource[] javaSources = new PathMatchingResourcePatternResolver().getResources( "file:" + FilenameUtils.separatorsToUnix(getJavaDirectory(project)) + "**/*.java"); for (Resource resource : javaSources) { File file = resource.getFile(); String testName = FilenameUtils.getBaseName(file.getName()); String testPackage = file.getParentFile().getAbsolutePath() .substring(getJavaDirectory(project).length()).replace(File.separatorChar, '.'); if (knownToClasspath(testPackage, testName)) { testCount += getTestCaseInfoFromClass(testPackage, testName, file).size(); } else { testCount += getTestCaseInfoFromFile(testPackage, testName, file).size(); } } } catch (IOException e) { log.warn("Failed to read Java source files - list of test cases for this project is incomplete", e); } return testCount; }
From source file:jeplus.util.RelativeDirUtil.java
/** * Get the relative path from one file to another, specifying the directory separator. If one of the provided resources does not exist, * it is assumed to be a file unless it ends with '/' or '\'. * * @param targetPath targetPath is calculated to this file * @param basePath basePath is calculated from this file * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on * Windows (for example)// w ww . ja v a2 s. c om * @return */ public static String getRelativePath(String targetPath, String basePath, String pathSeparator) { // Normalize the paths String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath); String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath); // Undo the changes to the separators made by normalization switch (pathSeparator) { case "/": normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath); break; case "\\": normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath); break; default: throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'"); } String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator)); String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator)); // First get all the common elements. Store them as a string, // and also count how many of them there are. StringBuilder common = new StringBuilder(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].equals(base[commonIndex])) { common.append(target[commonIndex]).append(pathSeparator); commonIndex++; } if (commonIndex == 0) { // No single common path element. This most // likely indicates differing drive letters, like C: and D:. // These paths cannot be relativized. throw new PathResolutionException("No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath + "'"); } // The number of directories we have to backtrack depends on whether the base is a file or a dir // For example, the relative path from // // /foo/bar/baz/gg/ff to /foo/bar/baz // // ".." if ff is a file // "../.." if ff is a directory // // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because // the resource referred to by this path may not actually exist, but it's the best I can do boolean baseIsFile = true; File baseResource = new File(normalizedBasePath); if (baseResource.exists()) { baseIsFile = baseResource.isFile(); } else if (basePath.endsWith(pathSeparator)) { baseIsFile = false; } StringBuilder relative = new StringBuilder(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append("..").append(pathSeparator); } } // deal with current folder (targetPath and basePath are the same) if (normalizedTargetPath.length() <= common.length()) { relative.append("."); } else { relative.append(normalizedTargetPath.substring(common.length())); } return relative.append(pathSeparator).toString(); }
From source file:MSUmpire.LCMSPeakStructure.LCMSPeakMS1.java
public String GetDefaultPepXML() { return FilenameUtils.separatorsToUnix(FilenameUtils.getFullPath(ScanCollectionName) + "interact-" + FilenameUtils.getBaseName(ScanCollectionName) + ".pep.xml"); }
From source file:com.ariht.maven.plugins.config.io.DirectoryReader.java
/** * Directories and/or specific files you do not wish to include in config generation * are converted from String to File instances. */// ww w . j a v a2 s . c om private List<File> convertStringsToFiles(final List<String> filesToIgnore) { if (filesToIgnore == null || filesToIgnore.isEmpty()) { return EMPTY_FILE_LIST; } final List<File> filesIgnored = new ArrayList<File>(filesToIgnore.size()); for (String fileToIgnore : new LinkedHashSet<String>(filesToIgnore)) { if (StringUtils.isNotBlank(fileToIgnore)) { fileToIgnore = FilenameUtils.separatorsToUnix(FilenameUtils.normalize(fileToIgnore.trim())); final File file = new File(fileToIgnore); if (file.exists()) { log.debug("Adding ignore for file: " + file.getAbsolutePath()); filesIgnored.add(file); } } } return filesIgnored; }
From source file:com.ibm.dbwkl.request.internal.SetupHandler.java
/** * @param configFile//from ww w.j av a2 s . co m * @return returns the result after writing the new setup file */ private STAFResult WriteAutoSetup(File configFile) { // Open the file and add the options try { FileWriter writer = new FileWriter(configFile, true); BufferedWriter bw = new BufferedWriter(writer); String jcclibs = this.parseResult.get(Options.SETUP_JCCLIBS); bw.newLine(); bw.write("# [DB2WKL SETUP] (Don't remove the comments!)\n"); bw.write("# DB2 Workload Service\n"); bw.write("# (this section was generated by the setup command)" + "\n"); bw.write("SET SYSTEM VAR IBM/DB2WKL/AutoSetup=true" + "\n"); if (this.parseResult.containsKey(Options.SETUP_JCCLIBS)) { bw.write("SET SYSTEM VAR IBM/OMPE/DB2WKL/JCCLIB=\"" + FilenameUtils.separatorsToUnix(jcclibs) + "\"" + "\n"); STAFHandler.instance.getSTAFHandle().submit2("local", "VAR", "SET SYSTEM VAR IBM/OMPE/DB2WKL/JCCLIB=\"" + FilenameUtils.separatorsToUnix(jcclibs) + "\""); } else { bw.write( "SET SYSTEM VAR IBM/OMPE/DB2WKL/JCCLIB=\"{STAF/config/STAFroot}/services/db2wkl/libs/jcc/\"" + "\n"); STAFHandler.instance.getSTAFHandle().submit2("local", "VAR", "SET SYSTEM VAR IBM/OMPE/DB2WKL/JCCLIB=\"{STAF/config/STAFroot}/services/db2wkl/libs/jcc/\""); } bw.write( "SERVICE db2wkl LIBRARY JSTAF EXECUTE {STAF/config/STAFroot}/services/db2wkl/db2wkl.jar OPTION JVMName=DB2WKLJVM" + "\n"); bw.write("# [DB2WKL SETUP]\n"); bw.newLine(); bw.close(); writer.close(); // when writing the file was successful also register the variables to be available immedately STAFHandler.instance.getSTAFHandle().submit2("local", "VAR", "SET SYSTEM VAR IBM/DB2WKL/AutoSetup=true"); } catch (IOException e) { Logger.log("Could not write into config file: " + e.getMessage(), LogLevel.Error); return new STAFResult(STAFResult.FileWriteError); } return new STAFResult(STAFResult.Ok); }