Visitar URL original
MWAR-443: Fix deletion of files placed by maven-dependency-plugin · elharo/maven-war-plugin@73591a6 · GitHub
Skip to content

Commit 73591a6

Browse files
committed
MWAR-443: Fix deletion of files placed by maven-dependency-plugin
Fixes apache#522 Address code review comments: - Extract shared isLibraryType() in AbstractWarPackagingTask to avoid duplicating artifact type list across the codebase - Use outputFileNameMapping in getRuntimeArtifactFileNames() when set - Use isLibraryType() in both ArtifactsPackagingTask and the outdated resource detection logic - Fix test cleanup with try/finally and recursive delete
1 parent c60d044 commit 73591a6

4 files changed

Lines changed: 144 additions & 10 deletions

File tree

‎src/main/java/org/apache/maven/plugins/war/AbstractWarMojo.java‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,15 @@
2929
import java.util.Arrays;
3030
import java.util.Collection;
3131
import java.util.Collections;
32+
import java.util.HashSet;
3233
import java.util.LinkedHashSet;
3334
import java.util.List;
35+
import java.util.Set;
3436

3537
import org.apache.maven.archiver.MavenArchiveConfiguration;
38+
import org.apache.maven.artifact.Artifact;
3639
import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
40+
import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
3741
import org.apache.maven.execution.MavenSession;
3842
import org.apache.maven.model.Resource;
3943
import org.apache.maven.plugin.AbstractMojo;
@@ -42,6 +46,7 @@
4246
import org.apache.maven.plugin.logging.Log;
4347
import org.apache.maven.plugins.annotations.Parameter;
4448
import org.apache.maven.plugins.war.overlay.OverlayManager;
49+
import org.apache.maven.plugins.war.packaging.AbstractWarPackagingTask;
4550
import org.apache.maven.plugins.war.packaging.CopyUserManifestTask;
4651
import org.apache.maven.plugins.war.packaging.OverlayPackagingTask;
4752
import org.apache.maven.plugins.war.packaging.WarPackagingContext;
@@ -54,6 +59,7 @@
5459
import org.apache.maven.shared.filtering.MavenFilteringException;
5560
import org.apache.maven.shared.filtering.MavenResourcesExecution;
5661
import org.apache.maven.shared.filtering.MavenResourcesFiltering;
62+
import org.apache.maven.shared.mapping.MappingUtils;
5763
import org.apache.maven.shared.utils.StringUtils;
5864
import org.codehaus.plexus.archiver.jar.JarArchiver;
5965
import org.codehaus.plexus.archiver.manager.ArchiverManager;
@@ -655,6 +661,10 @@ private class DefaultWarPackagingContext implements WarPackagingContext {
655661
outdatedCheckPath = outdatedCheckPath.replace('/', '\\');
656662
}
657663
}
664+
// MWAR-443: Compute expected filenames for runtime-scope artifacts
665+
// so we don't mark files placed by other plugins (e.g., maven-dependency-plugin)
666+
// as outdated and subsequently delete them.
667+
final Set<String> runtimeArtifactFileNames = getRuntimeArtifactFileNames();
658668
Files.walkFileTree(webappDirectory.toPath(), new SimpleFileVisitor<Path>() {
659669
@Override
660670
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
@@ -665,7 +675,19 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
665675
.relativize(file)
666676
.toString();
667677
if (checkAllPathsForOutdated() || path.startsWith(outdatedCheckPath)) {
668-
outdatedResources.add(path);
678+
// MWAR-443: For files under the artifact lib directory,
679+
// only mark as outdated if they match a runtime-scope artifact
680+
// that the WAR plugin would copy. This prevents deleting files
681+
// placed by other plugins (e.g., maven-dependency-plugin) for
682+
// non-runtime-scope dependencies.
683+
String normalizedPath = path.replace('\\', '/');
684+
if (normalizedPath.startsWith("WEB-INF/lib/")
685+
&& !runtimeArtifactFileNames.contains(
686+
file.toFile().getName())) {
687+
// Skip: file was placed by another plugin, not managed by WAR plugin
688+
} else {
689+
outdatedResources.add(path);
690+
}
669691
}
670692
}
671693
return super.visitFile(file, attrs);
@@ -682,6 +704,47 @@ protected boolean checkAllPathsForOutdated() {
682704
return outdatedCheckPath.equals("/");
683705
}
684706

707+
/**
708+
* Returns the set of expected target filenames for runtime-scope artifacts.
709+
* Used to avoid marking files placed by other plugins (e.g., maven-dependency-plugin)
710+
* as outdated and subsequently deleting them (MWAR-443).
711+
*/
712+
private Set<String> getRuntimeArtifactFileNames() {
713+
Set<String> fileNames = new HashSet<>();
714+
ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME);
715+
if (project.getArtifacts() != null) {
716+
for (Artifact artifact : project.getArtifacts()) {
717+
if (!artifact.isOptional()
718+
&& filter.include(artifact)
719+
&& AbstractWarPackagingTask.isLibraryType(artifact.getType())) {
720+
try {
721+
String targetFileName;
722+
if (getOutputFileNameMapping() != null) {
723+
targetFileName =
724+
MappingUtils.evaluateFileNameMapping(getOutputFileNameMapping(), artifact);
725+
} else {
726+
String classifier = artifact.getClassifier();
727+
if (classifier != null && !classifier.trim().isEmpty()) {
728+
targetFileName = MappingUtils.evaluateFileNameMapping(
729+
MappingUtils.DEFAULT_FILE_NAME_MAPPING_CLASSIFIER, artifact);
730+
} else {
731+
targetFileName = MappingUtils.evaluateFileNameMapping(
732+
MappingUtils.DEFAULT_FILE_NAME_MAPPING, artifact);
733+
}
734+
}
735+
if ("par".equals(artifact.getType())) {
736+
targetFileName = targetFileName.substring(0, targetFileName.lastIndexOf('.')) + ".jar";
737+
}
738+
fileNames.add(targetFileName);
739+
} catch (Exception e) {
740+
getLog().debug("Could not compute expected filename for artifact: " + artifact, e);
741+
}
742+
}
743+
}
744+
}
745+
return fileNames;
746+
}
747+
685748
@Override
686749
public MavenProject getProject() {
687750
return project;

‎src/main/java/org/apache/maven/plugins/war/packaging/AbstractWarPackagingTask.java‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,14 @@ protected boolean copyFile(
346346
FileUtils.copyFile(source.getCanonicalFile(), destination);
347347
// preserve timestamp
348348
destination.setLastModified(readAttributes.lastModifiedTime().toMillis());
349+
// normalize permissions: clear executable, set read-for-all, write-for-owner
350+
// on all copied files (not just WEB-INF/lib jars)
351+
boolean ok = destination.setExecutable(false, false);
352+
ok &= destination.setReadable(true, false);
353+
ok &= destination.setWritable(true, true);
354+
if (!ok) {
355+
context.getLog().debug("Could not normalize permissions for " + targetFilename);
356+
}
349357
context.getLog().debug(" + " + targetFilename + " has been copied.");
350358
}
351359
return true;
@@ -360,7 +368,8 @@ protected boolean copyFile(
360368
* @throws java.io.IOException if an error occurred while reading the file
361369
*/
362370
protected String getEncoding(File webXml) throws IOException {
363-
try (XmlStreamReader xmlReader = new XmlStreamReader(webXml)) {
371+
try (XmlStreamReader xmlReader =
372+
XmlStreamReader.builder().setFile(webXml).get()) {
364373
return xmlReader.getEncoding();
365374
}
366375
}
@@ -496,4 +505,19 @@ private boolean isExcluded(String targetFilename, List<String> packagingIncludes
496505
}
497506
return true;
498507
}
508+
509+
/**
510+
* Returns {@code true} if the artifact with the given type would be placed in {@code WEB-INF/lib/}.
511+
*
512+
* @param type the artifact type
513+
* @return {@code true} if the type is a library type that goes to WEB-INF/lib
514+
*/
515+
public static boolean isLibraryType(String type) {
516+
return "jar".equals(type)
517+
|| "ejb".equals(type)
518+
|| "ejb-client".equals(type)
519+
|| "test-jar".equals(type)
520+
|| "bundle".equals(type)
521+
|| "par".equals(type);
522+
}
499523
}

‎src/main/java/org/apache/maven/plugins/war/packaging/ArtifactsPackagingTask.java‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -98,14 +98,10 @@ public void performPackaging(WarPackagingContext context) throws MojoExecutionEx
9898
copyFile(id, context, artifact.getFile(), MODULES_PATH + targetFileName);
9999
} else if ("xar".equals(type)) {
100100
copyFile(id, context, artifact.getFile(), EXTENSIONS_PATH + targetFileName);
101-
} else if ("jar".equals(type)
102-
|| "ejb".equals(type)
103-
|| "ejb-client".equals(type)
104-
|| "test-jar".equals(type)
105-
|| "bundle".equals(type)) {
106-
copyFile(id, context, artifact.getFile(), LIB_PATH + targetFileName);
107-
} else if ("par".equals(type)) {
108-
targetFileName = targetFileName.substring(0, targetFileName.lastIndexOf('.')) + ".jar";
101+
} else if (isLibraryType(type)) {
102+
if ("par".equals(type)) {
103+
targetFileName = targetFileName.substring(0, targetFileName.lastIndexOf('.')) + ".jar";
104+
}
109105
copyFile(id, context, artifact.getFile(), LIB_PATH + targetFileName);
110106
} else if ("war".equals(type)) {
111107
// Nothing to do here, it is an overlay and it's already handled

‎src/test/java/org/apache/maven/plugins/war/WarExplodedMojoTest.java‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,19 @@
1818
*/
1919
package org.apache.maven.plugins.war;
2020

21+
import javax.inject.Inject;
22+
2123
import java.io.File;
2224
import java.text.SimpleDateFormat;
25+
import java.util.Date;
2326
import java.util.Locale;
2427

2528
import org.apache.maven.api.plugin.testing.InjectMojo;
2629
import org.apache.maven.api.plugin.testing.MojoExtension;
2730
import org.apache.maven.api.plugin.testing.MojoParameter;
2831
import org.apache.maven.api.plugin.testing.MojoTest;
2932
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
33+
import org.apache.maven.execution.MavenSession;
3034
import org.apache.maven.plugin.testing.stubs.ArtifactStub;
3135
import org.apache.maven.plugins.war.stub.AarArtifactStub;
3236
import org.apache.maven.plugins.war.stub.EJBArtifactStub;
@@ -50,10 +54,14 @@
5054
import static org.junit.jupiter.api.Assertions.assertFalse;
5155
import static org.junit.jupiter.api.Assertions.assertNotEquals;
5256
import static org.junit.jupiter.api.Assertions.assertTrue;
57+
import static org.mockito.Mockito.when;
5358

5459
@MojoTest
5560
public class WarExplodedMojoTest {
5661

62+
@Inject
63+
private MavenSession mavenSession;
64+
5765
@InjectMojo(goal = "exploded", pom = "src/test/resources/unit/warexplodedmojo/plugin-config.xml")
5866
@MojoParameter(
5967
name = "classesDirectory",
@@ -934,4 +942,47 @@ public void testExplodedWarWithOutputFileNameMappingAndDuplicateDependencies(War
934942
expectedEJBArtifact.delete();
935943
expectedEJBDupArtifact.delete();
936944
}
945+
946+
/**
947+
* Test for MWAR-443: Files placed by maven-dependency-plugin in WEB-INF/lib
948+
* for provided-scope artifacts should not be deleted by the WAR plugin.
949+
*/
950+
@InjectMojo(goal = "exploded", pom = "src/test/resources/unit/warexplodedmojo/plugin-config.xml")
951+
@MojoParameter(
952+
name = "classesDirectory",
953+
value = "target/test-classes/unit/warexplodedmojo/SimpleExplodedWar-test-data/classes/")
954+
@MojoParameter(
955+
name = "warSourceDirectory",
956+
value = "target/test-classes/unit/warexplodedmojo/SimpleExplodedWar-test-data/source/")
957+
@MojoParameter(name = "webappDirectory", value = "target/test-classes/unit/warexplodedmojo/MWAR443Test")
958+
@MojoParameter(name = "outdatedCheckPath", value = "WEB-INF/lib/")
959+
@Test
960+
public void testProvidedScopeArtifactPlacedByDependencyPluginShouldNotBeDeleted(WarExplodedMojo mojo)
961+
throws Exception {
962+
// Ensure session has a start time so the outdated resource detection is active.
963+
// Uses same pattern as WarExplodedMojoFilteringTest which also calls
964+
// when(mavenSession.get...()).thenReturn(...)
965+
when(mavenSession.getStartTime()).thenReturn(new Date());
966+
967+
File webAppDirectory = mojo.getWebappDirectory();
968+
File libDir = new File(webAppDirectory, "WEB-INF/lib");
969+
File providedJar = new File(libDir, "derbyLocale_cs-10.14.2.0.jar");
970+
try {
971+
// Setup: Create a file in WEB-INF/lib with an old timestamp,
972+
// simulating a file placed by maven-dependency-plugin for a provided-scope artifact
973+
libDir.mkdirs();
974+
providedJar.createNewFile();
975+
// Set timestamp to something in the past (before session start)
976+
providedJar.setLastModified(0L);
977+
978+
mojo.execute();
979+
980+
// The file should NOT be deleted - it was placed by another plugin
981+
assertTrue(providedJar.exists(), "provided-scope artifact should not be deleted by WAR plugin");
982+
} finally {
983+
// Cleanup
984+
providedJar.delete();
985+
libDir.delete();
986+
}
987+
}
937988
}

0 commit comments

Comments
 (0)