JCRVLT-389 fix prefix handling for filtering

git-svn-id: https://svn.apache.org/repos/asf/jackrabbit/commons/filevault-package-maven-plugin/trunk@1872191 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/AbstractMetadataPackageMojo.java b/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/AbstractMetadataPackageMojo.java
index e67214f..091d426 100644
--- a/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/AbstractMetadataPackageMojo.java
+++ b/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/AbstractMetadataPackageMojo.java
@@ -110,7 +110,7 @@
 
     /**
      * Sets the map of embedded files as project properties as a helper to pass data between the goals
-     * @param embeddedFiles map of embedded files.
+     * @param embeddedFiles map of embedded files (key=destination file name, value = source file)
      */
     @SuppressWarnings("unchecked")
     void setEmbeddedFilesMap(Map<String, File> embeddedFiles) {
@@ -119,7 +119,7 @@
 
     /**
      * Reads the map of embedded files from the project properties. This is a helper to pass data between the goals.
-     * @return the map of embedded files.
+     * @return the map of embedded files (key=destination file name, value = source file)
      */
     @SuppressWarnings("unchecked")
     Map<String, File> getEmbeddedFilesMap() {
@@ -166,6 +166,7 @@
         }
         return metaInfDirectory;
     }
+
     Filters loadGeneratedFilterFile() throws IOException, ConfigurationException {
         // load filters for further processing
         Filters filters = new Filters();
diff --git a/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/GenerateMetadataMojo.java b/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/GenerateMetadataMojo.java
index 0f10f36..92d2a2e 100644
--- a/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/GenerateMetadataMojo.java
+++ b/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/GenerateMetadataMojo.java
@@ -49,6 +49,7 @@
 
 import org.apache.commons.io.FilenameUtils;
 import org.apache.jackrabbit.vault.fs.api.PathFilterSet;
+import org.apache.jackrabbit.vault.fs.api.WorkspaceFilter;
 import org.apache.jackrabbit.vault.fs.config.ConfigurationException;
 import org.apache.jackrabbit.vault.fs.config.DefaultWorkspaceFilter;
 import org.apache.jackrabbit.vault.fs.filter.DefaultPathFilter;
@@ -627,7 +628,7 @@
         return sourceFilters.getSourceAsString();
     }
 
-    private void mergeFilters(DefaultWorkspaceFilter dst, DefaultWorkspaceFilter src) {
+    private void mergeFilters(DefaultWorkspaceFilter dst, WorkspaceFilter src) {
         for (PathFilterSet fs: src.getFilterSets()) {
             // check for collision
             for (PathFilterSet mfs: dst.getFilterSets()) {
diff --git a/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/VaultMojo.java b/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/VaultMojo.java
index 05acaeb..08dee46 100644
--- a/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/VaultMojo.java
+++ b/src/main/java/org/apache/jackrabbit/filevault/maven/packaging/VaultMojo.java
@@ -20,6 +20,8 @@
 
 import java.io.File;
 import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
@@ -230,14 +232,15 @@
      */
     protected void addFileToArchive(MavenResourcesExecution mavenResourcesExecution, ContentPackageArchiver archiver, File sourceFile,
             String destFileName) throws MavenFilteringException {
-        if ((destFileName.startsWith(Constants.ROOT_DIR) && enableJcrRootFiltering) ||
-            (destFileName.startsWith(Constants.ROOT_DIR) && enableMetaInfFiltering)) {
+        Path destFile = Paths.get(destFileName);
+        if ((destFile.startsWith(Constants.ROOT_DIR) && enableJcrRootFiltering) ||
+            (destFile.startsWith(Constants.META_INF) && enableMetaInfFiltering)) {
             getLog().info("Apply filtering to " + sourceFile);
             Resource resource = new Resource();
             resource.setDirectory(sourceFile.getParent());
             resource.setIncludes(Collections.singletonList(sourceFile.getName()));
             resource.setFiltering(true);
-            File newTargetDirectory = applyFiltering(mavenResourcesExecution, resource);
+            File newTargetDirectory = applyFiltering(destFile.getParent().toString(), mavenResourcesExecution, resource);
             sourceFile = new File(newTargetDirectory, sourceFile.getName());
         }
         archiver.addFile(sourceFile, destFileName);
@@ -252,9 +255,9 @@
      * @throws MavenFilteringException in case filtering failed
      */
     protected void addFileSetToArchive(MavenResourcesExecution mavenResourcesExecution, ContentPackageArchiver archiver, DefaultFileSet fileSet) throws MavenFilteringException {
-        // TODO: what to do with file sets not having any prefix set (workDirectory)
+        // ignore directories added with no prefix (workDirectory)
         if ((fileSet.getPrefix().startsWith(Constants.ROOT_DIR) && enableJcrRootFiltering) ||
-            (fileSet.getPrefix().startsWith(Constants.ROOT_DIR) && enableMetaInfFiltering)) {
+            (fileSet.getPrefix().startsWith(Constants.META_INF) && enableMetaInfFiltering)) {
             
             getLog().info("Apply filtering to FileSet below " + fileSet.getDirectory());
             Resource resource = new Resource();
@@ -267,20 +270,20 @@
                 // default exclude are managed via mavenResourcesExecution
             }
             resource.setFiltering(true);
-            File newTargetDirectory = applyFiltering(mavenResourcesExecution, resource);
+            File newTargetDirectory = applyFiltering(fileSet.getPrefix(), mavenResourcesExecution, resource);
             fileSet.setDirectory(newTargetDirectory);
         }
-
         archiver.addFileSet(fileSet);
     }
 
-    private @NotNull File applyFiltering(MavenResourcesExecution mavenResourcesExecution, Resource resource) throws MavenFilteringException {
+    private @NotNull File applyFiltering(String prefix, MavenResourcesExecution mavenResourcesExecution, Resource resource) throws MavenFilteringException {
         File targetPath = new File(project.getBuild().getDirectory(), "filteredFiles");
+        mavenResourcesExecution.setOutputDirectory(targetPath);
+        targetPath = new File(targetPath, prefix);
         // which path to set as target (is a temporary path)
         getLog().debug("Applying filtering to resource " + resource);
         resource.setTargetPath(targetPath.getPath());
         mavenResourcesExecution.setResources(Collections.singletonList(resource));
-        mavenResourcesExecution.setOutputDirectory(targetPath);
         mavenResourcesFiltering.filterResources(mavenResourcesExecution);
         return targetPath;
     }
diff --git a/src/test/java/org/apache/jackrabbit/filevault/maven/packaging/it/FilteringIT.java b/src/test/java/org/apache/jackrabbit/filevault/maven/packaging/it/FilteringIT.java
index 3b7ca65..c7e33e9 100644
--- a/src/test/java/org/apache/jackrabbit/filevault/maven/packaging/it/FilteringIT.java
+++ b/src/test/java/org/apache/jackrabbit/filevault/maven/packaging/it/FilteringIT.java
@@ -26,30 +26,45 @@
  */
 public class FilteringIT {
 
-    private ProjectBuilder verify(String projectName, String expectedFilesWithChecksumsFile, boolean enableJcrRootFiltering, boolean enableMetaInfFiltering, String ... goals) throws VerificationException, IOException {
+    private ProjectBuilder verify(String projectName, boolean enableJcrRootFiltering, boolean enableMetaInfFiltering, String ... goals) throws VerificationException, IOException {
         return new ProjectBuilder()
                 .setTestProjectDir("filtering-tests/" + projectName)
                 .setTestGoals(goals)
                 .setProperty("vault.enableMetaInfFiltering", Boolean.toString(enableMetaInfFiltering))
                 .setProperty("vault.enableJcrRootFiltering", Boolean.toString(enableJcrRootFiltering))
-                .setExpectedFilesWithChecksumsFile(expectedFilesWithChecksumsFile)
-                .build() 
-                .verifyExpectedFilesChecksum();
+                .build()
+                .verifyExpectedFiles();
     }
 
-    /**
-     * Tests if a pom with no filter definition at all fails.
-     */
     @Test
     public void test_simple_filter_with_filtering_enabled() throws Exception {
-        verify("simple-filter", "expected-files-with-checksums-filtered.txt", true, true);
+        verify("simple-filter", true, true)
+            .verifyExpectedFileChecksum("META-INF/vault/properties.xml", "d4c457e5")
+            .verifyExpectedFileChecksum("jcr_root/apps/bar/test1.properties", "10791371")
+            .verifyExpectedFileChecksum("jcr_root/apps/foo/test2.properties", "7563f01d");
     }
 
-    /**
-     * Tests if a pom with no filter definition at all fails.
-     */
     @Test
     public void test_simple_filter_with_filtering_disabled() throws Exception {
-        verify("simple-filter", "expected-files-with-checksums-unfiltered.txt", false, false);
+        verify("simple-filter", false, false)
+        .verifyExpectedFileChecksum("META-INF/vault/properties.xml", "e04970b0")
+        .verifyExpectedFileChecksum("jcr_root/apps/bar/test1.properties", "34e5a01d")
+        .verifyExpectedFileChecksum("jcr_root/apps/foo/test2.properties", "a41ae6f8");
+    }
+
+    @Test
+    public void test_simple_filter_with_filtering_partially_enabled() throws Exception {
+        verify("simple-filter", true, false)
+        .verifyExpectedFileChecksum("META-INF/vault/properties.xml", "e04970b0")
+        .verifyExpectedFileChecksum("jcr_root/apps/bar/test1.properties", "10791371")
+        .verifyExpectedFileChecksum("jcr_root/apps/foo/test2.properties", "7563f01d");
+    }
+
+    @Test
+    public void test_simple_filter_with_filtering_partially_enabled2() throws Exception {
+        verify("simple-filter", false, true)
+        .verifyExpectedFileChecksum("META-INF/vault/properties.xml", "d4c457e5")
+        .verifyExpectedFileChecksum("jcr_root/apps/bar/test1.properties", "34e5a01d")
+        .verifyExpectedFileChecksum("jcr_root/apps/foo/test2.properties", "a41ae6f8");
     }
 }
diff --git a/src/test/java/org/apache/jackrabbit/filevault/maven/packaging/it/ProjectBuilder.java b/src/test/java/org/apache/jackrabbit/filevault/maven/packaging/it/ProjectBuilder.java
index 10b2081..d9759f0 100644
--- a/src/test/java/org/apache/jackrabbit/filevault/maven/packaging/it/ProjectBuilder.java
+++ b/src/test/java/org/apache/jackrabbit/filevault/maven/packaging/it/ProjectBuilder.java
@@ -333,39 +333,45 @@
         for (String expectedEntryWithChecksum : expectedEntriesWithChecksums) {
             // split name and checksum
             String[] parts = expectedEntryWithChecksum.split(" ", 2);
-            final String name = parts[0];
-            // the second part must be a hexadecimal CRC32 checksum
-            final long expectedChecksum = Long.parseLong(parts[1], 16);
-            try (JarFile jar = new JarFile(testPackageFile)) {
-                JarEntry entry = jar.getJarEntry(name);
-                if (entry == null) {
-                    fail("Could not find entry with name " + name + " in package " + testPackageFile);
-                }
-                Assert.assertThat(entry, new JarEntryMatcher(jar, expectedChecksum));
+            verifyExpectedFileChecksum(parts[0], parts[1]);
+        }
+        return this;
+    }
+
+    public ProjectBuilder verifyExpectedFileChecksum(String name, String checksum) throws IOException {
+        // the second part must be a hexadecimal CRC32 checksum
+        final long expectedChecksum = Long.parseLong(checksum, 16);
+        try (JarFile jar = new JarFile(testPackageFile)) {
+            JarEntry entry = jar.getJarEntry(name);
+            if (entry == null) {
+                fail("Could not find entry with name " + name + " in package " + testPackageFile);
             }
+            Assert.assertThat(entry, new JarEntryMatcher(name, jar, expectedChecksum));
         }
         return this;
     }
 
     private final static class JarEntryMatcher extends TypeSafeMatcher<JarEntry> {
 
+        private final String name;
         private final long expectedCrc; 
         private final JarFile jarFile;
-        public JarEntryMatcher(JarFile jarFile, long expectedCrc) {
+        public JarEntryMatcher(String name, JarFile jarFile, long expectedCrc) {
+            this.name = name;
             this.jarFile = jarFile;
             this.expectedCrc = expectedCrc;
         }
 
         @Override
         protected void describeMismatchSafely(JarEntry item, Description mismatchDescription) {
-            mismatchDescription.appendText("was Jar entry with CRC '").appendText(Long.toHexString(item.getCrc())).appendText("'");
+            mismatchDescription.appendText("was Jar entry with name ").appendValue(item.getName()).appendText(" having the CRC ").appendValue(Long.toHexString(item.getCrc()));
             try (Reader reader = new BoundedReader(new InputStreamReader(jarFile.getInputStream(item), StandardCharsets.UTF_8), 8000)) {
                 String content = IOUtils.toString(reader);
                 // make new line visible
                 content = content.replaceAll("\r", Matcher.quoteReplacement("\r")).replaceAll("\n",  Matcher.quoteReplacement("\n"));
-                mismatchDescription.appendText("(").appendValue(content).appendText(")");
+                mismatchDescription.appendText(" (").appendValue(content).appendText(")");
             } catch (IOException e) {
-                mismatchDescription.appendText("(Could not extract value due to exception ").appendValue(e).appendText(")");
+                mismatchDescription.appendText(" (Could not extract value due to exception ").appendValue(e).appendText(")");
             }
         }
 
@@ -376,7 +382,7 @@
 
         @Override
         public void describeTo(Description description) {
-            description.appendText("having a crc ").appendText(Long.toHexString(expectedCrc));
+            description.appendText("Jar entry with name ").appendValue(name).appendText(" having the CRC ").appendValue(Long.toHexString(expectedCrc));
         }
     }
 
diff --git a/src/test/resources/test-projects/filtering-tests/simple-filter/META-INF/vault/properties.xml b/src/test/resources/test-projects/filtering-tests/simple-filter/META-INF/vault/properties.xml
new file mode 100644
index 0000000..618662e
--- /dev/null
+++ b/src/test/resources/test-projects/filtering-tests/simple-filter/META-INF/vault/properties.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8" standalone="no"?>
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one or more
+  ~ contributor license agreements.  See the NOTICE file distributed with
+  ~ this work for additional information regarding copyright ownership.
+  ~ The ASF licenses this file to You under the Apache License, Version 2.0
+  ~ (the "License"); you may not use this file except in compliance with
+  ~ the License.  You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License.
+  -->
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+<properties>
+<comment>FileVault Package Properties</comment>
+<entry key="createdBy">admin</entry>
+<entry key="name">${customKey}</entry>
+<entry key="lastModified">2011-11-15T09:43:22.972+01:00</entry>
+<entry key="lastModifiedBy">admin</entry>
+<entry key="created">2011-11-15T09:43:22.993+01:00</entry>
+<entry key="buildCount">1</entry>
+<entry key="version"/>
+<entry key="dependencies"/>
+<entry key="packageFormatVersion">2</entry>
+<entry key="description"/>
+<entry key="lastWrapped">2011-11-15T09:43:22.972+01:00</entry>
+<entry key="group"/>
+<entry key="lastWrappedBy">admin</entry>
+<entry key="acHandling">overwrite</entry>
+</properties>
diff --git a/src/test/resources/test-projects/filtering-tests/simple-filter/expected-files-with-checksums-filtered.txt b/src/test/resources/test-projects/filtering-tests/simple-filter/expected-files-with-checksums-filtered.txt
deleted file mode 100644
index 5932341..0000000
--- a/src/test/resources/test-projects/filtering-tests/simple-filter/expected-files-with-checksums-filtered.txt
+++ /dev/null
@@ -1 +0,0 @@
-jcr_root/apps/foo/test.properties 10791371
\ No newline at end of file
diff --git a/src/test/resources/test-projects/filtering-tests/simple-filter/expected-files-with-checksums-unfiltered.txt b/src/test/resources/test-projects/filtering-tests/simple-filter/expected-files-with-checksums-unfiltered.txt
deleted file mode 100644
index 0019059..0000000
--- a/src/test/resources/test-projects/filtering-tests/simple-filter/expected-files-with-checksums-unfiltered.txt
+++ /dev/null
@@ -1 +0,0 @@
-jcr_root/apps/foo/test.properties 34e5a01d
\ No newline at end of file
diff --git a/src/test/resources/test-projects/filtering-tests/simple-filter/expected-files.txt b/src/test/resources/test-projects/filtering-tests/simple-filter/expected-files.txt
new file mode 100644
index 0000000..2a8bd38
--- /dev/null
+++ b/src/test/resources/test-projects/filtering-tests/simple-filter/expected-files.txt
@@ -0,0 +1,18 @@
+META-INF/
+META-INF/MANIFEST.MF
+META-INF/maven/
+META-INF/maven/org.apache.jackrabbit.filevault/
+META-INF/maven/org.apache.jackrabbit.filevault/package-plugin-test-pkg/
+META-INF/maven/org.apache.jackrabbit.filevault/package-plugin-test-pkg/pom.properties
+META-INF/maven/org.apache.jackrabbit.filevault/package-plugin-test-pkg/pom.xml
+META-INF/vault/
+META-INF/vault/config.xml
+META-INF/vault/filter.xml
+META-INF/vault/properties.xml
+META-INF/vault/settings.xml
+jcr_root/
+jcr_root/apps/
+jcr_root/apps/bar/
+jcr_root/apps/bar/test1.properties
+jcr_root/apps/foo/
+jcr_root/apps/foo/test2.properties
\ No newline at end of file
diff --git a/src/test/resources/test-projects/filtering-tests/simple-filter/jcr_root/apps/foo/test.properties b/src/test/resources/test-projects/filtering-tests/simple-filter/jcr_root/apps/bar/test1.properties
similarity index 100%
rename from src/test/resources/test-projects/filtering-tests/simple-filter/jcr_root/apps/foo/test.properties
rename to src/test/resources/test-projects/filtering-tests/simple-filter/jcr_root/apps/bar/test1.properties
diff --git a/src/test/resources/test-projects/filtering-tests/simple-filter/jcr_root/apps/foo/test2.properties b/src/test/resources/test-projects/filtering-tests/simple-filter/jcr_root/apps/foo/test2.properties
new file mode 100644
index 0000000..2ea902c
--- /dev/null
+++ b/src/test/resources/test-projects/filtering-tests/simple-filter/jcr_root/apps/foo/test2.properties
@@ -0,0 +1,21 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+# only values which are not OS/environment specific should be validated here
+project.name=${project.name}
+customKey2=${customKey}
\ No newline at end of file
diff --git a/src/test/resources/test-projects/filtering-tests/simple-filter/pom.xml b/src/test/resources/test-projects/filtering-tests/simple-filter/pom.xml
index 6b9c325..8d815b5 100644
--- a/src/test/resources/test-projects/filtering-tests/simple-filter/pom.xml
+++ b/src/test/resources/test-projects/filtering-tests/simple-filter/pom.xml
@@ -37,6 +37,9 @@
                 <configuration>
                     <filters>
                         <filter>
+                            <root>/apps/bar</root>
+                        </filter>
+                        <filter>
                             <root>/apps/foo</root>
                         </filter>
                     </filters>