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:com.abiquo.appliancemanager.web.servlet.CheckServlet.java

public synchronized boolean checkRepositoryMounted() {
    final String repositoryLocation = FilenameUtils
            .normalizeNoEndSeparator(AMConfiguration.getRepositoryLocation());
    final String repositoryMountPoint = FilenameUtils
            .normalizeNoEndSeparator(AMConfiguration.getRepositoryPath());

    if (repositoryLocation.startsWith("localhost") || repositoryLocation.startsWith("127.0.0.1")) {
        LOGGER.warn("Cannot validate ''abiquo.appliancemanager.repositoryLocation'' {}."
                + " It is a local repository", repositoryLocation);
        return true;
    }/*from w w w.  j ava 2 s . com*/

    final File mountFile = new File(MOUNT_FILE);
    BufferedReader mountReader = null;
    try {
        mountReader = new BufferedReader(new FileReader(mountFile));

        for (String line = mountReader.readLine(); line != null; line = mountReader.readLine()) {
            if (line.contains(repositoryLocation)) {
                final String[] parts = line.split(" ");
                if (repositoryLocation.equals(FilenameUtils.normalizeNoEndSeparator(parts[0]))
                        && repositoryMountPoint
                                .equalsIgnoreCase(FilenameUtils.normalizeNoEndSeparator(parts[1]))) {
                    return true;
                } else {
                    LOGGER.warn(
                            "Repository location {} present but not mounted on the expected path {} \n" + line,
                            repositoryLocation, repositoryMountPoint);
                }
            }
        }

        return false;
    } catch (final FileNotFoundException e) {
        throw new AMException(AMError.MOUNT_FILE_NOT_FOUND, e);
    } catch (final IOException e) {
        throw new AMException(AMError.MOUNT_FILE_READ_ERROR, e);
    } finally {
        if (mountReader != null) {
            try {
                mountReader.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:hu.bme.mit.sette.common.descriptors.java.JavaSourceFile.java

/**
 * Creates an instance of the {@link JavaSourceFile} object by using the
 * specified source and binary directories and the specified source file.
 *
 * @param pSourceDirectory/*ww w  . j  a va  2s .co m*/
 *            the source directory (e.g. /path/to/project/src)
 * @param pSourceFile
 *            the source file (e.g.
 *            /path/to/project/src/hu/bme/mit/sette/MyClass.java)
 * @param classLoader
 *            the class loader to be used to load the class
 * @return A {@link JavaSourceFile} object representing the Java file.
 * @throws SetteConfigurationException
 *             If an error occurred, e.g. not enough permissions to access
 *             the directory or the file, cannot retrieve canonical file
 *             names, file is in the specified directory or cannot load the
 *             Java class contained by the file.
 */
public static JavaSourceFile fromFile(final File pSourceDirectory, final File pSourceFile,
        final ClassLoader classLoader) throws SetteConfigurationException {
    Validate.notNull(pSourceDirectory, "The source directory must not be null");
    Validate.notNull(pSourceFile, "The source file must not be null");
    Validate.notNull(classLoader, "The class loader must not be null");

    try {
        // validate permissions
        GeneralValidator v = new GeneralValidator(JavaSourceFile.class);

        FileValidator v1 = new FileValidator(pSourceDirectory);
        v1.type(FileType.DIRECTORY).readable(true).executable(true);
        v.addChildIfInvalid(v1);

        FileValidator v2 = new FileValidator(pSourceFile);
        v2.type(FileType.REGULAR_FILE).readable(true);
        v2.extension(JavaFileUtils.JAVA_SOURCE_EXTENSION);
        v.addChildIfInvalid(v2);

        v.validate();

        // get canonical file objects
        File sourceDirectory = pSourceDirectory.getCanonicalFile();
        File sourceFile = pSourceFile.getCanonicalFile();

        // get paths
        // like "/path/to/project/src"
        String sourceDirectoryPath = FilenameUtils.normalizeNoEndSeparator(sourceDirectory.getAbsolutePath());
        // like "/path/to/project/src/pkg/path/here/MyClass.java"
        String sourceFilePath = FilenameUtils.normalizeNoEndSeparator(sourceFile.getAbsolutePath());

        // check whether the file is under the specified directory
        if (FilenameUtils.directoryContains(sourceDirectoryPath, sourceFilePath)) {
            // get relative path and class name
            // like "pkg/path/here/MyClass.java"
            String classPath = sourceFilePath.substring(sourceDirectoryPath.length() + 1);

            // like "pkg.path.here.MyClass"
            String className = JavaFileUtils.filenameToClassName(classPath);

            // load class
            Class<?> javaClass = classLoader.loadClass(className);

            // create object and return with it
            return new JavaSourceFile(sourceFile, javaClass);
        } else {
            String message = String.format("The source file is not in the " + "source directory\n"
                    + "(sourceDirectory: [%s])\n(sourceFile: [%s])", sourceDirectory, sourceFile);
            throw new SetteConfigurationException(message);
        }
    } catch (ValidatorException e) {
        throw new SetteConfigurationException("A validation exception occurred", e);
    } catch (IOException e) {
        throw new SetteConfigurationException("An IO exception occurred", e);
    } catch (ClassNotFoundException e) {
        throw new SetteConfigurationException("The Java class could not have been loaded", e);
    }
}

From source file:com.sap.prd.mobile.ios.mios.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
 * '\'.//w w  w . ja va  2  s  . c  om
 * 
 * Copied from http://stackoverflow.com/a/3054692/933106.
 * 
 * @param target
 *          targetPath is calculated to this file
 * @param base
 *          basePath is calculated from this file
 * @param separator
 *          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.
    StringBuilder common = new StringBuilder();

    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;
    }

    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(".." + pathSeparator);
        }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
}

From source file:de.mpg.imeji.presentation.servlet.DigilibServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    PropertyBean propBean = new PropertyBean();
    if (propBean.isDigilibEnabled()) {
        try {/*w  w w. j  av  a 2s . c o m*/
            authorization = new Authorization();
            navigation = new Navigation();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        storageController = new StorageController();
        InternalStorageManager ism = new InternalStorageManager();
        internalStorageBase = FilenameUtils
                .getBaseName(FilenameUtils.normalizeNoEndSeparator(ism.getStoragePath()));
        // Copy the digilib-config.xml before initialising the digilib servlet, which needs this file
        copyFile(getDigilibConfigPath(), config.getServletContext().getRealPath("/WEB-INF"));
        super.init(config);
    } else {
        logger.info("Digilib Viewer is disabled.");
    }
}

From source file:edu.umn.msi.tropix.webgui.server.ExportServiceImpl.java

@ServiceMethod()
public void export(final String[] ids, final GridFtpServerOptions gridFtpOptions) {
    final TropixFile[] tropixFiles = fileService.getFiles(userSession.getGridId(), ids);
    final String host = gridFtpOptions.getHostname();
    final int port = gridFtpOptions.getPort();
    final Credential credential = userSession.getProxy();
    LOG.info("GridFTP request to host and port " + host + " " + port);
    final GridFtpClient gridFtpClient = gridFtpFactory.getClient(host, port, credential);

    final String path = FilenameUtils.normalizeNoEndSeparator(gridFtpOptions.getPath());
    try {// www .  j  av  a2s .  com
        LOG.debug("Attempting to create path " + path);
        gridFtpClient.makeDir(path);
    } catch (final RuntimeException e) {
        LOG.warn("Failed to make directory with path " + path
                + " proceeding anyway in case directory already exists.", e);
    }
    for (final TropixFile tropixFile : tropixFiles) {
        final StorageData data = storageDataFactory.getStorageData(tropixFile, credential);
        final String name = FilenameUtils.getBaseName(tropixFile.getName());
        LOG.debug("Attempting to transfer file wit id " + tropixFile.getFileId() + " and name " + name);
        data.getDownloadContext().get(GridFtpClientUtils.getOutputContext(gridFtpClient, path + "/" + name));
    }
}

From source file:de.mpg.imeji.presentation.beans.PropertyBean.java

/**
 * @return the internalStorageBase//www.ja  va2  s. c  o  m
 * @throws URISyntaxException
 * @throws IOException
 */
public String getInternalStorageBase() throws IOException, URISyntaxException {
    this.internalStorageBase = FilenameUtils.getBaseName(
            FilenameUtils.normalizeNoEndSeparator(PropertyReader.getProperty("imeji.storage.path")));
    return internalStorageBase;
}

From source file:com.apporiented.hermesftp.cmd.AbstractFtpCmd.java

/**
 * Returns the absolute path of the passed rel. path.
 * /* www  .ja  v a2  s  .  c o m*/
 * @param path The relative path;
 * @return The absolute path
 */
protected String getAbsPath(String path) {
    String result;
    try {
        path = FilenameUtils.normalizeNoEndSeparator(path);
        if (path.startsWith(File.separator)) {
            result = new File(getCtx().getOptions().getRootDir(), path.substring(1)).getCanonicalPath();
        } else {
            result = new File(getCtx().getRemoteDir(), path).getCanonicalPath();
        }
    } catch (IOException e) {
        result = getCtx().getRemoteDir();
        log.error(e);
    }
    return result;
}

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. j av  a 2  s . com*/
 * @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:cn.guoyukun.spring.web.upload.FileUploadUtils.java

private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException {

    uploadDir = FilenameUtils.normalizeNoEndSeparator(uploadDir);

    File desc = new File(uploadDir + File.separator + filename);

    if (!desc.getParentFile().exists()) {
        desc.getParentFile().mkdirs();/*from w  ww .  j  ava 2 s  . c  om*/
    }
    if (!desc.exists()) {
        desc.createNewFile();
    }
    return desc;
}

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;
}