Example usage for org.apache.commons.io FilenameUtils normalizeNoEndSeparator

List of usage examples for org.apache.commons.io FilenameUtils normalizeNoEndSeparator

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils normalizeNoEndSeparator.

Prototype

public static String normalizeNoEndSeparator(String filename) 

Source Link

Document

Normalizes a path, removing double and single dot path steps, and removing any final directory separator.

Usage

From source file:net.sf.jvifm.ui.shell.QuickRunShell.java

public boolean doCommand() {
    String cmd = null;/*from   w  ww  . j  a v a2s.c o  m*/
    String[] args = new String[] {};
    /*
    if (completeOptions != null && completeOptions.length > 0) {
       cmd = getCompletionText();
    } else {
    */

    cmd = txtCommand.getText();
    int argsRealBegin = cmd.indexOf(" ", argsBeginIndex);
    if (argsRealBegin > 0) { // arg
        String arg = cmd.substring(argsRealBegin + 1);
        cmd = cmd.substring(0, argsRealBegin).trim();
        args = arg.split("\\s+");
    }

    ShortcutsManager scm = ShortcutsManager.getInstance();
    if (scm.isShortCut(cmd)) {
        Shortcut cc = scm.findByName(cmd);
        Command command = new SystemCommand(cc.getText(), args, true);
        command.setPwd(Main.fileManager.getActivePanel().getPwd());
        commandRunner.run(command);
        return true;
    }

    String newPath = FilenameUtils.concat(pwd, cmd);
    newPath = FilenameUtils.normalizeNoEndSeparator(newPath);

    File file = null;
    try {
        file = new File(newPath);
    } catch (Exception e) {
        return false;
    }
    if (file != null && file.exists()) {
        if (file.isFile()) {
            // Util.openFileWithDefaultApp(newPath);
            Command command = new SystemCommand(newPath, args, true);
            command.setPwd(Main.fileManager.getActivePanel().getPwd());
            commandRunner.run(command);
            return true;
        }

        FileManager fileManager = Main.fileManager;
        FileLister activeLister = fileManager.getActivePanel();
        fileManager.activeGUI();
        activeLister.visit(newPath);
        return true;
    }
    String abPath = findExecuteInSysPath(cmd);
    if (abPath != null) {
        Command command = new SystemCommand(abPath, args, false, true);
        command.setPwd(Main.fileManager.getActivePanel().getPwd());
        commandRunner.run(command);
        return true;
    }
    return false;
}

From source file:integration.DeleteServiceFilesTest.java

/**
 * Gets a public repository on the OMERO data directory if one exists.
 * //from  w w  w  .jav a2 s  . co m
 * @return See above.
 * @throws Exception  Thrown if an error occurred.
 */
RepositoryPrx getLegacyRepository() throws Exception {
    RepositoryPrx legacy = null;
    RepositoryMap rm = factory.sharedResources().repositories();
    int repoCount = 0;
    String s = dataDir;
    for (OriginalFile desc : rm.descriptions) {
        String repoPath = desc.getPath().getValue() + desc.getName().getValue();
        s += "\nFound repository:" + desc.getPath().getValue() + desc.getName().getValue();
        if (FilenameUtils.equals(FilenameUtils.normalizeNoEndSeparator(dataDir),
                FilenameUtils.normalizeNoEndSeparator(repoPath))) {
            legacy = rm.proxies.get(repoCount);
            break;
        }
        repoCount++;
    }
    if (legacy == null) {
        throw new Exception("Unable to find legacy repository: " + s);
    }
    return legacy;
}

From source file:com.daphne.es.maintain.editor.web.controller.OnlineEditorController.java

@RequestMapping("/create/directory")
public String createDirectory(@RequestParam(value = "parentPath") String parentPath,
        @RequestParam(value = "name") String name, RedirectAttributes redirectAttributes) throws IOException {

    //?/// w w w.jav  a 2 s. c o  m
    name = FilenameUtils.normalizeNoEndSeparator(name);

    if (isValidFileName(name)) {
        String rootPath = sc.getRealPath(ROOT_DIR);
        parentPath = URLDecoder.decode(parentPath, Constants.ENCODING);

        File parent = new File(rootPath + File.separator + parentPath);
        File currentDirectory = new File(parent, name);
        boolean result = currentDirectory.mkdirs();
        if (result == false) {
            redirectAttributes.addFlashAttribute(Constants.ERROR,
                    "??[" + name + "]/?");
        } else {
            redirectAttributes.addFlashAttribute(Constants.MESSAGE, "??");
        }
    } else {
        redirectAttributes.addFlashAttribute(Constants.ERROR,
                "??[" + name + "]???????");
    }

    redirectAttributes.addAttribute("path", parentPath);
    return redirectToUrl(viewName("list"));
}

From source file:endrov.ioImageCollections.EvIONamebasedImageset.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 .j  ava  2  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:com.igormaznitsa.jcp.context.PreprocessorContext.java

/**
 * It finds a file for its path among files in source folder, it is prohibited to return files out of preprocessing folders.
 *
 * @param path the path to the needed file, it must not be null and the file must exist and be a file and be among files in preprocessing source folders
 * @return detected file object for the path
 * @throws IOException if it is impossible to find a file for the path
 *//*from ww w . j  a  v  a2 s. c o  m*/
@Nonnull
public File findFileInSourceFolder(@Nonnull final String path) throws IOException {
    if (path == null) {
        throw makeException("Path is null", null);
    }

    if (path.isEmpty()) {
        throw makeException("Path is empty", null);
    }

    File result = null;

    final TextFileDataContainer theFile = currentState.peekFile();
    final String parentDir = theFile == null ? null : theFile.getFile().getParent();

    final File resultFile = new File(path);
    if (resultFile.isAbsolute()) {
        // absolute path

        // check that the file is a child of a preprocessing source root else usage of the file is prohibited
        final String normalizedPath = FilenameUtils.normalizeNoEndSeparator(resultFile.getAbsolutePath());
        for (final File root : getSourceDirectoryAsFiles()) {
            final String rootNormalizedPath = FilenameUtils.normalizeNoEndSeparator(root.getAbsolutePath())
                    + File.separatorChar;
            if (normalizedPath.startsWith(rootNormalizedPath)) {
                result = resultFile;
                break;
            }
        }

        if (result == null) {
            throw makeException("Can't find file for path \'" + path
                    + "\' in preprocessing source folders, allowed usage only files in preprocessing source folders!",
                    null);
        } else if (!result.isFile()) {
            throw makeException("File \'" + result + "\' is either not found or not a file", null);
        }

    } else if (parentDir != null) {
        // relative path
        result = new File(parentDir, path);
    } else {
        final List<File> setOfFoundFiles = new ArrayList<File>();
        for (final File root : getSourceDirectoryAsFiles()) {
            final File variant = new File(root, path);
            if (variant.exists() && variant.isFile()) {
                setOfFoundFiles.add(variant);
            }
        }

        if (setOfFoundFiles.size() == 1) {
            result = setOfFoundFiles.get(0);
        } else if (setOfFoundFiles.isEmpty()) {
            result = null;
        } else {
            throw makeException("Found several variants for path \'" + path + "\' in different source roots",
                    null);
        }

        if (result == null) {
            throw makeException("Can't find file for path \'" + path
                    + "\' among source files registered for preprocessing.", null);
        } else if (!result.isFile()) {
            throw makeException(
                    "File \'" + PreprocessorUtils.getFilePath(result) + "\' is either not found or not a file",
                    null);
        }
    }

    return result;
}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceDirectoryHandler.java

/**
 * @see WorkspaceDirectoryHandler#createDirectoryInWorkspace(int, java.lang.String)
 */// www.  j a  v  a  2 s  . co m
@Override
public File createDirectoryInWorkspace(int workspaceID, String directoryName) throws IOException {

    String normalizedDirectoryName = FilenameUtils.normalizeNoEndSeparator(directoryName);
    File workspaceUploadDirectory = getUploadDirectoryForWorkspace(workspaceID);
    File finalDirectory = new File(workspaceUploadDirectory, normalizedDirectoryName);
    finalDirectory.mkdir();

    return finalDirectory;
}

From source file:nl.mvdr.umvc3replayanalyser.controller.FileUtils.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 '\'.
 * //from   w  w  w. j  a va 2  s .  co  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 relative path
 * @throws PathResolutionException
 *             in case the paths are not related at all
 */
static String getRelativePath(String targetPath, String basePath, String pathSeparator)
        throws PathResolutionException {

    // 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.abstracthorizon.proximity.impl.ProximityUtils.java

/**
 * Mangle item paths for emerge groups./*from   w  w w. j  a  v a  2  s .c  o m*/
 * 
 * @param items the items
 */
public static void mangleItemPathsForEmergeGroups(List items) {
    for (Iterator i = items.iterator(); i.hasNext();) {
        ItemProperties ip = (ItemProperties) i.next();
        if (ip.getDirectoryPath().equals(ItemProperties.PATH_ROOT)) {
            // make /groupId as path
            ip.setDirectoryPath(ItemProperties.PATH_ROOT + ip.getRepositoryGroupId());
        } else {
            // make /groupId/... as path WITHOUT trailing /
            ip.setDirectoryPath(FilenameUtils.separatorsToUnix(FilenameUtils.normalizeNoEndSeparator(
                    ItemProperties.PATH_ROOT + ip.getRepositoryGroupId() + ip.getDirectoryPath())));
        }
    }
}

From source file:org.apache.falcon.recipe.RecipeTool.java

private static String getLastPartOfPath(final String path) {
    String normalizedWfPath = FilenameUtils.normalizeNoEndSeparator(path);
    return (normalizedWfPath == null) ? FilenameUtils.getName(path) : FilenameUtils.getName(normalizedWfPath);
}

From source file:org.apache.jackrabbit.oak.run.osgi.OakOSGiRepositoryFactory.java

@SuppressWarnings("unchecked")
private static void processConfig(Map config) {
    String home = (String) config.get(REPOSITORY_HOME);
    checkNotNull(home, "Repository home not defined via [%s]", REPOSITORY_HOME);

    home = FilenameUtils.normalizeNoEndSeparator(home);

    String bundleDir = FilenameUtils.concat(home, "bundles");
    config.put(Constants.FRAMEWORK_STORAGE, bundleDir);

    //FIXME Pojo SR currently reads this from system property instead of Framework Property
    config.put(Constants.FRAMEWORK_STORAGE, bundleDir);

    //Directory used by Felix File Install to watch for configs
    config.put("felix.fileinstall.dir", FilenameUtils.concat(home, "config"));

    //Set log level for config to INFO LogService.LOG_INFO
    config.put("felix.fileinstall.log.level", "3");

    //This ensures that configuration is registered in main thread
    //and not in a different thread
    config.put("felix.fileinstall.noInitialDelay", "true");

    config.put("repository.home", FilenameUtils.concat(home, "repository"));

}