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) 

Source Link

Document

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

Usage

From source file:org.ebayopensource.turmeric.tools.TestResourceUtil.java

/**
 * Copy a test resource into the {@link TestingDir} managed location
 * /* w w  w. ja  v a2s.  co  m*/
 * @param path
 *            the path to the resource (will be reused as the output path in the {@link TestingDir#getDir()} +
 *            testingDirPath)
 * @param testingdir
 *            the test specific testing dir
 * @param testingDirPath
 *            the path within the test specific testing dir to use
 * @return the destination file that was copied
 * @throws IOException
 */
public static File copyResource(String path, TestingDir testingdir, String testingDirPath) throws IOException {
    File destBaseDir = testingdir.getFile(FilenameUtils.separatorsToSystem(testingDirPath));
    MavenTestingUtils.ensureDirExists(destBaseDir);
    File resource = getResource(path);
    String filename = resource.getName();
    String destRelPath = path.substring(0, path.length() - filename.length());
    String destPath = FilenameUtils.normalize(destRelPath + "/" + filename);
    File destFile = new File(destBaseDir, FilenameUtils.separatorsToSystem(destPath));
    FileUtils.copyFile(resource, destFile);
    return destFile;
}

From source file:org.eclipse.skalli.model.ext.maven.internal.MavenResolver.java

/**
 * Concats <code>pathPrefix</code> and <code>path</code>, normalizes the result by
 * removing double and single dot path segments, converts all file separators to forward slashes
 * and removes a leading slash, if any.//from   ww w  .j a va2 s . c  om
 *
 * @param pathPrefix  the path prefix.
 * @param path  the path relative to the path prefix.
 * @return  the bnormalized path, or <code>null</code> of removing double and single dot path
 * segments yielded an invalid path, e.g. a path like <tt>"foo/../../bar"</tt> would be treated
 * as invalid.
 */
private String getNormalizedPath(String pathPrefix, String path) {
    String normalizedPath = FilenameUtils.normalize(pathPrefix + "/" + path); //$NON-NLS-1$
    if (normalizedPath == null) {
        return null;
    }
    normalizedPath = FilenameUtils.separatorsToUnix(normalizedPath);
    if (normalizedPath.charAt(0) == '/') {
        normalizedPath = normalizedPath.substring(1);
    }
    return normalizedPath;
}

From source file:org.exist.http.servlets.HttpRequestWrapper.java

/**
 * @see javax.servlet.http.HttpServletRequest#getParameter(String)
 *///from   w w w . j  ava  2 s  . co m
@Override
public List<String> getUploadedFileName(String name) {
    if (!isFormDataParsed) {
        return null;
    }

    final Object o = params.get(name);
    if (o == null) {
        return null;
    }

    final List<FileItem> items = getFileItem(o);
    final List<String> files = new ArrayList<String>(items.size());
    for (final FileItem item : items) {
        files.add(FilenameUtils.normalize(item.getName()));
    }
    return files;
}

From source file:org.fusesource.mvnplugins.linkchecker.LinkcheckReport.java

private void generateDetailsSection(Locale locale, LinkcheckModel linkcheckModel) {
    getSink().section1();// w  ww.  j  a va2s.  co  m
    getSink().sectionTitle1();
    getSink().text(i18n.getString("sitegen-linkcheck-report", locale, "report.sitegen.linkcheck.detail"));
    getSink().sectionTitle1_();

    getSink().paragraph();
    getSink().rawText(
            i18n.getString("sitegen-linkcheck-report", locale, "report.sitegen.linkcheck.detail.overview"));
    getSink().paragraph_();

    getSink().table();

    // Header
    generateTableHeader(locale, true);

    // Content
    List linkcheckFiles = linkcheckModel.getFiles();
    for (Iterator it = linkcheckFiles.iterator(); it.hasNext();) {
        LinkcheckFile linkcheckFile = (LinkcheckFile) it.next();

        getSink().tableRow();

        getSink().tableCell();
        if (linkcheckFile.getUnsuccessful() == 0) {
            iconValid(locale);
        } else {
            iconError(locale);
        }
        getSink().tableCell_();

        // tableCell( createLinkPatternedText( linkcheckFile.getRelativePath(), "./"
        // + linkcheckFile.getRelativePath() ) );
        getSink().tableCell();
        getSink().link(linkcheckFile.getRelativePath());
        getSink().text(linkcheckFile.getRelativePath());
        getSink().link_();
        getSink().tableCell_();
        getSink().tableCell();
        getSink().text(String.valueOf(linkcheckFile.getNumberOfLinks()));
        getSink().tableCell_();
        getSink().tableCell();
        getSink().text(String.valueOf(linkcheckFile.getNumberOfLinks(LinkcheckFileResult.VALID_LEVEL)));
        getSink().tableCell_();
        getSink().tableCell();
        getSink().text(String.valueOf(linkcheckFile.getNumberOfLinks(LinkcheckFileResult.WARNING_LEVEL)));
        getSink().tableCell_();
        getSink().tableCell();
        getSink().text(String.valueOf(linkcheckFile.getNumberOfLinks(LinkcheckFileResult.ERROR_LEVEL)));
        getSink().tableCell_();

        getSink().tableRow_();

        // Detail error
        if (linkcheckFile.getUnsuccessful() != 0) {
            getSink().tableRow();

            getSink().tableCell();
            getSink().text("");
            getSink().tableCell_();

            // TODO it is due to DOXIA-78
            getSink().rawText("<td colspan=\"5\">");

            getSink().table();

            for (Iterator it2 = linkcheckFile.getResults().iterator(); it2.hasNext();) {
                LinkcheckFileResult linkcheckFileResult = (LinkcheckFileResult) it2.next();

                if (linkcheckFileResult.getStatusLevel() == LinkcheckFileResult.VALID_LEVEL) {
                    continue;
                }

                getSink().tableRow();

                getSink().tableCell();
                if (linkcheckFileResult.getStatusLevel() == LinkcheckFileResult.WARNING_LEVEL) {
                    iconWarning(locale);
                } else if (linkcheckFileResult.getStatusLevel() == LinkcheckFileResult.ERROR_LEVEL) {
                    iconError(locale);
                }
                getSink().tableCell_();

                getSink().tableCell();
                getSink().italic();
                if (linkcheckFileResult.getTarget().startsWith("#")) {
                    getSink().link(linkcheckFile.getRelativePath() + linkcheckFileResult.getTarget());
                } else if (linkcheckFileResult.getTarget().startsWith(".")) {
                    // We need to calculate a correct absolute path here, because target is a relative path
                    String absolutePath = FilenameUtils.getFullPath(linkcheckFile.getRelativePath())
                            + linkcheckFileResult.getTarget();
                    String normalizedPath = FilenameUtils.normalize(absolutePath);
                    if (normalizedPath == null) {
                        normalizedPath = absolutePath;
                    }
                    getSink().link(normalizedPath);
                } else {
                    getSink().link(linkcheckFileResult.getTarget());
                }
                // Show the link as it was written to make it easy for
                // the author to find it in the source document
                getSink().text(linkcheckFileResult.getTarget());
                getSink().link_();
                getSink().text(": ");
                getSink().text(linkcheckFileResult.getErrorMessage());
                getSink().italic_();
                getSink().tableCell_();

                getSink().tableRow_();
            }

            getSink().table_();

            getSink().tableCell_();

            getSink().tableRow_();
        }
    }

    getSink().table_();

    getSink().section1_();
}

From source file:org.geoserver.ftp.GSFTPUserManager.java

/**
 * @param ftpAuthRequest/*from   w w  w  . j  ava  2  s .c om*/
 *            one of {@link org.apache.ftpserver.usermanager.AnonymousAuthentication} or
 *            {@link org.apache.ftpserver.usermanager.UsernamePasswordAuthentication}
 * @throws AuthenticationFailedException
 *             if given an {@code AnonymousAuthentication}, or an invalid/disabled user
 *             credentials
 * @see UserManager#authenticate(Authentication)
 */
public User authenticate(final Authentication ftpAuthRequest) throws AuthenticationFailedException {
    if (!(ftpAuthRequest instanceof UsernamePasswordAuthentication)) {
        throw new AuthenticationFailedException();
    }
    final UsernamePasswordAuthentication upa = (UsernamePasswordAuthentication) ftpAuthRequest;
    final String principal = upa.getUsername();
    final String credentials = upa.getPassword();
    org.springframework.security.core.Authentication gsAuth = new UsernamePasswordAuthenticationToken(principal,
            credentials);
    try {
        gsAuth = authManager.authenticate(gsAuth);
    } catch (org.springframework.security.core.AuthenticationException authEx) {
        throw new AuthenticationFailedException(authEx);
    }

    try {
        // gather the user
        BaseUser user = getUserByName(principal);
        user.setPassword(credentials);
        // is the user enabled?
        if (!user.getEnabled()) {
            throw new AuthenticationFailedException();
        }

        // scary message for admins if the username/password has not
        // been changed
        if (DEFAULT_USER.equals(user.getName()) && DEFAULT_PASSWORD.equals(credentials)) {
            LOGGER.log(Level.SEVERE,
                    "The default admin/password combination has not been "
                            + "modified, this makes the embedded FTP server an "
                            + "open file host for everybody to use!!!");
        }

        final File dataRoot = dataDir.findOrCreateDataRoot();

        // enable only admins and non anonymous users
        boolean isGSAdmin = false;
        for (GrantedAuthority authority : gsAuth.getAuthorities()) {
            final String userRole = authority.getAuthority();
            if (ADMIN_ROLE.equals(userRole)) {
                isGSAdmin = true;
                break;
            }
        }

        final File homeDirectory;
        if (isGSAdmin) {
            homeDirectory = dataRoot;
        } else {
            /*
             * This resolves the user's home directory to data/incoming/<user name> but does not
             * create the directory if it does not already exist. That is left to when the user
             * is authenticated, check the authenticate() method above.
             */
            homeDirectory = new File(new File(dataRoot, "incoming"), user.getName());
        }
        String normalizedPath = homeDirectory.getAbsolutePath();
        normalizedPath = FilenameUtils.normalize(normalizedPath);
        user.setHomeDirectory(normalizedPath);
        if (!homeDirectory.exists()) {
            LOGGER.fine("Creating FTP home directory for user " + user.getName() + " at " + normalizedPath);
            homeDirectory.mkdirs();
        }

        return user;
    } catch (AuthenticationFailedException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.log(Level.INFO, "FTP authentication failure", e);
        throw new AuthenticationFailedException(e);
    }
}

From source file:org.geoserver.restupload.ResumableUploadPathMapper.java

private Boolean canExecute(String itemPath) {
    Boolean canExecute = false;/*w  w  w. j ava 2  s.c o  m*/
    GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class);
    Resource tmpUploadFolder = loader.get(sourcePath);
    if (FilenameUtils.normalize(itemPath).startsWith(FilenameUtils.normalize(tmpUploadFolder.toString()))) {
        canExecute = true;
    }
    return canExecute;
}

From source file:org.geotools.gce.imagecollection.RasterLayerRequest.java

/**
 * Compute this specific request settings all the parameters needed by a
 * visiting {@link RasterLayerResponse} object.
 * /*from  www.  j a  v  a2 s  .  c  o  m*/
 * @throws DataSourceException
 */
private void prepare() throws DataSourceException {
    String path = null;
    if (filter != null) {
        path = parsePath(filter);
    } else {
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("No PATH have been specified through a Filter. Proceeding with default Image");
        }
        if (rasterManager.parent.defaultValues.path == null) {
            imageManager = rasterManager.getDatasetManager(Utils.FAKE_IMAGE_PATH);
            return;
        } else {
            path = rasterManager.parent.defaultValues.path;
        }
    }
    final String storePath = rasterManager.parent.rootPath;

    //First normalization
    path = FilenameUtils.normalize(path);
    if (path.startsWith(storePath)) {
        // Removing the store path prefix from the specified path
        // allow to deal with the case of parentPath = /home/user1/folder1/ and path = /home/user1/folder1/folder3 
        // which comes back to path = folder3
        path = path.substring(storePath.length());
    }
    final String filePath = FilenameUtils.normalize(FilenameUtils.concat(storePath, path));
    if (!filePath.startsWith(storePath)) {
        throw new DataSourceException("Possible attempt to access data outside the coverate store path:\n"
                + "Store Path: " + storePath + "\nSpecified File Path: " + filePath);
    }
    imageManager = rasterManager.getDatasetManager(filePath);

    //
    // DO WE HAVE A REQUESTED AREA?
    //
    // Check if we have something to load by intersecting the
    // requested envelope with the bounds of this data set.
    //
    if (requestedBBox == null) {

        //
        // In case we have nothing to look at we should get the whole
        // coverage
        //
        requestedBBox = imageManager.coverageBBox;
        cropBBox = imageManager.coverageBBox;
        requestedRasterArea = (Rectangle) imageManager.coverageRasterArea.clone();
        destinationRasterArea = (Rectangle) imageManager.coverageRasterArea.clone();
        requestedResolution = imageManager.coverageFullResolution.clone();
        // TODO harmonize the various types of transformations
        requestedGridToWorld = (AffineTransform) imageManager.coverageGridToWorld2D;
        return;
    }

    //
    // Adjust requested bounding box and source region in order to fall
    // within the source coverage
    //
    computeRequestSpatialElements();
}

From source file:org.geotools.gce.imagemosaic.Utils.java

/**
 * @param testingDirectory// w  w  w .  j ava2s.  c om
 * @return
 * @throws IllegalArgumentException
 * @throws IOException
 */
public static String checkDirectory(String testingDirectory, boolean writable) throws IllegalArgumentException {

    File inDir = new File(testingDirectory);
    boolean failure = !inDir.exists() || !inDir.isDirectory() || inDir.isHidden() || !inDir.canRead();
    if (writable) {
        failure |= !inDir.canWrite();
    }
    if (failure) {
        String message = "Unable to create the mosaic\n" + "location is:" + testingDirectory + "\n"
                + "location exists:" + inDir.exists() + "\n" + "location is a directory:" + inDir.isDirectory()
                + "\n" + "location is writable:" + inDir.canWrite() + "\n" + "location is readable:"
                + inDir.canRead() + "\n" + "location is hidden:" + inDir.isHidden() + "\n";
        LOGGER.severe(message);
        throw new IllegalArgumentException(message);
    }
    try {
        testingDirectory = inDir.getCanonicalPath();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
    testingDirectory = FilenameUtils.normalize(testingDirectory);
    if (!testingDirectory.endsWith(File.separator))
        testingDirectory = testingDirectory + File.separator;
    // test to see if things are still good
    inDir = new File(testingDirectory);
    failure = !inDir.exists() || !inDir.isDirectory() || inDir.isHidden() || !inDir.canRead();
    if (writable) {
        failure |= !inDir.canWrite();
    }
    if (failure) {
        String message = "Unable to create the mosaic\n" + "location is:" + testingDirectory + "\n"
                + "location exists:" + inDir.exists() + "\n" + "location is a directory:" + inDir.isDirectory()
                + "\n" + "location is writable:" + inDir.canWrite() + "\n" + "location is readable:"
                + inDir.canRead() + "\n" + "location is hidden:" + inDir.isHidden() + "\n";
        LOGGER.severe(message);
        throw new IllegalArgumentException(message);
    }
    return testingDirectory;
}

From source file:org.gradle.internal.FileUtils.java

/**
 * Normalizes the given file, removing redundant segments like /../. If normalization
 * tries to step beyond the file system root, the root is returned.
 *//*from   w w  w .j  a v  a2 s . co m*/
public static File normalize(File src) {
    String path = src.getAbsolutePath();
    String normalizedPath = FilenameUtils.normalize(path);
    if (normalizedPath != null) {
        return new File(normalizedPath);
    }
    File root = src;
    File parent = root.getParentFile();
    while (parent != null) {
        root = root.getParentFile();
        parent = root.getParentFile();
    }
    return root;
}

From source file:org.jamwiki.parser.image.ImageUtil.java

/**
 * Utility method for building the URL to an uploaded file (NOT the file's
 * topic page).  If the file does not exist then this method will return
 * <code>null</code>./*from   w  w  w .  ja  v a 2 s.  c  o  m*/
 *
 * @param context The servlet context root.
 * @param filename The relative path of the file.  See
 *  {@link org.jamwiki.model.WikiFile#getUrl}.
 * @param forceAbsoluteUrl Set to <code>true</code> if the returned URL should
 *  always be absolute.  By default an absolute URL will only be returned if
 *  the PROP_FILE_SERVER_URL property is not empty and differs from the
 *  PROP_SERVER_URL property.
 * @return The URL to an uploaded file (not the file's topic page) or
 *  <code>null</code> if the file does not exist.
 */
public static String buildImageUrl(String context, String filename, boolean forceAbsoluteUrl) {
    String relativeFileRoot = FilenameUtils.normalize(context + "/" + DEFAULT_RELATIVE_FILE_DIRECTORY);
    if (Environment.getValue(Environment.PROP_FILE_UPLOAD_STORAGE)
            .equals(WikiBase.UPLOAD_STORAGE.DOCROOT.toString())) {
        relativeFileRoot = Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH);
    }
    String url = FilenameUtils.normalize(relativeFileRoot + "/" + filename);
    if (isImagesOnFS()) {
        String fileServerUrl = Environment.getValue(Environment.PROP_FILE_SERVER_URL);
        String absoluteServerUrl = Environment.getValue(Environment.PROP_SERVER_URL);
        if (!StringUtils.isBlank(fileServerUrl)
                && !StringUtils.equalsIgnoreCase(fileServerUrl, absoluteServerUrl)) {
            // file server URL is not the same as server URL, so make the image URL absolute
            url = LinkUtil.normalize(fileServerUrl + url);
        } else if (forceAbsoluteUrl) {
            // caller requested an absolute URL when one would not have otherwise been
            // required, so use the server URL to generate an absolute URL
            url = LinkUtil.normalize(absoluteServerUrl + url);
        }
    }
    return FilenameUtils.separatorsToUnix(url);
}