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.apache.archiva.webdav.ArchivaDavResourceFactory.java

private DavResource getResourceFromGroup(DavServletRequest request, List<String> repositories,
        ArchivaDavResourceLocator locator, RepositoryGroupConfiguration repositoryGroupConfiguration)
        throws DavException, RepositoryAdminException {
    if (repositoryGroupConfiguration.getRepositories() == null
            || repositoryGroupConfiguration.getRepositories().isEmpty()) {
        File file = new File(System.getProperty("appserver.base"),
                "groups/" + repositoryGroupConfiguration.getId());

        return new ArchivaDavResource(file.getPath(), "groups/" + repositoryGroupConfiguration.getId(), null,
                request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler, fileLockManager);
    }//  ww  w .  j av  a  2s .c o  m
    List<File> mergedRepositoryContents = new ArrayList<>();
    // multiple repo types so we guess they are all the same type
    // so use the first one
    // FIXME add a method with group in the repository storage
    String firstRepoId = repositoryGroupConfiguration.getRepositories().get(0);

    String path = getLogicalResource(locator, managedRepositoryAdmin.getManagedRepository(firstRepoId), false);
    if (path.startsWith("/")) {
        path = path.substring(1);
    }
    LogicalResource logicalResource = new LogicalResource(path);

    // flow:
    // if the current user logged in has permission to any of the repositories, allow user to
    // browse the repo group but displaying only the repositories which the user has permission to access.
    // otherwise, prompt for authentication.

    String activePrincipal = getActivePrincipal(request);

    boolean allow = isAllowedToContinue(request, repositories, activePrincipal);

    // remove last /
    String pathInfo = StringUtils.removeEnd(request.getPathInfo(), "/");

    if (allow) {

        if (StringUtils.endsWith(pathInfo, repositoryGroupConfiguration.getMergedIndexPath())) {
            File mergedRepoDir = buildMergedIndexDirectory(repositories, activePrincipal, request,
                    repositoryGroupConfiguration);
            mergedRepositoryContents.add(mergedRepoDir);
        } else {
            if (StringUtils.equalsIgnoreCase(pathInfo, "/" + repositoryGroupConfiguration.getId())) {
                File tmpDirectory = new File(SystemUtils.getJavaIoTmpDir(), repositoryGroupConfiguration.getId()
                        + "/" + repositoryGroupConfiguration.getMergedIndexPath());
                if (!tmpDirectory.exists()) {
                    synchronized (tmpDirectory.getAbsolutePath()) {
                        if (!tmpDirectory.exists()) {
                            tmpDirectory.mkdirs();
                        }
                    }
                }
                mergedRepositoryContents.add(tmpDirectory.getParentFile());
            }
            for (String repository : repositories) {
                ManagedRepositoryContent managedRepository = null;

                try {
                    managedRepository = repositoryFactory.getManagedRepositoryContent(repository);
                } catch (RepositoryNotFoundException e) {
                    throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Invalid managed repository <" + repository + ">: " + e.getMessage());
                } catch (RepositoryException e) {
                    throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Invalid managed repository <" + repository + ">: " + e.getMessage());
                }

                File resourceFile = new File(managedRepository.getRepoRoot(), logicalResource.getPath());
                if (resourceFile.exists()) {
                    // in case of group displaying index directory doesn't have sense !!
                    String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
                    if (StringUtils.isNotEmpty(repoIndexDirectory)) {
                        if (!new File(repoIndexDirectory).isAbsolute()) {
                            repoIndexDirectory = new File(managedRepository.getRepository().getLocation(),
                                    StringUtils.isEmpty(repoIndexDirectory) ? ".indexer" : repoIndexDirectory)
                                            .getAbsolutePath();
                        }
                    }
                    if (StringUtils.isEmpty(repoIndexDirectory)) {
                        repoIndexDirectory = new File(managedRepository.getRepository().getLocation(),
                                ".indexer").getAbsolutePath();
                    }

                    if (!StringUtils.equals(FilenameUtils.normalize(repoIndexDirectory),
                            FilenameUtils.normalize(resourceFile.getAbsolutePath()))) {
                        // for prompted authentication
                        if (httpAuth.getSecuritySession(request.getSession(true)) != null) {
                            try {
                                if (isAuthorized(request, repository)) {
                                    mergedRepositoryContents.add(resourceFile);
                                    log.debug("Repository '{}' accessed by '{}'", repository, activePrincipal);
                                }
                            } catch (DavException e) {
                                // TODO: review exception handling

                                log.debug("Skipping repository '{}' for user '{}': {}", managedRepository,
                                        activePrincipal, e.getMessage());

                            }

                        } else {
                            // for the current user logged in
                            try {
                                if (servletAuth.isAuthorized(activePrincipal, repository,
                                        WebdavMethodUtil.getMethodPermission(request.getMethod()))) {
                                    mergedRepositoryContents.add(resourceFile);
                                    log.debug("Repository '{}' accessed by '{}'", repository, activePrincipal);
                                }
                            } catch (UnauthorizedException e) {
                                // TODO: review exception handling

                                log.debug("Skipping repository '{}' for user '{}': {}", managedRepository,
                                        activePrincipal, e.getMessage());

                            }
                        }
                    }
                }
            }
        }
    } else {
        throw new UnauthorizedDavException(locator.getRepositoryId(), "User not authorized.");
    }

    ArchivaVirtualDavResource resource = new ArchivaVirtualDavResource(mergedRepositoryContents,
            logicalResource.getPath(), mimeTypes, locator, this);

    // compatibility with MRM-440 to ensure browsing the repository group works ok
    if (resource.isCollection() && !request.getRequestURI().endsWith("/")) {
        throw new BrowserRedirectException(resource.getHref());
    }

    return resource;
}

From source file:org.apache.flex.utils.FilenameNormalization.java

/**
 * Normalize a {@link File}.  This method normalizes the case of the file path
 * characters and then calls {@link FilenameUtils#normalize(String)}.
 * @see FilenameUtils#normalize(String)/*from   ww  w.  ja v  a  2  s  .com*/
 * @param f A file.
 * @return The normalized File.
 */
public static File normalize(File f) {
    String caseNormalizedAbsPath = f.getAbsolutePath();
    return new File(FilenameUtils.normalize(caseNormalizedAbsPath));
}

From source file:org.apache.flex.utils.FilenameNormalization.java

/**
 * Normalize a {@link String}. This method normalizes the case of the file
 * path characters and then calls {@link FilenameUtils#normalize(String)}.
 * //from   w w w.  j  ava  2  s .com
 * @see FilenameUtils#normalize(String)
 * @param path The fiel path.
 * @return The normalized String. If the given path is already normalized,
 * the original string object will be returned.
 */
public static String normalize(String path) {
    File f = new File(path);
    String caseNormalizedAbsPath = f.getAbsolutePath();
    String normalized = FilenameUtils.normalize(caseNormalizedAbsPath);

    if (normalized == null)
        return path;

    // If the path is already normalized, return the original string object
    // to prevent duplicated string objects.
    if (normalized.equals(path))
        return path;
    else
        return normalized;
}

From source file:org.apache.gora.cassandra.compiler.GoraCassandraNativeCompiler.java

/**
 * Starts the java generated class file/*  w  w w.jav  a 2 s  .  c om*/
 *
 * @param name Class name
 * @throws IOException
 */
private void startFile(String name, String packageName) throws IOException {
    String fullDest = FilenameUtils.normalize(
            dest.getAbsolutePath() + File.separatorChar + packageName.replace('.', File.separatorChar));
    File dir = new File(fullDest);
    if (!dir.exists())
        if (!dir.mkdirs())
            throw new IOException("Unable to create " + dir);
    name = cap(name) + ".java";
    out = new OutputStreamWriter(new FileOutputStream(new File(dir, name)), Charset.defaultCharset());
}

From source file:org.apache.gora.dynamodb.compiler.GoraDynamoDBCompiler.java

/**
 * Starts the java generated class file//from  w w w  .j a  va 2  s .  c  om
 *
 * @param name  Class name
 * @param space spacing
 * @throws IOException
 */
private void startFile(String name, String space) throws IOException {
    String fullDest = FilenameUtils.normalize(
            dest.getAbsolutePath() + File.separatorChar + packageName.replace('.', File.separatorChar));
    File dir = new File(fullDest);
    if (!dir.exists())
        if (!dir.mkdirs())
            throw new IOException("Unable to create " + dir);
    name = cap(name) + ".java";
    out = new OutputStreamWriter(new FileOutputStream(new File(dir, name)), Charset.defaultCharset());

}

From source file:org.apache.maven.doxia.tools.DefaultSiteTool.java

/**
 * @param path could be null./*ww  w .ja va 2  s. c  om*/
 * @return the path normalized, i.e. by eliminating "/../" and "/./" in the path.
 * @see FilenameUtils#normalize(String)
 */
protected static String getNormalizedPath(String path) {
    String normalized = FilenameUtils.normalize(path);
    if (normalized == null) {
        normalized = path;
    }
    return (normalized == null) ? null : normalized.replace('\\', '/');
}

From source file:org.apache.maven.plugins.linkcheck.LinkcheckReportGenerator.java

private void generateDetailsSection(Locale locale, LinkcheckModel linkcheckModel, Sink sink) {
    sink.section1();/*from  ww  w .ja v a  2s.c om*/
    sink.sectionTitle1();
    sink.text(i18n.getString("linkcheck-report", locale, "report.linkcheck.detail"));
    sink.sectionTitle1_();

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

    sink.table();

    // Header
    generateTableHeader(locale, true, sink);

    // Content
    List linkcheckFiles = linkcheckModel.getFiles();
    for (Object linkcheckFile1 : linkcheckFiles) {
        LinkcheckFile linkcheckFile = (LinkcheckFile) linkcheckFile1;

        sink.tableRow();

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

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

        sink.tableRow_();

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

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

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

            sink.table();

            for (Object o : linkcheckFile.getResults()) {
                LinkcheckFileResult linkcheckFileResult = (LinkcheckFileResult) o;

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

                sink.tableRow();

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

                sink.tableCell();
                sink.italic();
                if (linkcheckFileResult.getTarget().startsWith("#")) {
                    sink.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;
                    }
                    sink.link(normalizedPath);
                } else {
                    sink.link(linkcheckFileResult.getTarget());
                }
                // Show the link as it was written to make it easy for
                // the author to find it in the source document
                sink.text(linkcheckFileResult.getTarget());
                sink.link_();
                sink.text(": ");
                sink.text(linkcheckFileResult.getErrorMessage());
                sink.italic_();
                sink.tableCell_();

                sink.tableRow_();
            }

            sink.table_();

            sink.tableCell_();

            sink.tableRow_();
        }
    }

    sink.table_();

    sink.section1_();
}

From source file:org.apache.maven.shared.release.util.ReleaseUtil.java

public static int getBaseWorkingDirectoryParentCount(String basedir, String workingDirectory) {
    int num = 0;//from   w  ww  . j  a  v a 2  s  .  c  o m

    // we can safely assume case-insensitivity as we are just backtracking, not comparing. This helps with issues
    // on Windows with C: vs c:
    workingDirectory = FilenameUtils.normalize(workingDirectory.toLowerCase(Locale.ENGLISH));
    basedir = FilenameUtils.normalize(basedir.toLowerCase(Locale.ENGLISH));

    // MRELEASE-663
    // For Windows is does matter if basedir ends with a file-separator or not to be able to compare.
    // Using the parent of a dummy file makes it possible to compare them OS-independent
    File workingDirectoryFile = new File(workingDirectory, ".tmp").getParentFile();
    File basedirFile = new File(basedir, ".tmp").getParentFile();

    if (!workingDirectoryFile.equals(basedirFile) && workingDirectory.startsWith(basedir)) {
        do {
            workingDirectoryFile = workingDirectoryFile.getParentFile();
            num++;
        } while (!workingDirectoryFile.equals(basedirFile));
    }
    return num;
}

From source file:org.apache.rya.api.path.PathUtils.java

/**
 * Cleans the path to prevent path manipulation. It performs the following:
 * <ul>/* w ww .  j  a v a  2  s  .  c o m*/
 *   <li>Normalizes a path, removing double and single dot path steps.</li>
 *   <li>Ensures path is not in shared directory.</li>
 * </ul>
 * @param filename the filename to clean.
 * @return the cleansed path.
 * @throws IllegalArgumentException if file is in a shared directory.
 */
public static String clean(final String filename) throws IllegalArgumentException {
    if (filename != null) {
        final String clean = FilenameUtils.normalize(filename);
        if (!isInSecureDir(clean)) {
            throw new IllegalArgumentException(
                    "Operation of a file in a shared directory is not allowed: " + filename);
        }
        return clean;
    }
    return null;
}

From source file:org.apache.synapse.deployers.ClassMediatorDeployer.java

/**
 * This will be called when there is a change in the specified deployment
 * folder (in the axis2.xml) and this will register class loader into the deployement store
 *
 * @param deploymentFileData - describes the updated file
 * @throws DeploymentException - in case an error on the deployment
 *///from  www  . ja  v a  2  s.  com
public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {

    String mediatorPath = FilenameUtils.normalize(deploymentFileData.getAbsolutePath());

    log.info("Deploying Class mediators from file : " + mediatorPath);
    ClassLoader mediatorLoader = Utils.getClassLoader(ClassMediatorDeployer.class.getClassLoader(),
            mediatorPath, false);
    getDeploymentStore().addClassMediatorClassLoader(mediatorPath, mediatorLoader);

}