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.pentaho.platform.repository.RepositoryFilenameUtils.java

/**
 * Normalizes a path, removing double and single dot path steps.
 * <p/>// ww w .  j a  v  a 2 s  .  c om
 * This method normalizes a path to a standard format.
 * <p/>
 * A trailing slash will be retained. A double slash will be merged to a single slash (but UNC names are
 * handled). A single dot path segment will be removed. A double dot will cause that path segment and the one
 * before to be removed. If the double dot has no parent path segment to work with, <code>null</code> is
 * returned.
 * <p/>
 * The output will be the same on both Unix and Windows except for the separator character.
 * 
 * <pre>
 * /foo//               -->   /foo/
 * /foo/./              -->   /foo/
 * /foo/../bar          -->   /bar
 * /foo/../bar/         -->   /bar/
 * /foo/../bar/../baz   -->   /baz
 * //foo//./bar         -->   /foo/bar
 * /../                 -->   null
 * ../foo               -->   null
 * foo/bar/..           -->   foo/
 * foo/../../bar        -->   null
 * foo/../bar           -->   bar
 * </pre>
 * 
 * @param filename
 *          the filename to normalize, null returns null
 * @return the normalized filename, or null if invalid
 */
public static String normalize(final String filename) {
    return FilenameUtils.normalize(filename, true);
}

From source file:org.pepstock.jem.ant.tasks.DataSetManager.java

/**
 * Creates a file wrapper, normalizing the name. That's necessary due to you can write on ANT JCL 
 * both the relative or the absolute file name.
 * /*from   w  w  w  .  j a  v a  2  s.  c  o  m*/
 * @param ds dataset instance
 * @return a file wrapper instance
 * @throws BuildException if dataPath is null, returns ann exception
 */
private static FileWrapper getFile(DataSet ds, String disposition) throws BuildException {
    // gets the data path and checks
    // if dataset name starts
    String dataPath = DataPathsContainer.getInstance().getAbsoluteDataPath(ds.getName());

    File file = null;
    String fileName = null;

    //checks if the Dsname is a absolute file name
    // if absolute path is equals return the file 
    // otherwise checks datapath
    if (dataPath != null) {
        // if name is absolute
        // creates a new FILE object with full pathname 
        file = new File(ds.getName());
        // normalizes using UNIX rules
        fileName = FilenameUtils.normalize(file.getAbsolutePath(), true);
        // extract the short name, taking the string after dataPath
        fileName = StringUtils.substringAfter(fileName, dataPath);
        // removes the first / of the filename
        fileName = fileName.substring(1);

        // we must check if full is correct in disposition NEW (only for new allocation)
        if (Disposition.NEW.equalsIgnoreCase(disposition)) {
            try {
                // checks all paths
                PathsContainer paths = DataPathsContainer.getInstance().getPaths(fileName);
                // creates a file with dataPath as parent, plus file name  
                file = new File(paths.getCurrent().getContent(), fileName);

            } catch (InvalidDatasetNameException e) {
                throw new BuildException(e);
            }
        }
    } else {
        // should be relative
        file = new File(ds.getName());
        // normalizes the full path and checks again with the name
        // if equals means that is absolute because the previuos checks only if it's using the 
        // data paths. here the absolute path IS NOT a data path
        if (FilenameUtils.normalize(file.getAbsolutePath(), true).equalsIgnoreCase(ds.getName())) {
            // normalizes using UNIX rules
            fileName = FilenameUtils.normalize(file.getAbsolutePath(), true);
        } else {
            try {
                // checks all paths
                PathsContainer paths = DataPathsContainer.getInstance().getPaths(ds.getName());
                // is relative!
                // creates a file with dataPath as parent, plus file name  
                file = new File(paths.getCurrent().getContent(), ds.getName());
                // if disposition is not in new allocation and the file with current path doesn't exists,
                // try to use the old path is exist
                if (!Disposition.NEW.equalsIgnoreCase(disposition) && !file.exists()
                        && paths.getOld() != null) {
                    file = new File(paths.getOld().getContent(), ds.getName());
                }
                // normalizes using UNIX rules
                fileName = FilenameUtils.normalize(ds.getName(), true);
            } catch (InvalidDatasetNameException e) {
                throw new BuildException(e);
            }
        }
    }
    return new FileWrapper(file, fileName);
}

From source file:org.pepstock.jem.ant.tasks.utilities.ExecBinaryTask.java

/**
 * Creates a string of executable, normalizing the name. That's necessary due to you can write on ANT JCL 
 * both the relative or the absolute file name.
 * //  w  w w .j  a  v a 2  s .  c om
 * @return a executable string command, normalized
 * @throws BuildException if binaryPath is null, returns an exception
 */
private String normalizeExecutable() throws BuildException {
    // gets the bianry path from the environment
    // variables
    // if binary path is null, exception
    String binaryPath = System.getProperty(ConfigKeys.JEM_BINARY_PATH_NAME);
    if (binaryPath == null) {
        throw new BuildException(AntMessage.JEMA053E.toMessage().getFormattedMessage());
    }

    // normalizes binaryPath using UNIX rules
    binaryPath = FilenameUtils.normalize(binaryPath, true);
    File file = null;

    //checks if the executable is a absolute file name
    // if absolute path is equals return the file 
    // otherwise checks binarypath
    if (executable.startsWith(binaryPath)) {
        // if name is absolute
        // creates a new FILE object with full pathname 
        file = new File(executable);
    } else {
        // should be relative
        file = new File(executable);
        // normalizes the full path and checks again with the name
        // if equals means that is absolute
        if (!FilenameUtils.normalize(file.getAbsolutePath(), true).equalsIgnoreCase(executable)) {
            // is relative!
            // creates a file with dataPath as parent, plus file name  
            file = new File(binaryPath, executable);
        }
    }
    // normalizes using UNIX rules
    return FilenameUtils.normalize(file.getAbsolutePath(), true);
}

From source file:org.pepstock.jem.factories.AbstractFactory.java

/**
 * Utility method to resolve properties used in JCL, like classPath.
 * /*from  w  w  w  .  ja v  a 2 s  .c  om*/
 * @param valueParm value inserted in JCL property
 * @param pathKey kind of path 
 * @return absolute paths for values
 * @throwsException if a substitution exception occurs
 */
public String resolvePathNames(String valueParm, String pathKey) {
    String value = VariableSubstituter.substitute(valueParm, systemProperties);
    String pathSeparator = System.getProperty("path.separator");
    StringBuilder sb = new StringBuilder();
    String[] filesNames = value.split(VALUES_SEPARATOR);
    for (int i = 0; i < filesNames.length; i++) {
        File filePath = getFile(FilenameUtils.normalize(filesNames[i], true), pathKey);
        if (i > 0) {
            sb.append(pathSeparator);
        }
        sb.append(filePath.getAbsolutePath());
    }
    return sb.toString();
}

From source file:org.pepstock.jem.factories.AbstractFactory.java

private File getFile(String fileName, String pathKey) throws BuildException {
    //checks if the filename is a absolute file name
    // if absolute path is equals return the file 
    // otherwise checks path
    File checkFile = new File(fileName);
    String checkFileName = FilenameUtils.normalize(checkFile.getAbsolutePath(), true);
    if (checkFileName.equalsIgnoreCase(fileName)) {
        return checkFile;
    }// w ww.  java 2  s. co m

    // gets the path from the environment
    // variables
    String path = System.getProperty(pathKey);
    if (fileName.startsWith(path)) {
        return new File(fileName);
    }

    // create file object in class path
    return new File(path, fileName);
}

From source file:org.pepstock.jem.jbpm.tasks.DataSetManager.java

/**
 * Creates a file wrapper, normalizing the name. That's necessary due to you can write on JBPM JCL 
 * both the relative or the absolute file name.
 * //from ww w.j  av  a  2 s  .  c  om
 * @param ds dataset instance
 * @return a file wrapper instance
 * @throws JBpmException if dataPath is null, returns JBPM exception
 */
private static FileWrapper getFile(DataSet ds, String disposition) throws JBpmException {
    // gets the data path and checks
    // if dataset name starts
    String dataPath = DataPathsContainer.getInstance().getAbsoluteDataPath(ds.getName());

    File file = null;
    String fileName = null;

    //checks if the Dsname is a absolute file name
    // if absolute path is equals return the file 
    // otherwise checks datapath
    if (dataPath != null) {
        // if name is absolute
        // creates a new FILE object with full pathname 
        file = new File(ds.getName());
        // normalizes using UNIX rules
        fileName = FilenameUtils.normalize(file.getAbsolutePath(), true);
        // extract the short name, taking the string after dataPath
        fileName = StringUtils.substringAfter(fileName, dataPath);
        // removes the first / of the filename
        fileName = fileName.substring(1);

        // we must check if full is correct in disposition NEW (only for new allocation)
        if (Disposition.NEW.equalsIgnoreCase(disposition)) {
            try {
                // checks all paths
                PathsContainer paths = DataPathsContainer.getInstance().getPaths(fileName);
                // creates a file with dataPath as parent, plus file name  
                file = new File(paths.getCurrent().getContent(), fileName);

            } catch (InvalidDatasetNameException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
                new JBpmException(e.getMessageInterface(), e);
            }
        }
    } else {
        // should be relative
        file = new File(ds.getName());
        // normalizes the full path and checks again with the name
        // if equals means that is absolute because the previous checks only if it's using the 
        // data paths. here the absolute path IS NOT a data path
        if (FilenameUtils.normalize(file.getAbsolutePath(), true).equalsIgnoreCase(ds.getName())) {
            // normalizes using UNIX rules
            fileName = FilenameUtils.normalize(file.getAbsolutePath(), true);
        } else {
            try {
                // checks all paths
                PathsContainer paths = DataPathsContainer.getInstance().getPaths(ds.getName());
                // is relative!
                // creates a file with dataPath as parent, plus file name  
                file = new File(paths.getCurrent().getContent(), ds.getName());
                // if disposition is not in new allocation and the file with current path doesn't exists,
                // try to use the old path is exist
                if (!Disposition.NEW.equalsIgnoreCase(disposition) && !file.exists()
                        && paths.getOld() != null) {
                    file = new File(paths.getOld().getContent(), ds.getName());
                }
                // normalizes using UNIX rules
                fileName = FilenameUtils.normalize(ds.getName(), true);
            } catch (InvalidDatasetNameException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
                new JBpmException(e.getMessageInterface(), e);
            }
        }
    }
    return new FileWrapper(file, fileName);
}

From source file:org.pepstock.jem.junit.init.submitters.AbstractSubmitter.java

/**
 * //  w  w  w . j  a va  2  s  .  c o  m
 * @param command
 * @param args
 * @return
 * @throws NodeMessageException
 * @throws IOException
 * @throws InterruptedException
 */
int launch(String command, String[] args) throws NodeMessageException, IOException, InterruptedException {
    String osCommand = null;
    if (SystemUtils.IS_OS_WINDOWS) {
        osCommand = command + ".cmd";
    } else {
        osCommand = command + ".sh";
    }

    Process process = null;
    try {
        File logFile = File.createTempFile("junit", "log");

        String redirect = "> " + FilenameUtils.normalize(logFile.getAbsolutePath(), true) + " 2>&1";
        StringBuilder sb = new StringBuilder(osCommand);
        for (String arg : args) {
            sb.append(" ").append(arg);
        }

        System.err.println(sb.toString());

        sb.append(" ").append(redirect);

        // create a process builder
        ProcessBuilder builder = new ProcessBuilder();
        Shell shell = CurrentPlatform.getInstance().getShell();

        builder.command(shell.getName(), shell.getParameters(), sb.toString());

        // set directory where execute process
        builder.directory(new File(System.getenv("JEM_HOME") + "/bin"));

        // load variable environment from a temporary maps that you can use
        // inside of configure method.
        Map<String, String> env = System.getenv();
        Map<String, String> map = builder.environment();
        for (Map.Entry<String, String> e : env.entrySet()) {
            map.put(e.getKey(), e.getValue());
        }

        // start process and save instance
        process = builder.start();
        // wait for end of job execution
        int rc = process.waitFor();

        FileInputStream fis = new FileInputStream(logFile);
        IOUtils.copy(fis, System.out);
        IOUtils.closeQuietly(fis);
        logFile.delete();
        return rc;

    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:org.pepstock.jem.node.DataPathsManager.java

/**
 * Returns the absolute data path or data path name using file name argument
 * @param fileName file name to use to get info
 * @param names if <code>true</code>, get data path name otherwise absolute data path  
 * @return if names is set to <code>true</code>, get data path name otherwise absolute data path 
 *//*w ww. j a v a 2 s  . c o  m*/
private String retrieveDataPath(String fileName, boolean name) {
    String file = FilenameUtils
            .normalize(fileName.endsWith(File.separator) ? fileName : fileName + File.separator, true);
    for (Path mp : dataPaths.getPaths()) {
        String pathToCheck = FilenameUtils.normalize(
                mp.getContent().endsWith(File.separator) ? mp.getContent() : mp.getContent() + File.separator,
                true);
        if (StringUtils.startsWithIgnoreCase(file, pathToCheck)) {
            return name ? mp.getName() : mp.getContent();
        }
    }
    return null;
}

From source file:org.pepstock.jem.node.DataPathsManager.java

/**
 * Loads data path information on a list
 * @param names if <code>true</code>, loads data path names otherwise absolute data paths 
 * @return if names is set to <code>true</code>, loads data path names otherwise absolute data paths 
 *///from   w  ww. j a v  a  2 s.c o  m
private List<String> loadDataPaths(boolean names) {
    List<String> groups = new LinkedList<String>();
    for (Path mp : dataPaths.getPaths()) {
        groups.add(names ? mp.getName() : FilenameUtils.normalize(mp.getContent(), true));
    }
    return groups;
}

From source file:org.pepstock.jem.node.executors.gfs.GetFilesList.java

@Override
public Collection<GfsFile> getResultForDataPath() throws ExecutorException {
    // checks if a data type and root path request. If yes, having the storage groups manager
    // scans all defined data paths
    // otherwise asks for the specific folder
    if (ROOT_PATH.equalsIgnoreCase(getItem())) {
        // scans all paths defined 
        Collection<GfsFile> list = new LinkedList<GfsFile>();
        for (String path : Main.DATA_PATHS_MANAGER.getDataPaths()) {
            list.addAll(getFilesList(path, new File(path)));
        }// w w  w  . j  a  va2 s .  c om
        return list;
    } else {
        // gets data path from path name
        if (getPathName() != null) {
            String parentPath = Main.DATA_PATHS_MANAGER.getAbsoluteDataPathByName(getPathName());
            File file = new File(parentPath, getItem());
            // return list of files of folder
            return this.getResult(parentPath, file);
        } else {
            // normalize the path
            String item = FilenameUtils.normalize(
                    getItem().endsWith(File.separator) ? getItem() : getItem() + File.separator, true);
            try {
                // gets data path 
                PathsContainer paths = Main.DATA_PATHS_MANAGER.getPaths(item);
                String parentPath = paths.getCurrent().getContent();
                // checks if file exist. If file belongs to old folder
                // returns file from old path
                // otherwise uses the normal path defined in the rules
                File file = new File(parentPath, getItem());
                if (!file.exists() && paths.getOld() != null) {
                    parentPath = paths.getOld().getContent();
                }
                file = new File(parentPath, getItem());
                // checks if folder exists and must be a folder (not a file)
                if (!file.exists()) {
                    throw new ExecutorException(NodeMessage.JEMC186E, getItem());
                }
                // returns list of files
                return this.getResult(parentPath, file);
            } catch (InvalidDatasetNameException e) {
                throw new ExecutorException(e.getMessageInterface(), e, getItem());
            }
        }
    }
}