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

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

Introduction

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

Prototype

public static String normalize(String filename, boolean unixSeparator) 

Source Link

Document

Normalizes a path, removing double and single dot path steps.

Usage

From source file:org.datavyu.util.OFileUtils.java

/**
 * Generates the longest common directory for the two given absolute paths.
 *
 * @param path1/*from   w w w . j a  va 2  s .com*/
 * @param path2
 * @return String representing the longest common directory for path1 and
 *         path2. null if no such common directory (i.e. if the files were
 *         on different drives)
 */
public static String longestCommonDir(final String path1, final String path2) {

    if ((path1 == null) || (path2 == null)) {
        throw new NullPointerException();
    }

    String pathA = FilenameUtils.normalize(path1, true);
    String pathB = FilenameUtils.normalize(path2, true);

    final char sep = '/';

    int iA = pathA.indexOf(sep);
    int iB = pathB.indexOf(sep);

    if ((iA == -1) || (iB == -1)) {
        return null;
    }

    String lcd = null;

    while (pathA.substring(0, iA).equals(pathB.substring(0, iB))) {
        lcd = pathA.substring(0, iA + 1);

        iA = pathA.indexOf(sep, iA + 1);
        iB = pathB.indexOf(sep, iB + 1);

        if ((iA == -1) || (iB == -1)) {
            break;
        }
    }

    return lcd;
}

From source file:org.datavyu.util.OFileUtils.java

/**
 * Calculate the difference in directory levels between basePath and path.
 * basePath must be a predecessor of path.
 * basePath must be a directory./*from w  w w .  j a  v  a 2  s. co  m*/
 * basePath and path must be valid paths of the same filesystem and mount
 * point.
 * basePath and path must be absolute paths.
 * Directories must have '/' at the end of the path.
 *
 * @param basePath
 * @param path
 * @return a positive integer >= 0 denoting the difference in directory
 *         levels if the difference can be determined. -1 if the difference
 *         cannot be determined.
 */
public static int levelDifference(final String basePath, final String path) {

    if ((basePath == null) || (path == null)) {
        throw new NullPointerException();
    }

    File base = new File(FilenameUtils.normalize(basePath, true));
    File ancestor = new File(FilenameUtils.getFullPath(FilenameUtils.normalize(path, true)));

    int diff = 0;

    while (!base.equals(ancestor)) {
        ancestor = ancestor.getParentFile();

        if (ancestor != null) {
            diff++;
        } else {
            return -1;
        }
    }

    return diff;
}

From source file:org.datavyu.util.OFileUtils.java

/**
 * Generate a string S such that basePath.concat(S).equals(filePath)
 * basePath must be a predecessor of file path.
 * basePath must be a directory./*from w  w w .  j a v a 2s.  c  om*/
 * Directories must have '/' at the end of the path.
 *
 * @param basePath
 * @param filePath
 * @return null if filePath does not have basePath as a prefix.
 */
public static String relativeToBase(final String basePath, final String filePath) {

    if ((basePath == null) || (filePath == null)) {
        throw new NullPointerException();
    }

    String base = FilenameUtils.normalize(basePath, true);
    String file = FilenameUtils.normalize(filePath, true);

    if (!file.startsWith(base)) {
        return null;
    }

    return file.substring(base.length());
}

From source file:org.eclipse.wb.internal.swt.utils.ResourceManagerClassLoaderInitializer.java

/**
 * @return the {@link URL} for resource in plugin.
 *///from ww  w  . j  a v a  2 s  .  c o  m
private URL getEntry(String symbolicName, String fullPath) throws Exception {
    // try target platform
    {
        IPluginModelBase modelBase = PluginRegistry.findModel(symbolicName);
        String installLocation = modelBase.getInstallLocation();
        if (!StringUtils.isEmpty(installLocation) && installLocation.toLowerCase().endsWith(".jar")) {
            String urlPath = "jar:file:/" + installLocation + "!/" + fullPath;
            urlPath = FilenameUtils.normalize(urlPath, true);
            return new URL(urlPath);
        }
    }
    // try workspace plugin
    {
        IPluginModelBase pluginModel = PluginRegistry.findModel(symbolicName);
        if (pluginModel != null) {
            IResource underlyingResource = pluginModel.getUnderlyingResource();
            if (underlyingResource != null) {
                IProject project = underlyingResource.getProject();
                return project.getFile(new Path(fullPath)).getLocationURI().toURL();
            }
        }
    }
    // try runtime plugin
    {
        Bundle bundle = Platform.getBundle(symbolicName);
        if (bundle != null) {
            return bundle.getEntry(fullPath);
        }
    }
    // not found
    return null;
}

From source file:org.grycap.gpf4med.util.URLUtils.java

/**
 * Parses a URL from a String. This method supports file-system paths 
 * (e.g. /foo/bar).//from  w  w w . j  a va2s . com
 * @param str String representation of an URL.
 * @return an URL.
 * @throws IOException If an input/output error occurs.
 */
public static URL parseURL(final String str) throws MalformedURLException {
    URL url = null;
    if (StringUtils.isNotBlank(str)) {
        try {
            url = new URL(str);
        } catch (MalformedURLException e) {
            url = null;
            if (!str.matches("^[a-zA-Z]+[/]*:[^\\\\]")) {
                // convert path to UNIX path
                String path = FilenameUtils.separatorsToUnix(str.trim());
                final Pattern pattern = Pattern.compile("^([a-zA-Z]:/)");
                final Matcher matcher = pattern.matcher(path);
                path = matcher.replaceFirst("/");
                // convert relative paths to absolute paths
                if (!path.startsWith("/")) {
                    path = path.startsWith("~") ? path.replaceFirst("~", System.getProperty("user.home"))
                            : FilenameUtils.concat(System.getProperty("user.dir"), path);
                }
                // normalize path
                path = FilenameUtils.normalize(path, true);
                if (StringUtils.isNotBlank(path)) {
                    url = new File(path).toURI().toURL();
                } else {
                    throw new MalformedURLException("Invalid path: " + path);
                }
            } else {
                throw e;
            }
        }
    }
    return url;
}

From source file:org.jenkinsci.plugins.vssj.VssJournal.java

/**
 * Check if Filename is in Project by comparing if Filename starts with one of the
 * project names. Project names should start with $/
 * @param filename/* w ww .  java2s  .  c o m*/
 * @param list of projects 
 * @return true if filename is in project, otherwise false
 */
protected boolean isFilenameInProject(String filename, String[] projects) {
    if (projects == null)
        return true;
    for (String project : projects) {
        String fn = FilenameUtils.normalize(filename, true);
        String proj = FilenameUtils.normalize(project, true);
        if (fn.trim().startsWith(proj.trim()))
            return true;
    }
    return false;
}

From source file:org.kie.commons.java.nio.base.AbstractPath.java

@Override
public Path toAbsolutePath() throws IOException, SecurityException {
    if (isAbsolute()) {
        return this;
    }//from  w ww. ja  v a 2 s .co m
    if (host.isEmpty()) {
        return newPath(fs, FilenameUtils.normalize(defaultDirectory() + toString(), !usesWindowsFormat), host,
                isRealPath, true);
    }
    return newPath(fs, defaultDirectory() + toString(false), host, isRealPath, true);
}

From source file:org.kie.commons.java.nio.base.AbstractPath.java

@Override
public Path toRealPath(final LinkOption... options) throws IOException, SecurityException {
    if (isRealPath) {
        return this;
    }/* w  ww .  j a  v  a2s  . co m*/
    return newPath(fs, FilenameUtils.normalize(toString(), !usesWindowsFormat), host, true, true);
}

From source file:org.kie.commons.java.nio.base.AbstractPath.java

@Override
public Path normalize() {
    if (isNormalized) {
        return this;
    }/*from   w  ww  . j a v  a  2s .c  o  m*/

    return newPath(fs, FilenameUtils.normalize(new String(path), !usesWindowsFormat), host, isRealPath, true);
}

From source file:org.opensextant.xtext.XText.java

/**
 * Optional API routine. If XText is used as a main program, this is the entry point for extraction/collection.
 * If XText is used as an API, caller may use convertFile() directly without engaging in the setup and assumptions
 * behind this convenience method.//from  w w  w  .j  ava2s  . c om
 * The main entry point to converting compound documents and folders.
 * 
 * @param filepath
 *            item from which we extract text
 * @throws IOException
 *             err
 * @throws ConfigException
 *             err
 */
public void extractText(String filepath) throws IOException, ConfigException {

    start_time = System.currentTimeMillis();

    log.info("Conversion.  INPUT PATH={}", filepath);
    String path = FilenameUtils.normalize(new File(filepath).getAbsolutePath(), true);
    if (path == null) {
        throw new IOException("Failed to normalize the path: " + filepath);
    }

    File input = new File(path);
    if (!input.exists()) {
        throw new IOException("Non existent input FILE=" + path);
    }

    /* Filter on absolute path */
    if (PathManager.isXTextCache(path)) {
        throw new ConfigException("XText cannot be directed to extract text from its own cache files. "
                + "Move the cache files out of ./xtext/ folders if you really need to do this.");
    }

    if (isArchive(input.getName())) {
        // Archive will collect originals to "export"
        // Archive will save conversions to "output"
        // PathManager is STATEFUL for as long as this archive is processing
        // If an archive is uncovered while traversing files, its contents can be dumped to the child export folder.
        convertArchive(input);
    } else if (isPST(input.getName()) && !useTikaPST) {
        this.convertOutlookPST(input);
    } else if (input.isFile()) {
        // If prefix is not set, then conversion will be dumped flatly to output area.
        paths.setInputRoot(input);
        convertFile(input);
    } else if (input.isDirectory()) {
        paths.setInputRoot(input);
        convertFolder(input);
    }

    stop_time = System.currentTimeMillis();

    if (paths.isSaving()) {
        if (paths.isSaveWithInput()) {
            log.info("Output can be accessed at from the input folder {} in 'xtext' sub-folders",
                    input.getParent());
        } else {
            log.info("Output can be accessed at " + paths.getConversionCache());
        }
    }

    reportStatistics();
}