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:net.sourceforge.pmd.docs.RuleDocGenerator.java

private String getRuleClassSourceFilepath(String ruleClass) throws IOException {
    final String relativeSourceFilename = ruleClass.replaceAll("\\.", Matcher.quoteReplacement(File.separator))
            + ".java";
    final List<Path> foundPathResult = new LinkedList<>();

    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
        @Override/*from   ww  w.ja  v  a 2s .  c om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String path = file.toString();
            if (path.contains("src") && path.endsWith(relativeSourceFilename)) {
                foundPathResult.add(file);
                return FileVisitResult.TERMINATE;
            }
            return super.visitFile(file, attrs);
        }
    });

    if (!foundPathResult.isEmpty()) {
        Path foundPath = foundPathResult.get(0);
        foundPath = root.relativize(foundPath);
        return FilenameUtils.normalize(foundPath.toString(), true);
    }

    return FilenameUtils.normalize(relativeSourceFilename, true);
}

From source file:net.sourceforge.pmd.docs.RuleDocGeneratorTest.java

@Test
public void testSingleRuleset() throws RuleSetNotFoundException, IOException {
    RuleDocGenerator generator = new RuleDocGenerator(writer, root);

    RuleSetFactory rsf = new RuleSetFactory();
    RuleSet ruleset = rsf.createRuleSet("rulesets/ruledoctest/sample.xml");

    generator.generate(Arrays.asList(ruleset).iterator(), Arrays
            .asList("rulesets/ruledoctest/sample-deprecated.xml", "rulesets/ruledoctest/other-ruleset.xml"));

    assertEquals(3, writer.getData().size());
    FileEntry languageIndex = writer.getData().get(0);
    assertTrue(FilenameUtils.normalize(languageIndex.getFilename(), true)
            .endsWith("docs/pages/pmd/rules/java.md"));
    assertEquals(loadResource("/expected/java.md"), languageIndex.getContent());

    FileEntry ruleSetIndex = writer.getData().get(1);
    assertTrue(FilenameUtils.normalize(ruleSetIndex.getFilename(), true)
            .endsWith("docs/pages/pmd/rules/java/sample.md"));
    assertEquals(loadResource("/expected/sample.md"), ruleSetIndex.getContent());

    FileEntry sidebar = writer.getData().get(2);
    assertTrue(FilenameUtils.normalize(sidebar.getFilename(), true)
            .endsWith("docs/_data/sidebars/pmd_sidebar.yml"));
    assertEquals(loadResource("/expected/pmd_sidebar.yml"), sidebar.getContent());
}

From source file:net.sourceforge.pmd.docs.RuleSetUtils.java

public static String getRuleSetClasspath(RuleSet ruleset) {
    final String RESOURCES_PATH = "/resources/";
    String filename = FilenameUtils.normalize(StringUtils.chomp(ruleset.getFileName()), true);
    int startIndex = filename.lastIndexOf(RESOURCES_PATH);
    if (startIndex > -1) {
        return filename.substring(startIndex + RESOURCES_PATH.length());
    } else {/*  w  ww . j a v  a 2 s  . c o  m*/
        return filename;
    }
}

From source file:ninja.AssetsControllerHelper.java

/**
 * If we get - for whatever reason - a relative URL like
 * assets/../conf/application.conf we expand that to the "real" path. In the
 * above case conf/application.conf.//  w ww  .  j  a va2s  . com
 *
 * You should then add the assets prefix.
 *
 * Otherwise someone can create an attack and read all resources of our app.
 * If we expand and normalize the incoming path this is no longer possible.
 *
 * @param fileName A potential "fileName"
 * @param enforceUnixSeparator If true it will force the usage of the unix separator '/'
 *                             If false it will use the separator of the underlying system.
 *                             usually '/' in case of unix and '\' in case of windows.
 * @return A normalized fileName.
 */
public String normalizePathWithoutLeadingSlash(String fileName, boolean enforceUnixSeparator) {
    String fileNameNormalized = enforceUnixSeparator ? FilenameUtils.normalize(fileName, true)
            : FilenameUtils.normalize(fileName);
    return StringUtils.removeStart(fileNameNormalized, "/");
}

From source file:nl.nn.adapterframework.configuration.classloaders.BytesClassLoader.java

public URL getResource(String name, boolean useParent) {
    name = FilenameUtils.normalize(name, true);
    byte[] bytes = resources.get(name);
    if (bytes != null) {
        URLStreamHandler urlStreamHandler = new BytesURLStreamHandler(bytes);
        try {// w  w w.  j  ava 2  s.  com
            return new URL(null, PROTOCOL + ":" + name, urlStreamHandler);
        } catch (MalformedURLException e) {
            log.error("Could not create url", e);
        }
    }
    if (useParent)
        return super.getResource(name);
    else
        return null;
}

From source file:org.alfresco.extension.bulkimport.source.fs.FilesystemSourceUtils.java

/**
 * Returns true if the suspectedChild is within the given directory.  This
 * method is preferred over the File version, as it forces normalisation
 * of the two paths//from ww  w.j a v a2 s.  c o  m
 * (see <a href="http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FilenameUtils.html#normalize(java.lang.String, boolean)">this reference</a>)
 * first.
 * 
 * @param directoryPath      The directory in which to check <i>(may be null, although doing so will always return false)</i>.
 * @param suspectedChildPath The suspect child to check for <i>(may be null, although doing so will always return false)</i>.
 * @return true if and only if suspectedChild is "within" directory.  Note that this comparison is done solely at a "path string"
 *         level.
 */
public final static boolean isInDirectory(final String directoryPath, final String suspectedChildPath) {
    return (isInDirectoryImpl(new File(FilenameUtils.normalize(directoryPath, true)),
            new File(FilenameUtils.normalize(suspectedChildPath, true))));
}

From source file:org.alfresco.extension.bulkimport.source.fs.FilesystemSourceUtils.java

/**
 * This method does the magic of constructing the content URL for
 * "in-place" content.//  ww  w .j a v a  2 s.co  m
 * 
 * @param mimeTypeService The Alfresco MimetypeService <i>(must not be null)</i>.
 * @param contentStore    The content store Alfresco is configured to use <i>(must not be null)</i>.
 * @param contentFile     The content file to build a content URL for <i>(must not be null)</i>.
 * @return The constructed <code>ContentData</code>, or null if the contentFile cannot be in-place imported for any reason.
 */
public final static ContentData buildContentProperty(final MimetypeService mimeTypeService,
        final ContentStore contentStore, final File contentFile) {
    ContentData result = null;

    final String normalisedFilename = FilenameUtils.normalize(contentFile.getAbsolutePath(), true);
    String normalisedContentStoreRoot = FilenameUtils.normalize(contentStore.getRootLocation(), true);

    // Ensure content store root ends with a single / character
    if (!normalisedContentStoreRoot.endsWith("/")) {
        normalisedContentStoreRoot = normalisedContentStoreRoot + "/";
    }

    // If, after normalisation, the filename doesn't start with the content store root, we can't in-place import
    if (normalisedFilename.startsWith(normalisedContentStoreRoot)) {
        final String contentStoreRelativeFilename = normalisedFilename
                .substring(normalisedContentStoreRoot.length());
        final String contentUrl = FileContentStore.STORE_PROTOCOL + ContentStore.PROTOCOL_DELIMITER
                + contentStoreRelativeFilename;

        // If the resulting content URL would be too long, we can't in-place import
        if (contentUrl.length() <= MAX_CONTENT_URL_LENGTH) {
            final String mimeType = mimeTypeService.guessMimetype(contentFile.getName());
            final String encoding = guessEncoding(mimeTypeService, contentFile, mimeType);

            result = new ContentData(contentUrl, mimeType, contentFile.length(), encoding);
        }
    }

    return (result);
}

From source file:org.apache.flex.compiler.config.Configuration.java

/**
 * Get normalized theme file paths. If a the compiler is in
 * "Flex 3 compatibility" mode and only "Spark" theme is used, it will be
 * replaced with the legacy "Halo" theme.
 * // w  ww  .  j  a  v a 2s  . c o  m
 * @return A list of normalized paths to the theme files.
 */
public List<String> getCompilerThemeFiles() {
    if (themeFiles == null)
        return EMPTY_STRING_LIST;

    final boolean isVersion3OrEarlier = getCompilerMxmlCompatibilityVersion() <= MXML_VERSION_3_0;
    final boolean hasOnlyOneThemeFile = themeFiles.size() == 1;
    if (isVersion3OrEarlier && hasOnlyOneThemeFile) {
        // Swap in the default Flex 3 theme of Halo.
        final String path = FilenameUtils.normalize(themeFiles.get(0), true);
        final String sparkPath = "/themes/Spark/spark.css";

        if (path.endsWith(sparkPath)) {
            int index = path.indexOf(sparkPath);
            final String haloPath = path.substring(0, index) + "/themes/Halo/halo.swc";
            themeFiles.set(0, FilenameNormalization.normalize(haloPath));
        }
    }
    return themeFiles;
}

From source file:org.apache.sling.scripting.sightly.impl.engine.extension.URIManipulationFilterExtension.java

@Override
@SuppressWarnings("unchecked")
public Object call(RenderContext renderContext, Object... arguments) {
    ExtensionUtils.checkArgumentCount(RuntimeFunction.URI_MANIPULATION, arguments, 2);
    RuntimeObjectModel runtimeObjectModel = renderContext.getObjectModel();
    String uriString = runtimeObjectModel.toString(arguments[0]);
    Map<String, Object> options = runtimeObjectModel.toMap(arguments[1]);
    StringBuilder sb = new StringBuilder();
    PathInfo pathInfo = new PathInfo(uriString);
    uriAppender(sb, SCHEME, options, pathInfo.getScheme());
    if (sb.length() > 0) {
        sb.append(":");
        sb.append(StringUtils.defaultIfEmpty(pathInfo.getBeginPathSeparator(), "//"));
    }/*  ww w .j  a v a 2 s  .c o  m*/
    if (sb.length() > 0) {
        uriAppender(sb, DOMAIN, options, pathInfo.getHost());
    } else {
        String domain = getOption(DOMAIN, options, pathInfo.getHost());
        if (StringUtils.isNotEmpty(domain)) {
            sb.append("//").append(domain);
        }
    }
    if (pathInfo.getPort() > -1) {
        sb.append(":").append(pathInfo.getPort());
    }
    String prependPath = getOption(PREPEND_PATH, options, StringUtils.EMPTY);
    if (prependPath == null) {
        prependPath = StringUtils.EMPTY;
    }
    String path = getOption(PATH, options, pathInfo.getPath());
    if (StringUtils.isEmpty(path)) {
        // if the path is forced to be empty don't remove the path
        path = pathInfo.getPath();
    }
    if (StringUtils.isNotEmpty(path) && !"/".equals(path)) {
        if (StringUtils.isNotEmpty(prependPath)) {
            if (sb.length() > 0 && !prependPath.startsWith("/")) {
                prependPath = "/" + prependPath;
            }
            if (!prependPath.endsWith("/")) {
                prependPath += "/";
            }
        }

        String appendPath = getOption(APPEND_PATH, options, StringUtils.EMPTY);
        if (appendPath == null) {
            appendPath = StringUtils.EMPTY;
        }
        if (StringUtils.isNotEmpty(appendPath)) {
            if (!appendPath.startsWith("/")) {
                appendPath = "/" + appendPath;
            }
        }
        String newPath;
        try {
            newPath = new URI(prependPath + path + appendPath).normalize().getPath();
        } catch (URISyntaxException e) {
            newPath = prependPath + path + appendPath;
        }
        if (sb.length() > 0 && sb.lastIndexOf("/") != sb.length() - 1 && StringUtils.isNotEmpty(newPath)
                && !newPath.startsWith("/")) {
            sb.append("/");
        }
        sb.append(newPath);
        Set<String> selectors = pathInfo.getSelectors();
        handleSelectors(runtimeObjectModel, selectors, options);
        for (String selector : selectors) {
            if (StringUtils.isNotBlank(selector) && !selector.contains(" ")) {
                // make sure not to append empty or invalid selectors
                sb.append(".").append(selector);
            }
        }
        String extension = getOption(EXTENSION, options, pathInfo.getExtension());
        if (StringUtils.isNotEmpty(extension)) {
            sb.append(".").append(extension);
        }

        String prependSuffix = getOption(PREPEND_SUFFIX, options, StringUtils.EMPTY);
        if (StringUtils.isNotEmpty(prependSuffix)) {
            if (!prependSuffix.startsWith("/")) {
                prependSuffix = "/" + prependSuffix;
            }
            if (!prependSuffix.endsWith("/")) {
                prependSuffix += "/";
            }
        }
        String pathInfoSuffix = pathInfo.getSuffix();
        String suffix = getOption(SUFFIX, options, pathInfoSuffix == null ? StringUtils.EMPTY : pathInfoSuffix);
        if (suffix == null) {
            suffix = StringUtils.EMPTY;
        }
        String appendSuffix = getOption(APPEND_SUFFIX, options, StringUtils.EMPTY);
        if (StringUtils.isNotEmpty(appendSuffix)) {
            appendSuffix = "/" + appendSuffix;
        }
        String newSuffix = FilenameUtils.normalize(prependSuffix + suffix + appendSuffix, true);
        if (StringUtils.isNotEmpty(newSuffix)) {
            if (!newSuffix.startsWith("/")) {
                sb.append("/");
            }
            sb.append(newSuffix);
        }

    } else if ("/".equals(path)) {
        sb.append(path);
    }
    Map<String, Collection<String>> parameters = pathInfo.getParameters();
    handleParameters(runtimeObjectModel, parameters, options);
    if (sb.length() > 0 && !parameters.isEmpty()) {
        if (StringUtils.isEmpty(path)) {
            sb.append("/");
        }
        sb.append("?");
        for (Map.Entry<String, Collection<String>> entry : parameters.entrySet()) {
            for (String value : entry.getValue()) {
                sb.append(entry.getKey()).append("=").append(value).append("&");
            }
        }
        // delete the last &
        sb.deleteCharAt(sb.length() - 1);
    }
    String fragment = getOption(FRAGMENT, options, pathInfo.getFragment());
    if (StringUtils.isNotEmpty(fragment)) {
        sb.append("#").append(fragment);
    }
    return sb.toString();
}

From source file:org.apache.zookeeper.server.quorum.auth.QuorumKerberosHostBasedAuthTest.java

private static void setupJaasConfigEntries(String hostServerPrincipal, String hostLearnerPrincipal,
        String hostNamedLearnerPrincipal) {
    String keytabFilePath = FilenameUtils.normalize(KerberosTestUtils.getKeytabFile(), true);
    String jaasEntries = new String("" + "QuorumServer {\n"
            + "       com.sun.security.auth.module.Krb5LoginModule required\n" + "       useKeyTab=true\n"
            + "       keyTab=\"" + keytabFilePath + "\"\n" + "       storeKey=true\n"
            + "       useTicketCache=false\n" + "       debug=false\n" + "       principal=\""
            + KerberosTestUtils.replaceHostPattern(hostServerPrincipal) + "\";\n" + "};\n" + "QuorumLearner {\n"
            + "       com.sun.security.auth.module.Krb5LoginModule required\n" + "       useKeyTab=true\n"
            + "       keyTab=\"" + keytabFilePath + "\"\n" + "       storeKey=true\n"
            + "       useTicketCache=false\n" + "       debug=false\n" + "       principal=\""
            + KerberosTestUtils.replaceHostPattern(hostLearnerPrincipal) + "\";\n" + "};\n"
            + "QuorumLearnerMyHost {\n" + "       com.sun.security.auth.module.Krb5LoginModule required\n"
            + "       useKeyTab=true\n" + "       keyTab=\"" + keytabFilePath + "\"\n"
            + "       storeKey=true\n" + "       useTicketCache=false\n" + "       debug=false\n"
            + "       principal=\"" + hostNamedLearnerPrincipal + "\";\n" + "};\n");
    setupJaasConfig(jaasEntries);//  ww w.  ja  va  2 s  . c o m
}