List of usage examples for org.apache.commons.io FilenameUtils separatorsToUnix
public static String separatorsToUnix(String path)
From source file:org.jumpmind.symmetric.file.FileSyncUtils.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 '\'. * /* w w w .ja va 2 s.c om*/ * @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) */ 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 if (pathSeparator.equals("/")) { normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath); } else if (pathSeparator.equals("\\")) { normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath); } else { 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. StringBuffer common = new StringBuffer(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].equals(base[commonIndex])) { common.append(target[commonIndex] + 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; } StringBuffer relative = new StringBuffer(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append(".." + pathSeparator); } } relative.append(normalizedTargetPath.substring(common.length())); return relative.toString(); }
From source file:org.jwebsocket.plugins.filesystem.FileSystemPlugIn.java
/** * Gets the file list from a given alias an optionally from a sub path. * * @param aUsername The requester client username. * @param aToken/*from ww w . j a v a 2 s . co m*/ * @return */ private Token mGetFilelist(WebSocketConnector aConnector, Token aToken) { String lAlias = aToken.getString("alias"); boolean lRecursive = aToken.getBoolean("recursive", false); boolean lIncludeDirs = aToken.getBoolean("includeDirs", false); List<Object> lFilemasks = aToken.getList("filemasks", new FastList<Object>()); String lSubPath = aToken.getString("path", null); Object lObject; String lBaseDir; Token lToken = TokenFactory.createToken(); lObject = mSettings.getAliasPath(lAlias); if (lObject != null) { lBaseDir = (String) lObject; lBaseDir = replaceAliasVars(aConnector, lBaseDir); /* lBaseDir = JWebSocketConfig.expandEnvVarsAndProps(lBaseDir). replace("{username}", aConnector.getUsername()); */ File lDir; if (null != lSubPath) { lDir = new File(lBaseDir + File.separator + lSubPath); } else { lDir = new File(lBaseDir + File.separator); } if (!isPathInFS(lDir, lBaseDir)) { lToken.setInteger("code", -1); lToken.setString("msg", "The path '" + lSubPath + "' is out of the file-system location!"); return lToken; } else if (!(lDir.exists() && lDir.isDirectory())) { lToken.setInteger("code", -1); lToken.setString("msg", "The path '" + lSubPath + "' is not directory on target '" + lAlias + "' alias!"); return lToken; } // IOFileFilter lFileFilter = FileFilterUtils.nameFileFilter(lFilemask); String[] lFilemaskArray = new String[lFilemasks.size()]; int lIdx = 0; for (Object lMask : lFilemasks) { lFilemaskArray[lIdx] = (String) lMask; lIdx++; } IOFileFilter lFileFilter = new WildcardFileFilter(lFilemaskArray); IOFileFilter lDirFilter = null; if (lRecursive) { lDirFilter = FileFilterUtils.directoryFileFilter(); } Collection<File> lFiles = FileUtils.listFilesAndDirs(lDir, lFileFilter, lDirFilter); List<Map> lFileList = new FastList<Map>(); File lBasePath = new File(lBaseDir); MimetypesFileTypeMap lMimesMap = new MimetypesFileTypeMap(); String lRelativePath; for (File lFile : lFiles) { if (lFile == lDir // we don't want directories to be returned // except explicitely requested || (!lIncludeDirs && lFile.isDirectory())) { continue; } Map<String, Object> lFileData = new FastMap<String, Object>(); String lFilename = lFile.getAbsolutePath().replace(lBasePath.getAbsolutePath() + File.separator, ""); // we always return the path in unix/url/java format String lUnixPath = FilenameUtils.separatorsToUnix(lFilename); int lSeparator = lUnixPath.lastIndexOf("/"); if (lSeparator != -1) { lFilename = lUnixPath.substring(lSeparator + 1); lRelativePath = lUnixPath.substring(0, lSeparator + 1); } else { lRelativePath = ""; } lFileData.put("relativePath", lRelativePath); lFileData.put("filename", lFilename); lFileData.put("size", lFile.length()); lFileData.put("modified", Tools.DateToISO8601(new Date(lFile.lastModified()))); lFileData.put("hidden", lFile.isHidden()); lFileData.put("canRead", lFile.canRead()); lFileData.put("canWrite", lFile.canWrite()); lFileData.put("directory", lFile.isDirectory()); lFileData.put("mime", lMimesMap.getContentType(lFile)); if (lAlias.equals(PRIVATE_ALIAS_DIR_KEY)) { lFileData.put("url", getString(ALIAS_WEB_ROOT_KEY, ALIAS_WEB_ROOT_DEF) // in URLs we only want forward slashes + FilenameUtils.separatorsToUnix(lFilename)); } lFileList.add(lFileData); } lToken.setList("files", lFileList); lToken.setInteger("code", 0); lToken.setString("msg", "ok"); } else { lToken.setInteger("code", -1); lToken.setString("msg", "No alias '" + lAlias + "' defined for filesystem plug-in"); } return lToken; }
From source file:org.jwebsocket.plugins.reporting.Settings.java
/** * Sets the report folder//from ww w .j av a 2s. c o m * * @param aReportFolder */ public void setReportFolder(String aReportFolder) { mReportFolder = aReportFolder; mReportFolder = FilenameUtils.separatorsToUnix(JWebSocketConfig.expandEnvVarsAndProps(mReportFolder)); if (!mReportFolder.endsWith("/")) { mReportFolder += "/"; } }
From source file:org.jwebsocket.ui.TestDialog.java
private void loadPropertyFile() { mJMSServerProperties = new Properties(); String lHomeEnv = System.getenv("JWEBSOCKET_HOME"); if (lHomeEnv != null) { try {/*w w w . j a v a 2 s . co m*/ lHomeEnv = FilenameUtils.separatorsToUnix(lHomeEnv); mLog("Loading JMSServer properties file"); // loading a properties file with the default data for the JMSSendPayloadDialog mJMSServerProperties .load(new FileInputStream(lHomeEnv + "conf/jWebSocketSwingGUI/JMSDemoServer.properties")); mLog("JMSServer properties file loaded correctly with the following configurations: " + mJMSServerProperties.toString()); } catch (IOException lException) { mLog(lException.getMessage()); } } }
From source file:org.kalypso.ui.repository.RepositoryDumper.java
private void doDump(final Writer structureWriter, final File zmlFile, final IRepositoryItem item) throws IOException, SensorException { final String structIdentifier = buildStructIdentifier(item); structureWriter.write(structIdentifier); structureWriter.write(';'); final IObservation observation = ObservationCache.getInstance().getObservationFor(item); if (observation != null) { final String relativePathTo = FileUtilities.getRelativePathTo(m_directory, zmlFile); /*//from ww w . ja va 2 s. c o m * We write a unix style path here, as this is more generally recognized. Also, we can directly use the * structure.txt for PSI-Fake */ final String unixPath = FilenameUtils.separatorsToUnix(relativePathTo); structureWriter.write(unixPath); structureWriter.write(';'); structureWriter.write(observation.getName()); /* Dump if neccessary. */ final DateRange dra = ObservationViewHelper.makeDateRange(item); ZmlFactory.writeToFile(observation, zmlFile, new ObservationRequest(dra)); } structureWriter.write("\n"); //$NON-NLS-1$ }
From source file:org.larz.dom4.editor.ResourceUtils.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 * '\'.//www.ja va2 s .c o m * * @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) * @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 if (pathSeparator.equals("/")) { normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath); } else if (pathSeparator.equals("\\")) { normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath); } else { 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. StringBuffer common = new StringBuffer(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].equals(base[commonIndex])) { common.append(target[commonIndex] + 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; } StringBuffer relative = new StringBuffer(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append(".." + pathSeparator); } } relative.append(normalizedTargetPath.substring(common.length())); return relative.toString(); }
From source file:org.objectstyle.woproject.maven2.wolifecycle.AbstractWOMojo.java
protected boolean isWebObjectAppleGroup(final String dependencyGroup) { if (dependencyGroup == null) { return false; }//ww w.j ava2 s . com String normalizedGroup = FilenameUtils.separatorsToUnix(dependencyGroup); boolean returnValue = MAVEN_WEBOBJECTS_GROUP_ID.equals(normalizedGroup); getLog().debug("The group " + normalizedGroup + " is " + (returnValue ? "" : "NOT ") + "an Apple group."); return returnValue; }
From source file:org.openoffice.maven.Environment.java
/** * Guess office home from search path./* w ww .j ava 2s .c om*/ * This method has default visibility for testing. * * @param path the path * @return the file */ static File guessOfficeHomeFromPATH(String path) { String[] pathElements = StringUtils.split(path, File.pathSeparatorChar); String baseDirName = getBaseDirName(); for (int i = 0; i < pathElements.length; i++) { String pathname = FilenameUtils.separatorsToUnix(pathElements[i]); pathname = FilenameUtils.normalizeNoEndSeparator(pathname); int n = pathname.lastIndexOf(baseDirName); if (n > 0) { return new File(pathname.substring(0, n)); } } return null; }
From source file:org.openoffice.maven.idl.IdlBuilderMojo.java
/** * Guess the root module of the OOo extension API. * /*from w w w . j av a 2 s . co m*/ * <p>The folders containing the IDL files has to follow the * same hierarchy than the IDL modules declared in the IDL files.</p> * * <p>The root module is the path of IDL folders which are the only * children of their parent. A valid IDL folder respects the * regular expression defined by {@link #IDENTIFIER_REGEX}.</p> * * @return the guessed module or an empty string if it can't be guessed. */ private String guessRootModule() { File idlDir = ConfigurationManager.getIdlDir(); int childCount = 1; File currentFile = idlDir; while (childCount == 1) { // List only the valid children String[] children = currentFile.list(new PackageNameFilter()); childCount = children.length; if (childCount == 1) { currentFile = new File(currentFile, children[0]); } } if (currentFile.equals(idlDir)) { this.getLog().warn("no children found in " + idlDir); return ""; } String modulePath = currentFile.getPath().substring(idlDir.getPath().length() + 1); modulePath = FilenameUtils.separatorsToUnix(modulePath); String rootModule = modulePath.replaceAll("/", "."); return rootModule; }
From source file:org.opoo.press.maven.wagon.git.GitWagon.java
@Override public void put(File source, String destination) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { if (source.isDirectory()) { throw new IllegalArgumentException("Source is a directory: " + source); }/*from w ww .j av a 2 s . co m*/ String resourceName = FilenameUtils.separatorsToUnix(destination); Resource resource = new Resource(resourceName); firePutInitiated(resource, source); firePutStarted(resource, source); try { File file = new File(checkoutDirectory, destination); file.getParentFile().mkdirs(); transfer(resource, source, new FileOutputStream(file), true); } catch (Exception e) { fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw new TransferFailedException("Unable to put file", e); } firePutCompleted(resource, source); }