diff --git a/pom.xml b/pom.xml index 97ab32ea..c32f502a 100644 --- a/pom.xml +++ b/pom.xml @@ -24,11 +24,10 @@ org.apache.maven.shared maven-shared-components 42 - maven-filtering - 3.3.3-SNAPSHOT + 4.0.0-SNAPSHOT Apache Maven Filtering A component to assist in filtering of resource files with properties from a Maven project. @@ -61,17 +60,18 @@ - 3.6.3 - 1.7.36 + 17 + 4.0.0-beta-3 + 2.0.13 0.0.7 - 2024-03-02T08:58:28Z + 2023-03-21T10:54:20Z - javax.inject - javax.inject - 1 + org.apache.maven + maven-api-core + ${mavenVersion} org.slf4j @@ -83,58 +83,38 @@ plexus-build-api ${plexusBuildApiVersion} - - org.apache.maven - maven-core - ${mavenVersion} - provided - - - org.apache.maven - maven-model - ${mavenVersion} - provided - - - org.apache.maven - maven-settings - ${mavenVersion} - provided - org.codehaus.plexus plexus-utils - - - org.codehaus.plexus - plexus-xml + 4.0.0 org.codehaus.plexus plexus-interpolation - 1.27 + 1.26 + - commons-io - commons-io - 2.15.1 + org.apache.maven.plugin-testing + maven-plugin-testing-harness + 4.0.0-alpha-3-SNAPSHOT + test - org.apache.commons - commons-lang3 - 3.14.0 + org.apache.maven + maven-core + ${mavenVersion} - org.mockito - mockito-core - 4.11.0 + mockito-junit-jupiter + 4.7.0 test - org.codehaus.plexus - plexus-testing - 1.3.0 + org.junit.jupiter + junit-jupiter + 5.9.2 test @@ -143,11 +123,6 @@ 2.2 test - - org.junit.jupiter - junit-jupiter-api - test - org.slf4j slf4j-simple @@ -159,11 +134,6 @@ org.eclipse.sisu.plexus test - - org.eclipse.sisu - org.eclipse.sisu.inject - test - diff --git a/src/main/java/org/apache/maven/shared/filtering/AbstractMavenFilteringRequest.java b/src/main/java/org/apache/maven/shared/filtering/AbstractMavenFilteringRequest.java index 503e70e5..e0c88712 100644 --- a/src/main/java/org/apache/maven/shared/filtering/AbstractMavenFilteringRequest.java +++ b/src/main/java/org/apache/maven/shared/filtering/AbstractMavenFilteringRequest.java @@ -23,21 +23,21 @@ import java.util.List; import java.util.Properties; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; /** * @since 1.0-beta-3 */ public class AbstractMavenFilteringRequest { - private MavenProject mavenProject; + private Project mavenProject; private List filters; private boolean escapeWindowsPaths = true; - private MavenSession mavenSession; + private Session mavenSession; /** * List of Strings considered as expressions which contains values in the project/pom: pom project Default value @@ -93,8 +93,7 @@ protected AbstractMavenFilteringRequest() { * @param filters The list of filters. * @param mavenSession The MavenSession. */ - protected AbstractMavenFilteringRequest( - MavenProject mavenProject, List filters, MavenSession mavenSession) { + protected AbstractMavenFilteringRequest(Project mavenProject, List filters, Session mavenSession) { initDefaults(); this.mavenProject = mavenProject; this.filters = filters; @@ -112,7 +111,7 @@ private void initDefaults() { /** * @return The MavenProject */ - public MavenProject getMavenProject() { + public Project getMavenProject() { return mavenProject; } @@ -121,7 +120,7 @@ public MavenProject getMavenProject() { * * @param mavenProject The MavenProject to be set. */ - public void setMavenProject(MavenProject mavenProject) { + public void setMavenProject(Project mavenProject) { this.mavenProject = mavenProject; } @@ -198,14 +197,14 @@ public void setEscapedBackslashesInFilePath(boolean escape) { /** * @return Current value of mavenSession */ - public MavenSession getMavenSession() { + public Session getMavenSession() { return mavenSession; } /** * @param mavenSession Set new value for the MavenSession of the instance. */ - public void setMavenSession(MavenSession mavenSession) { + public void setMavenSession(Session mavenSession) { this.mavenSession = mavenSession; } diff --git a/src/main/java/org/apache/maven/shared/filtering/BaseFilter.java b/src/main/java/org/apache/maven/shared/filtering/BaseFilter.java index 256c2c59..a55a041b 100644 --- a/src/main/java/org/apache/maven/shared/filtering/BaseFilter.java +++ b/src/main/java/org/apache/maven/shared/filtering/BaseFilter.java @@ -18,19 +18,20 @@ */ package org.apache.maven.shared.filtering; -import java.io.File; import java.io.IOException; import java.io.Reader; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; +import java.util.Optional; import java.util.Properties; import java.util.TreeSet; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; -import org.apache.maven.settings.Settings; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; +import org.apache.maven.api.settings.Settings; import org.codehaus.plexus.interpolation.Interpolator; import org.codehaus.plexus.interpolation.PrefixAwareRecursionInterceptor; import org.codehaus.plexus.interpolation.PrefixedObjectValueSource; @@ -52,10 +53,10 @@ protected Logger getLogger() { @Override public List getDefaultFilterWrappers( - final MavenProject mavenProject, + final Project mavenProject, List filters, final boolean escapedBackslashesInFilePath, - MavenSession mavenSession, + Session mavenSession, MavenResourcesExecution mavenResourcesExecution) throws MavenFilteringException { @@ -88,10 +89,7 @@ public List getDefaultFilterWrappers(final AbstractMavenFiltering // Project properties if (request.getMavenProject() != null) { - baseProps.putAll( - request.getMavenProject().getProperties() == null - ? Collections.emptyMap() - : request.getMavenProject().getProperties()); + baseProps.putAll(request.getMavenProject().getModel().getProperties()); } // TODO this is NPE free but do we consider this as normal // or do we have to throw an MavenFilteringException with mavenSession cannot be null @@ -107,20 +105,21 @@ public List getDefaultFilterWrappers(final AbstractMavenFiltering // if (request.getMavenSession() != null) { // User properties have precedence over system properties - putAll(baseProps, request.getMavenSession().getSystemProperties()); - putAll(baseProps, request.getMavenSession().getUserProperties()); + baseProps.putAll(request.getMavenSession().getSystemProperties()); + baseProps.putAll(request.getMavenSession().getUserProperties()); } // now we build properties to use for resources interpolation final Properties filterProperties = new Properties(); - File basedir = - request.getMavenProject() != null ? request.getMavenProject().getBasedir() : new File("."); + Path basedir = Optional.ofNullable(request.getMavenProject()) + .map(Project::getBasedir) + .orElseGet(() -> Paths.get(".")); loadProperties(filterProperties, basedir, request.getFileFilters(), baseProps); if (filterProperties.isEmpty()) { - putAll(filterProperties, baseProps); + filterProperties.putAll(baseProps); } if (request.getMavenProject() != null) { @@ -137,20 +136,17 @@ public List getDefaultFilterWrappers(final AbstractMavenFiltering } // Project properties - filterProperties.putAll( - request.getMavenProject().getProperties() == null - ? Collections.emptyMap() - : request.getMavenProject().getProperties()); + filterProperties.putAll(request.getMavenProject().getModel().getProperties()); } if (request.getMavenSession() != null) { // User properties have precedence over system properties - putAll(filterProperties, request.getMavenSession().getSystemProperties()); - putAll(filterProperties, request.getMavenSession().getUserProperties()); + filterProperties.putAll(request.getMavenSession().getSystemProperties()); + filterProperties.putAll(request.getMavenSession().getUserProperties()); } if (request.getAdditionalProperties() != null) { // additional properties wins - putAll(filterProperties, request.getAdditionalProperties()); + filterProperties.putAll(request.getAdditionalProperties()); } List defaultFilterWrappers = @@ -180,22 +176,15 @@ public List getDefaultFilterWrappers(final AbstractMavenFiltering return defaultFilterWrappers; } - @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") - private static void putAll(Properties filterProperties, Properties request) { - synchronized (request) { - filterProperties.putAll(request); - } - } - /** * default visibility only for testing reason ! */ void loadProperties( - Properties filterProperties, File basedir, List propertiesFilePaths, Properties baseProps) + Properties filterProperties, Path basedir, List propertiesFilePaths, Properties baseProps) throws MavenFilteringException { if (propertiesFilePaths != null) { Properties workProperties = new Properties(); - putAll(workProperties, baseProps); + workProperties.putAll(baseProps); for (String filterFile : propertiesFilePaths) { if (filterFile == null || filterFile.trim().isEmpty()) { @@ -203,10 +192,10 @@ void loadProperties( continue; } try { - File propFile = FilteringUtils.resolveFile(basedir, filterFile); + Path propFile = FilteringUtils.resolveFile(basedir, filterFile); Properties properties = PropertyUtils.loadPropertyFile(propFile, workProperties, getLogger()); - putAll(filterProperties, properties); - putAll(workProperties, properties); + filterProperties.putAll(properties); + workProperties.putAll(properties); } catch (IOException e) { throw new MavenFilteringException("Error loading property file '" + filterFile + "'", e); } @@ -218,7 +207,7 @@ private static final class Wrapper extends FilterWrapper { private LinkedHashSet delimiters; - private MavenProject project; + private Project project; private ValueSource propertiesValueSource; @@ -228,14 +217,14 @@ private static final class Wrapper extends FilterWrapper { private boolean escapeWindowsPaths; - private final MavenSession mavenSession; + private final Session mavenSession; private boolean supportMultiLineFiltering; Wrapper( LinkedHashSet delimiters, - MavenProject project, - MavenSession mavenSession, + Project project, + Session mavenSession, ValueSource propertiesValueSource, List projectStartExpressions, String escapeString, @@ -288,8 +277,8 @@ private static Interpolator createInterpolator( LinkedHashSet delimiters, List projectStartExpressions, ValueSource propertiesValueSource, - MavenProject project, - MavenSession mavenSession, + Project project, + Session mavenSession, String escapeString, boolean escapeWindowsPaths) { MultiDelimiterStringSearchInterpolator interpolator = new MultiDelimiterStringSearchInterpolator(); @@ -298,7 +287,18 @@ private static Interpolator createInterpolator( interpolator.addValueSource(propertiesValueSource); if (project != null) { - interpolator.addValueSource(new PrefixedObjectValueSource(projectStartExpressions, project, true)); + for (Object root : new Object[] {project, project.getModel()}) { + interpolator.addValueSource(new PrefixedObjectValueSource(projectStartExpressions, root, true) { + @Override + public Object getValue(String expression) { + Object value = super.getValue(expression); + if (value instanceof Optional) { + value = ((Optional) value).orElse(null); + } + return value; + } + }); + } } if (mavenSession != null) { diff --git a/src/main/java/org/apache/maven/shared/filtering/DefaultFilterInfo.java b/src/main/java/org/apache/maven/shared/filtering/DefaultFilterInfo.java index 45560c9e..16c33fff 100644 --- a/src/main/java/org/apache/maven/shared/filtering/DefaultFilterInfo.java +++ b/src/main/java/org/apache/maven/shared/filtering/DefaultFilterInfo.java @@ -20,8 +20,8 @@ import java.util.List; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; /** * @author Kristian Rosenvold @@ -39,10 +39,10 @@ public interface DefaultFilterInfo { * @since 1.0-beta-2 */ List getDefaultFilterWrappers( - MavenProject mavenProject, + Project mavenProject, List filters, boolean escapedBackslashesInFilePath, - MavenSession mavenSession, + Session mavenSession, MavenResourcesExecution mavenResourcesExecution) throws MavenFilteringException; diff --git a/src/main/java/org/apache/maven/shared/filtering/DefaultMavenFileFilter.java b/src/main/java/org/apache/maven/shared/filtering/DefaultMavenFileFilter.java index c6b03549..e4437b57 100644 --- a/src/main/java/org/apache/maven/shared/filtering/DefaultMavenFileFilter.java +++ b/src/main/java/org/apache/maven/shared/filtering/DefaultMavenFileFilter.java @@ -22,12 +22,12 @@ import javax.inject.Named; import javax.inject.Singleton; -import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.util.List; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; import org.sonatype.plexus.build.incremental.BuildContext; import static java.util.Objects.requireNonNull; @@ -47,14 +47,14 @@ public DefaultMavenFileFilter(BuildContext buildContext) { @Override public void copyFile( - File from, - File to, + Path from, + Path to, boolean filtering, - MavenProject mavenProject, + Project mavenProject, List filters, boolean escapedBackslashesInFilePath, String encoding, - MavenSession mavenSession) + Session mavenSession) throws MavenFilteringException { MavenResourcesExecution mre = new MavenResourcesExecution(); mre.setMavenProject(mavenProject); @@ -80,42 +80,28 @@ public void copyFile(MavenFileFilterRequest mavenFileFilterRequest) throws Maven } @Override - public void copyFile(File from, File to, boolean filtering, List filterWrappers, String encoding) + public void copyFile(Path from, Path to, boolean filtering, List filterWrappers, String encoding) throws MavenFilteringException { try { if (filtering) { if (getLogger().isDebugEnabled()) { - getLogger().debug("filtering " + from.getPath() + " to " + to.getPath()); + getLogger().debug("filtering " + from + " to " + to); } FilterWrapper[] array = filterWrappers.toArray(new FilterWrapper[0]); FilteringUtils.copyFile(from, to, encoding, array, false); } else { if (getLogger().isDebugEnabled()) { - getLogger().debug("copy " + from.getPath() + " to " + to.getPath()); + getLogger().debug("copy " + from + " to " + to); } FilteringUtils.copyFile(from, to, encoding, new FilterWrapper[0], false); } - buildContext.refresh(to); + buildContext.refresh(to.toFile()); } catch (IOException e) { throw new MavenFilteringException( - (filtering ? "filtering " : "copying ") + from.getPath() + " to " + to.getPath() + " failed with " - + e.getClass().getSimpleName(), + (filtering ? "filtering " : "copying ") + from + " to " + to + " failed with " + + e.getClass().getSimpleName() + ": " + e.getMessage(), e); } } - - @Override - @Deprecated - public void copyFile( - File from, - File to, - boolean filtering, - List filterWrappers, - String encoding, - boolean overwrite) - throws MavenFilteringException { - // overwrite forced to false to preserve backward comp - copyFile(from, to, filtering, filterWrappers, encoding); - } } diff --git a/src/main/java/org/apache/maven/shared/filtering/DefaultMavenReaderFilter.java b/src/main/java/org/apache/maven/shared/filtering/DefaultMavenReaderFilter.java index a3c7d2a6..80d18655 100644 --- a/src/main/java/org/apache/maven/shared/filtering/DefaultMavenReaderFilter.java +++ b/src/main/java/org/apache/maven/shared/filtering/DefaultMavenReaderFilter.java @@ -25,8 +25,8 @@ import java.util.Collections; import java.util.List; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; /** * @author Kristian Rosenvold @@ -38,10 +38,10 @@ public class DefaultMavenReaderFilter extends BaseFilter implements MavenReaderF public Reader filter( Reader from, boolean filtering, - MavenProject mavenProject, + Project mavenProject, List filters, boolean escapedBackslashesInFilePath, - MavenSession mavenSession) + Session mavenSession) throws MavenFilteringException { MavenResourcesExecution mre = new MavenResourcesExecution(); mre.setMavenProject(mavenProject); diff --git a/src/main/java/org/apache/maven/shared/filtering/DefaultMavenResourcesFiltering.java b/src/main/java/org/apache/maven/shared/filtering/DefaultMavenResourcesFiltering.java index 0c8688f8..8e0304e1 100644 --- a/src/main/java/org/apache/maven/shared/filtering/DefaultMavenResourcesFiltering.java +++ b/src/main/java/org/apache/maven/shared/filtering/DefaultMavenResourcesFiltering.java @@ -22,11 +22,11 @@ import javax.inject.Named; import javax.inject.Singleton; -import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -34,11 +34,6 @@ import java.util.List; import java.util.Locale; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.maven.model.Resource; -import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -57,6 +52,7 @@ public class DefaultMavenResourcesFiltering implements MavenResourcesFiltering { private static final String[] EMPTY_STRING_ARRAY = {}; private static final String[] DEFAULT_INCLUDES = {"**/**"}; + private static final int BUFFER_LENGTH = 8192; private final List defaultNonFilteredFileExtensions; @@ -93,8 +89,13 @@ public boolean filteredFileExtension(String fileName, List userNonFilter } private static String getExtension(String fileName) { - String rawExt = FilenameUtils.getExtension(fileName); - return rawExt == null ? null : rawExt.toLowerCase(Locale.ROOT); + final int extensionPos = fileName.lastIndexOf('.'); + final int lastUnixPos = fileName.lastIndexOf('/'); + final int lastWindowsPos = fileName.lastIndexOf('\\'); + final int lastSeparator = Math.max(lastUnixPos, lastWindowsPos); + return lastSeparator > extensionPos + ? "" + : fileName.substring(extensionPos + 1).toLowerCase(Locale.ROOT); } @Override @@ -122,7 +123,7 @@ public void filterResources(MavenResourcesExecution mavenResourcesExecution) thr } if (mavenResourcesExecution.getEncoding() == null - || mavenResourcesExecution.getEncoding().length() < 1) { + || mavenResourcesExecution.getEncoding().isEmpty()) { LOGGER.warn("Using platform encoding (" + System.getProperty("file.encoding") + " actually) to copy filtered resources, i.e. build is platform dependent!"); } else { @@ -130,7 +131,7 @@ public void filterResources(MavenResourcesExecution mavenResourcesExecution) thr } if (mavenResourcesExecution.getPropertiesEncoding() == null - || mavenResourcesExecution.getPropertiesEncoding().length() < 1) { + || mavenResourcesExecution.getPropertiesEncoding().isEmpty()) { LOGGER.debug("Using '" + mavenResourcesExecution.getEncoding() + "' encoding to copy filtered properties files."); } else { @@ -140,7 +141,7 @@ public void filterResources(MavenResourcesExecution mavenResourcesExecution) thr // Keep track of filtering being used and the properties files being filtered boolean isFilteringUsed = false; - List propertiesFiles = new ArrayList<>(); + List propertiesFiles = new ArrayList<>(); for (Resource resource : mavenResourcesExecution.getResources()) { @@ -175,14 +176,14 @@ public void filterResources(MavenResourcesExecution mavenResourcesExecution) thr String targetPath = resource.getTargetPath(); - File resourceDirectory = (resource.getDirectory() == null) ? null : new File(resource.getDirectory()); + Path resourceDirectory = (resource.getDirectory() == null) ? null : Paths.get(resource.getDirectory()); if (resourceDirectory != null && !resourceDirectory.isAbsolute()) { resourceDirectory = - new File(mavenResourcesExecution.getResourcesBaseDirectory(), resourceDirectory.getPath()); + mavenResourcesExecution.getResourcesBaseDirectory().resolve(resourceDirectory); } - if (resourceDirectory == null || !resourceDirectory.exists()) { + if (resourceDirectory == null || !Files.exists(resourceDirectory)) { LOGGER.info("skip non existing resourceDirectory " + resourceDirectory); continue; } @@ -190,45 +191,25 @@ public void filterResources(MavenResourcesExecution mavenResourcesExecution) thr // this part is required in case the user specified "../something" // as destination // see MNG-1345 - File outputDirectory = mavenResourcesExecution.getOutputDirectory(); - if (!outputDirectory.mkdirs() && !outputDirectory.exists()) { - throw new MavenFilteringException("Cannot create resource output directory: " + outputDirectory); + Path outputDirectory = mavenResourcesExecution.getOutputDirectory(); + boolean outputExists = Files.exists(outputDirectory); + if (!outputExists) { + try { + Files.createDirectories(outputDirectory); + } catch (IOException e) { + throw new MavenFilteringException("Cannot create resource output directory: " + outputDirectory, e); + } } if (resource.isFiltering()) { isFilteringUsed = true; } - boolean filtersFileChanged = buildContext.hasDelta(mavenResourcesExecution.getFileFilters()); - Path resourcePath = resourceDirectory.toPath(); - DirectoryScanner scanner = new DirectoryScanner() { - @Override - protected boolean isSelected(String name, File file) { - if (filtersFileChanged) { - // if the file filters file has a change we must assume everything is out of - // date - return true; - } - if (file.isFile()) { - try { - File targetFile = getTargetFile(file); - if (targetFile.isFile() && buildContext.isUptodate(targetFile, file)) { - return false; - } - } catch (MavenFilteringException e) { - // can't really do anything than to assume we must copy the file... - } - } - return true; - } - - private File getTargetFile(File file) throws MavenFilteringException { - Path relativize = resourcePath.relativize(file.toPath()); - return getDestinationFile( - outputDirectory, targetPath, relativize.toString(), mavenResourcesExecution); - } - }; - scanner.setBasedir(resourceDirectory); + boolean ignoreDelta = !outputExists + || buildContext.hasDelta(mavenResourcesExecution.getFileFilters()) + || buildContext.hasDelta(getRelativeOutputDirectory(mavenResourcesExecution)); + LOGGER.debug("ignoreDelta " + ignoreDelta); + Scanner scanner = buildContext.newScanner(resourceDirectory.toFile(), ignoreDelta); setupScanner(resource, scanner, mavenResourcesExecution.isAddDefaultExcludes()); @@ -236,34 +217,24 @@ private File getTargetFile(File file) throws MavenFilteringException { if (mavenResourcesExecution.isIncludeEmptyDirs()) { try { - File targetDirectory = targetPath == null ? outputDirectory : new File(outputDirectory, targetPath); + Path targetDirectory = targetPath == null ? outputDirectory : outputDirectory.resolve(targetPath); copyDirectoryLayout(resourceDirectory, targetDirectory, scanner); } catch (IOException e) { - throw new MavenFilteringException("Cannot copy directory structure from " - + resourceDirectory.getPath() + " to " + outputDirectory.getPath()); + throw new MavenFilteringException( + "Cannot copy directory structure from " + resourceDirectory + " to " + outputDirectory); } } List includedFiles = Arrays.asList(scanner.getIncludedFiles()); try { - Path basedir = mavenResourcesExecution - .getMavenProject() - .getBasedir() - .getAbsoluteFile() - .toPath(); + Path basedir = + mavenResourcesExecution.getMavenProject().getBasedir().toAbsolutePath(); Path destination = getDestinationFile(outputDirectory, targetPath, "", mavenResourcesExecution) - .getAbsoluteFile() - .toPath(); - String origin = basedir.relativize( - resourceDirectory.getAbsoluteFile().toPath()) - .toString(); - if (StringUtils.isEmpty(origin)) { - origin = "."; - } + .toAbsolutePath(); LOGGER.info("Copying " + includedFiles.size() + " resource" + (includedFiles.size() > 1 ? "s" : "") + " from " - + origin + + basedir.relativize(resourceDirectory.toAbsolutePath()) + " to " + basedir.relativize(destination)); } catch (Exception e) { @@ -275,20 +246,21 @@ private File getTargetFile(File file) throws MavenFilteringException { for (String name : includedFiles) { LOGGER.debug("Copying file " + name); - File source = new File(resourceDirectory, name); + Path source = resourceDirectory.resolve(name); - File destinationFile = getDestinationFile(outputDirectory, targetPath, name, mavenResourcesExecution); + Path destinationFile = getDestinationFile(outputDirectory, targetPath, name, mavenResourcesExecution); - if (mavenResourcesExecution.isFlatten() && destinationFile.exists()) { + if (mavenResourcesExecution.isFlatten() && Files.exists(destinationFile)) { if (mavenResourcesExecution.isOverwrite()) { - LOGGER.warn("existing file " + destinationFile.getName() + " will be overwritten by " + name); + LOGGER.warn( + "existing file " + destinationFile.getFileName() + " will be overwritten by " + name); } else { - throw new MavenFilteringException("existing file " + destinationFile.getName() + throw new MavenFilteringException("existing file " + destinationFile.getFileName() + " will be overwritten by " + name + " and overwrite was not set to true"); } } - boolean filteredExt = - filteredFileExtension(source.getName(), mavenResourcesExecution.getNonFilteredFileExtensions()); + boolean filteredExt = filteredFileExtension( + source.getFileName().toString(), mavenResourcesExecution.getNonFilteredFileExtensions()); if (resource.isFiltering() && isPropertiesFile(source)) { propertiesFiles.add(source); } @@ -296,30 +268,34 @@ private File getTargetFile(File file) throws MavenFilteringException { // Determine which encoding to use when filtering this file String encoding = getEncoding( source, mavenResourcesExecution.getEncoding(), mavenResourcesExecution.getPropertiesEncoding()); - LOGGER.debug("Using '" + encoding + "' encoding to copy filtered resource '" + source.getName() + "'."); + LOGGER.debug( + "Using '" + encoding + "' encoding to copy filtered resource '" + source.getFileName() + "'."); mavenFileFilter.copyFile( source, destinationFile, resource.isFiltering() && filteredExt, mavenResourcesExecution.getFilterWrappers(), - encoding, - mavenResourcesExecution.isOverwrite()); + encoding); } // deal with deleted source files - Scanner deleteScanner = buildContext.newDeleteScanner(resourceDirectory); + scanner = buildContext.newDeleteScanner(resourceDirectory.toFile()); - setupScanner(resource, deleteScanner, mavenResourcesExecution.isAddDefaultExcludes()); + setupScanner(resource, scanner, mavenResourcesExecution.isAddDefaultExcludes()); - deleteScanner.scan(); + scanner.scan(); - for (String name : deleteScanner.getIncludedFiles()) { - File destinationFile = getDestinationFile(outputDirectory, targetPath, name, mavenResourcesExecution); + for (String name : scanner.getIncludedFiles()) { + Path destinationFile = getDestinationFile(outputDirectory, targetPath, name, mavenResourcesExecution); - destinationFile.delete(); + try { + Files.deleteIfExists(destinationFile); + } catch (IOException e) { + // ignore + } - buildContext.refresh(destinationFile); + buildContext.refresh(destinationFile.toFile()); } } @@ -329,10 +305,10 @@ private File getTargetFile(File file) throws MavenFilteringException { // - filtering is enabled for at least one resource // - there is at least one properties file in one of the resources that has filtering enabled if ((mavenResourcesExecution.getPropertiesEncoding() == null - || mavenResourcesExecution.getPropertiesEncoding().length() < 1) + || mavenResourcesExecution.getPropertiesEncoding().isEmpty()) && !mavenResourcesExecution.getNonFilteredFileExtensions().contains("properties") && isFilteringUsed - && propertiesFiles.size() > 0) { + && !propertiesFiles.isEmpty()) { // @todo Sometime in the future we should change this to be a warning LOGGER.info("The encoding used to copy filtered properties files has not been set." + " This means that the same encoding will be used to copy filtered properties files" @@ -345,8 +321,8 @@ private File getTargetFile(File file) throws MavenFilteringException { StringBuilder affectedFiles = new StringBuilder(); affectedFiles.append("Here is a list of the filtered properties files in your project that might be" + " affected by encoding problems: "); - for (File propertiesFile : propertiesFiles) { - affectedFiles.append(System.lineSeparator()).append(" - ").append(propertiesFile.getPath()); + for (Path propertiesFile : propertiesFiles) { + affectedFiles.append(System.lineSeparator()).append(" - ").append(propertiesFile); } LOGGER.debug(affectedFiles.toString()); } @@ -362,7 +338,7 @@ private File getTargetFile(File file) throws MavenFilteringException { * @return The encoding to use when filtering the specified file * @since 3.2.0 */ - static String getEncoding(File file, String encoding, String propertiesEncoding) { + static String getEncoding(Path file, String encoding, String propertiesEncoding) { if (isPropertiesFile(file)) { if (propertiesEncoding == null) { // Since propertiesEncoding is a new feature, not all plugins will have implemented support for it. @@ -383,8 +359,8 @@ static String getEncoding(File file, String encoding, String propertiesEncoding) * @return true if the file name has an extension of "properties", otherwise false * @since 3.2.0 */ - static boolean isPropertiesFile(File file) { - return "properties".equals(getExtension(file.getName())); + static boolean isPropertiesFile(Path file) { + return "properties".equals(getExtension(file.getFileName().toString())); } private void handleDefaultFilterWrappers(MavenResourcesExecution mavenResourcesExecution) @@ -397,8 +373,8 @@ private void handleDefaultFilterWrappers(MavenResourcesExecution mavenResourcesE mavenResourcesExecution.setFilterWrappers(filterWrappers); } - private File getDestinationFile( - File outputDirectory, String targetPath, String name, MavenResourcesExecution mavenResourcesExecution) + private Path getDestinationFile( + Path outputDirectory, String targetPath, String name, MavenResourcesExecution mavenResourcesExecution) throws MavenFilteringException { String destination; if (!mavenResourcesExecution.isFlatten()) { @@ -410,7 +386,7 @@ private File getDestinationFile( } if (mavenResourcesExecution.isFilterFilenames() - && mavenResourcesExecution.getFilterWrappers().size() > 0) { + && !mavenResourcesExecution.getFilterWrappers().isEmpty()) { destination = filterFileName(destination, mavenResourcesExecution.getFilterWrappers()); } @@ -418,14 +394,14 @@ private File getDestinationFile( destination = targetPath + "/" + destination; } - File destinationFile = new File(destination); - if (!destinationFile.isAbsolute()) { - destinationFile = new File(outputDirectory, destination); - } + Path destinationFile = outputDirectory.resolve(destination); - if (!destinationFile.getParentFile().exists()) { - destinationFile.getParentFile().mkdirs(); + try { + Files.createDirectories(destinationFile.getParent()); + } catch (IOException e) { + throw new MavenFilteringException("Unable to create directory " + destinationFile.getParent(), e); } + return destinationFile; } @@ -438,9 +414,8 @@ private String[] setupScanner(Resource resource, Scanner scanner, boolean addDef } scanner.setIncludes(includes); - String[] excludes = null; if (resource.getExcludes() != null && !resource.getExcludes().isEmpty()) { - excludes = resource.getExcludes().toArray(EMPTY_STRING_ARRAY); + String[] excludes = resource.getExcludes().toArray(EMPTY_STRING_ARRAY); scanner.setExcludes(excludes); } @@ -450,7 +425,7 @@ private String[] setupScanner(Resource resource, Scanner scanner, boolean addDef return includes; } - private void copyDirectoryLayout(File sourceDirectory, File destinationDirectory, Scanner scanner) + private void copyDirectoryLayout(Path sourceDirectory, Path destinationDirectory, Scanner scanner) throws IOException { if (sourceDirectory == null) { throw new IOException("source directory can't be null."); @@ -464,30 +439,31 @@ private void copyDirectoryLayout(File sourceDirectory, File destinationDirectory throw new IOException("source and destination are the same directory."); } - if (!sourceDirectory.exists()) { - throw new IOException("Source directory doesn't exist (" + sourceDirectory.getAbsolutePath() + ")."); + if (!Files.exists(sourceDirectory)) { + throw new IOException("Source directory doesn't exists (" + sourceDirectory.toAbsolutePath() + ")."); } for (String name : scanner.getIncludedDirectories()) { - File source = new File(sourceDirectory, name); + Path source = sourceDirectory.resolve(name); if (source.equals(sourceDirectory)) { continue; } - File destination = new File(destinationDirectory, name); - destination.mkdirs(); + Path destination = destinationDirectory.resolve(name); + Files.createDirectories(destination); } } private String getRelativeOutputDirectory(MavenResourcesExecution execution) { - String relOutDir = execution.getOutputDirectory().getAbsolutePath(); + String relOutDir = execution.getOutputDirectory().toAbsolutePath().toString(); - if (execution.getMavenProject() != null && execution.getMavenProject().getBasedir() != null) { - String basedir = execution.getMavenProject().getBasedir().getAbsolutePath(); + if (execution.getMavenProject() != null) { + String basedir = + execution.getMavenProject().getBasedir().toAbsolutePath().toString(); relOutDir = FilteringUtils.getRelativeFilePath(basedir, relOutDir); if (relOutDir == null) { - relOutDir = execution.getOutputDirectory().getPath(); + relOutDir = execution.getOutputDirectory().toString(); } else { relOutDir = relOutDir.replace('\\', '/'); } @@ -507,7 +483,12 @@ private String filterFileName(String name, List wrappers) throws } try (StringWriter writer = new StringWriter()) { - IOUtils.copy(reader, writer); + char[] buffer = new char[BUFFER_LENGTH]; + int nRead; + while ((nRead = reader.read(buffer, 0, buffer.length)) >= 0) { + writer.write(buffer, 0, nRead); + } + String filteredFilename = writer.toString(); if (LOGGER.isDebugEnabled()) { diff --git a/src/main/java/org/apache/maven/shared/filtering/FilteringUtils.java b/src/main/java/org/apache/maven/shared/filtering/FilteringUtils.java index 6c1f3d3e..b3ea73e2 100644 --- a/src/main/java/org/apache/maven/shared/filtering/FilteringUtils.java +++ b/src/main/java/org/apache/maven/shared/filtering/FilteringUtils.java @@ -26,12 +26,12 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.NoSuchFileException; -import java.nio.file.attribute.PosixFilePermission; -import java.util.EnumSet; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Locale; import java.util.StringTokenizer; import java.util.regex.Pattern; -import org.apache.commons.lang3.SystemUtils; import org.codehaus.plexus.util.io.CachingOutputStream; import org.codehaus.plexus.util.io.CachingWriter; @@ -58,6 +58,10 @@ public final class FilteringUtils { private static final String WINDOWS_PATH_PATTERN = "^(.*)[a-zA-Z]:\\\\(.*)"; private static final Pattern PATTERN = Pattern.compile(WINDOWS_PATH_PATTERN); + + private static final boolean IS_WINDOWS = + System.getProperty("os.name").toLowerCase(Locale.ROOT).startsWith("windows"); + public static final int COPY_BUFFER_LENGTH = 8192; /** @@ -103,7 +107,7 @@ public static String escapeWindowsPath(String val) { * @param filename absolute or relative file path to resolve * @return the canonical File of filename */ - public static File resolveFile(final File baseFile, String filename) { + public static Path resolveFile(final Path baseFile, String filename) { String filenm = filename; if ('/' != File.separatorChar) { filenm = filename.replace('/', File.separatorChar); @@ -114,17 +118,10 @@ public static File resolveFile(final File baseFile, String filename) { } // deal with absolute files - if (filenm.startsWith(File.separator) || (SystemUtils.IS_OS_WINDOWS && filenm.indexOf(":") > 0)) { - File file = new File(filenm); - - try { - file = file.getCanonicalFile(); - } catch (final IOException ioe) { - // nop - } - - return file; + if (filenm.startsWith(File.separator) || (IS_WINDOWS && filenm.indexOf(":") > 0)) { + return Paths.get(filenm).toAbsolutePath().normalize(); } + // FIXME: I'm almost certain this // removal is unnecessary, as getAbsoluteFile() strips // them. However, I'm not sure about this UNC stuff. (JT) final char[] chars = filename.toCharArray(); @@ -150,15 +147,7 @@ public static File resolveFile(final File baseFile, String filename) { filenm = sb.toString(); // must be relative - File file = (new File(baseFile, filenm)).getAbsoluteFile(); - - try { - file = file.getCanonicalFile(); - } catch (final IOException ioe) { - // nop - } - - return file; + return baseFile.resolve(filenm).toAbsolutePath().normalize(); } /** @@ -306,21 +295,21 @@ static boolean isEmpty(final String string) { * @param wrappers array of {@link FilterWrapper} * @throws IOException if an IO error occurs during copying or filtering */ - public static void copyFile(File from, File to, String encoding, FilterWrapper[] wrappers) throws IOException { - setReadWritePermissions(to); - + public static void copyFile(Path from, Path to, String encoding, FilterWrapper[] wrappers, boolean overwrite) + throws IOException { if (wrappers == null || wrappers.length == 0) { - try (OutputStream os = new CachingOutputStream(to.toPath())) { - Files.copy(from.toPath(), os); + try (OutputStream os = new CachingOutputStream(to)) { + Files.copy(from, os); } } else { Charset charset = charset(encoding); - try (Reader fileReader = Files.newBufferedReader(from.toPath(), charset)) { + + try (Reader fileReader = Files.newBufferedReader(from, charset)) { Reader wrapped = fileReader; for (FilterWrapper wrapper : wrappers) { wrapped = wrapper.getReader(wrapped); } - try (Writer writer = new CachingWriter(to.toPath(), charset)) { + try (Writer writer = new CachingWriter(to, charset)) { char[] buffer = new char[COPY_BUFFER_LENGTH]; int nRead; while ((nRead = wrapped.read(buffer, 0, COPY_BUFFER_LENGTH)) >= 0) { @@ -333,24 +322,6 @@ public static void copyFile(File from, File to, String encoding, FilterWrapper[] copyFilePermissions(from, to); } - /** - * If wrappers is null or empty, the file will be copy only if to.lastModified() < from.lastModified() or if - * overwrite is true. - * - * @param from the file to copy - * @param to the destination file - * @param encoding the file output encoding (only if wrappers is not empty) - * @param wrappers array of {@link FilterWrapper} - * @param overwrite unused - * @throws IOException if an IO error occurs during copying or filtering - * @deprecated use {@link #copyFile(File, File, String, FilterWrapper[])} instead - */ - @Deprecated - public static void copyFile(File from, File to, String encoding, FilterWrapper[] wrappers, boolean overwrite) - throws IOException { - copyFile(from, to, encoding, wrappers); - } - /** * Attempts to copy file permissions from the source to the destination file. * Initially attempts to copy posix file permissions, assuming that the files are both on posix filesystems. @@ -361,34 +332,19 @@ public static void copyFile(File from, File to, String encoding, FilterWrapper[] * @param source the file to copy permissions from. * @param destination the file to copy permissions to. */ - private static void copyFilePermissions(File source, File destination) throws IOException { + private static void copyFilePermissions(Path source, Path destination) throws IOException { try { // attempt to copy posix file permissions - Files.setPosixFilePermissions(destination.toPath(), Files.getPosixFilePermissions(source.toPath())); + Files.setPosixFilePermissions(destination, Files.getPosixFilePermissions(source)); } catch (NoSuchFileException nsfe) { // ignore if destination file or symlink does not exist } catch (UnsupportedOperationException e) { // fallback to setting partial permissions - destination.setExecutable(source.canExecute()); - destination.setReadable(source.canRead()); - destination.setWritable(source.canWrite()); - } - } - - @SuppressWarnings("ResultOfMethodCallIgnored") - private static void setReadWritePermissions(File file) throws IOException { - if (file.exists()) { - try { - Files.setPosixFilePermissions( - file.toPath(), - EnumSet.of( - PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, - PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE, - PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_WRITE)); - } catch (UnsupportedOperationException e) { - file.setReadable(true); - file.setWritable(true); - } + File sf = source.toFile(); + File df = destination.toFile(); + df.setExecutable(sf.canExecute()); + df.setReadable(sf.canRead()); + df.setWritable(sf.canWrite()); } } diff --git a/src/main/java/org/apache/maven/shared/filtering/MavenFileFilter.java b/src/main/java/org/apache/maven/shared/filtering/MavenFileFilter.java index a68db1d1..f5534470 100644 --- a/src/main/java/org/apache/maven/shared/filtering/MavenFileFilter.java +++ b/src/main/java/org/apache/maven/shared/filtering/MavenFileFilter.java @@ -18,11 +18,11 @@ */ package org.apache.maven.shared.filtering; -import java.io.File; +import java.nio.file.Path; import java.util.List; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; /** * @author Olivier Lamy @@ -35,23 +35,23 @@ public interface MavenFileFilter extends DefaultFilterInfo { * @param from file to copy/filter * @param to destination file * @param filtering enable or not filtering - * @param mavenProject {@link MavenProject} - * @param mavenSession {@link MavenSession} + * @param mavenProject {@link Project} + * @param mavenSession {@link Session} * @param escapedBackslashesInFilePath escape backslashes in file path. * @param filters {@link List} of String which are path to a Property file * @param encoding The encoding which is used during the filtering process. * @throws MavenFilteringException in case of failure. - * @see DefaultFilterInfo#getDefaultFilterWrappers(MavenProject, List, boolean,MavenSession, MavenResourcesExecution) + * @see DefaultFilterInfo#getDefaultFilterWrappers(Project, List, boolean, Session, MavenResourcesExecution) */ void copyFile( - File from, - File to, + Path from, + Path to, boolean filtering, - MavenProject mavenProject, + Project mavenProject, List filters, boolean escapedBackslashesInFilePath, String encoding, - MavenSession mavenSession) + Session mavenSession) throws MavenFilteringException; /** @@ -69,27 +69,6 @@ void copyFile( * @param encoding The encoding used during the filtering. * @throws MavenFilteringException In case of an error. */ - void copyFile(File from, File to, boolean filtering, List filterWrappers, String encoding) - throws MavenFilteringException; - - /** - * @param from The source file - * @param to The destination file - * @param filtering true to apply filtering - * @param filterWrappers The filters to be applied. - * @param encoding The encoding to use - * @param overwrite unused - * @throws MavenFilteringException In case of an error. - * @since 1.0-beta-2 - * @deprecated use {@link #copyFile(File, File, boolean, List, String)} instead - */ - @Deprecated - void copyFile( - File from, - File to, - boolean filtering, - List filterWrappers, - String encoding, - boolean overwrite) + void copyFile(Path from, Path to, boolean filtering, List filterWrappers, String encoding) throws MavenFilteringException; } diff --git a/src/main/java/org/apache/maven/shared/filtering/MavenFileFilterRequest.java b/src/main/java/org/apache/maven/shared/filtering/MavenFileFilterRequest.java index fed57943..af8b1c95 100644 --- a/src/main/java/org/apache/maven/shared/filtering/MavenFileFilterRequest.java +++ b/src/main/java/org/apache/maven/shared/filtering/MavenFileFilterRequest.java @@ -18,12 +18,12 @@ */ package org.apache.maven.shared.filtering; -import java.io.File; +import java.nio.file.Path; import java.util.List; import java.util.Properties; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; /** * @author Olivier Lamy @@ -31,9 +31,9 @@ */ public class MavenFileFilterRequest extends AbstractMavenFilteringRequest { - private File from; + private Path from; - private File to; + private Path to; private boolean filtering; @@ -58,14 +58,14 @@ public MavenFileFilterRequest() { * @param additionalProperties Supplemental properties. */ public MavenFileFilterRequest( - File from, - File to, + Path from, + Path to, boolean filtering, - MavenProject mavenProject, + Project mavenProject, List filters, boolean escapedBackslashesInFilePath, String encoding, - MavenSession mavenSession, + Session mavenSession, Properties additionalProperties) { super(mavenProject, filters, mavenSession); this.encoding = encoding; @@ -97,28 +97,28 @@ public void setEncoding(String encoding) { /** * @return to filter from. */ - public File getFrom() { + public Path getFrom() { return from; } /** * @param from set filter from. */ - public void setFrom(File from) { + public void setFrom(Path from) { this.from = from; } /** * @return The filter to */ - public File getTo() { + public Path getTo() { return to; } /** * @param to Set the target. */ - public void setTo(File to) { + public void setTo(Path to) { this.to = to; } diff --git a/src/main/java/org/apache/maven/shared/filtering/MavenReaderFilter.java b/src/main/java/org/apache/maven/shared/filtering/MavenReaderFilter.java index 1ef03876..efee74cc 100644 --- a/src/main/java/org/apache/maven/shared/filtering/MavenReaderFilter.java +++ b/src/main/java/org/apache/maven/shared/filtering/MavenReaderFilter.java @@ -21,8 +21,8 @@ import java.io.Reader; import java.util.List; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; /** * @author Olivier Lamy @@ -35,22 +35,20 @@ public interface MavenReaderFilter extends DefaultFilterInfo { * * @param from the source reader * @param filtering enable or not filtering - * @param mavenProject {@link MavenProject} - * @param mavenSession {@link MavenSession} + * @param mavenProject {@link Project} + * @param mavenSession {@link Session} * @param filters {@link java.util.List} of String which are path to a Property file * @param escapedBackslashesInFilePath escape backslashes in file path. * @return an input stream that applies the filter * @throws org.apache.maven.shared.filtering.MavenFilteringException in case of failure. - * @see #getDefaultFilterWrappers(org.apache.maven.project.MavenProject, java.util.List, boolean, - * org.apache.maven.execution.MavenSession, org.apache.maven.shared.filtering.MavenResourcesExecution) */ Reader filter( Reader from, boolean filtering, - MavenProject mavenProject, + Project mavenProject, List filters, boolean escapedBackslashesInFilePath, - MavenSession mavenSession) + Session mavenSession) throws MavenFilteringException; /** diff --git a/src/main/java/org/apache/maven/shared/filtering/MavenReaderFilterRequest.java b/src/main/java/org/apache/maven/shared/filtering/MavenReaderFilterRequest.java index e961af2b..864729a4 100644 --- a/src/main/java/org/apache/maven/shared/filtering/MavenReaderFilterRequest.java +++ b/src/main/java/org/apache/maven/shared/filtering/MavenReaderFilterRequest.java @@ -22,8 +22,8 @@ import java.util.List; import java.util.Properties; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; /** * @author Olivier Lamy @@ -55,10 +55,10 @@ public MavenReaderFilterRequest() { public MavenReaderFilterRequest( Reader from, boolean filtering, - MavenProject mavenProject, + Project mavenProject, List filters, boolean escapedBackslashesInFilePath, - MavenSession mavenSession, + Session mavenSession, Properties additionalProperties) { super(mavenProject, filters, mavenSession); this.from = from; diff --git a/src/main/java/org/apache/maven/shared/filtering/MavenResourcesExecution.java b/src/main/java/org/apache/maven/shared/filtering/MavenResourcesExecution.java index 460aeeaf..18e2ff65 100644 --- a/src/main/java/org/apache/maven/shared/filtering/MavenResourcesExecution.java +++ b/src/main/java/org/apache/maven/shared/filtering/MavenResourcesExecution.java @@ -18,14 +18,13 @@ */ package org.apache.maven.shared.filtering; -import java.io.File; import java.io.Reader; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.model.Resource; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.Project; +import org.apache.maven.api.Session; import org.codehaus.plexus.interpolation.StringSearchInterpolator; import org.codehaus.plexus.interpolation.ValueSource; @@ -36,15 +35,15 @@ */ public class MavenResourcesExecution extends AbstractMavenFilteringRequest { - private List resources; + private List resources; - private File outputDirectory; + private Path outputDirectory; private List nonFilteredFileExtensions; private List filterWrappers; - private File resourcesBaseDirectory; + private Path resourcesBaseDirectory; private boolean useDefaultFilterWrappers = false; @@ -133,13 +132,13 @@ public MavenResourcesExecution() { * @param mavenSession The maven session. */ public MavenResourcesExecution( - List resources, - File outputDirectory, - MavenProject mavenProject, + List resources, + Path outputDirectory, + Project mavenProject, String encoding, List fileFilters, List nonFilteredFileExtensions, - MavenSession mavenSession) { + Session mavenSession) { super(mavenProject, fileFilters, mavenSession); this.encoding = encoding; this.resources = resources; @@ -159,11 +158,11 @@ public MavenResourcesExecution( * @param nonFilteredFileExtensions The list of extensions which should not being filtered. */ public MavenResourcesExecution( - List resources, - File outputDirectory, + List resources, + Path outputDirectory, String encoding, List filterWrappers, - File resourcesBaseDirectory, + Path resourcesBaseDirectory, List nonFilteredFileExtensions) { this(); this.resources = resources; @@ -216,28 +215,28 @@ public void setPropertiesEncoding(String propertiesEncoding) { /** * @return List of {@link org.apache.maven.model.Resource} */ - public List getResources() { + public List getResources() { return resources; } /** * @param resources List of {@link org.apache.maven.model.Resource} */ - public void setResources(List resources) { + public void setResources(List resources) { this.resources = resources; } /** * @return The output directory. */ - public File getOutputDirectory() { + public Path getOutputDirectory() { return outputDirectory; } /** * @param outputDirectory The output directory. */ - public void setOutputDirectory(File outputDirectory) { + public void setOutputDirectory(Path outputDirectory) { this.outputDirectory = outputDirectory; } @@ -310,14 +309,14 @@ public Reader getReader(Reader reader) { /** * @return The resource base directory. */ - public File getResourcesBaseDirectory() { + public Path getResourcesBaseDirectory() { return resourcesBaseDirectory; } /** * @param resourcesBaseDirectory Set the resource base directory. */ - public void setResourcesBaseDirectory(File resourcesBaseDirectory) { + public void setResourcesBaseDirectory(Path resourcesBaseDirectory) { this.resourcesBaseDirectory = resourcesBaseDirectory; } diff --git a/src/main/java/org/apache/maven/shared/filtering/PropertyUtils.java b/src/main/java/org/apache/maven/shared/filtering/PropertyUtils.java index e811f665..f5046dfc 100644 --- a/src/main/java/org/apache/maven/shared/filtering/PropertyUtils.java +++ b/src/main/java/org/apache/maven/shared/filtering/PropertyUtils.java @@ -18,11 +18,11 @@ */ package org.apache.maven.shared.filtering; -import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; +import java.nio.file.Path; import java.util.LinkedList; import java.util.List; import java.util.Properties; @@ -55,7 +55,7 @@ private PropertyUtils() { * @return Properties object containing the properties in the file with their values fully resolved. * @throws IOException if profile does not exist, or cannot be read. */ - public static Properties loadPropertyFile(File propFile, Properties baseProps) throws IOException { + public static Properties loadPropertyFile(Path propFile, Properties baseProps) throws IOException { return loadPropertyFile(propFile, baseProps, null); } @@ -74,14 +74,14 @@ public static Properties loadPropertyFile(File propFile, Properties baseProps) t * * @since 3.1.2 */ - public static Properties loadPropertyFile(File propFile, Properties baseProps, Logger logger) throws IOException { - if (!propFile.exists()) { + public static Properties loadPropertyFile(Path propFile, Properties baseProps, Logger logger) throws IOException { + if (!Files.exists(propFile)) { throw new FileNotFoundException(propFile.toString()); } final Properties fileProps = new Properties(); - try (InputStream inStream = Files.newInputStream(propFile.toPath())) { + try (InputStream inStream = Files.newInputStream(propFile)) { fileProps.load(inStream); } @@ -116,7 +116,7 @@ public static Properties loadPropertyFile(File propFile, Properties baseProps, L * @return the loaded and fully resolved Properties object * @throws IOException if profile does not exist, or cannot be read. */ - public static Properties loadPropertyFile(File propfile, boolean fail, boolean useSystemProps) throws IOException { + public static Properties loadPropertyFile(Path propfile, boolean fail, boolean useSystemProps) throws IOException { return loadPropertyFile(propfile, fail, useSystemProps, null); } @@ -132,7 +132,7 @@ public static Properties loadPropertyFile(File propfile, boolean fail, boolean u * * @since 3.1.2 */ - public static Properties loadPropertyFile(File propfile, boolean fail, boolean useSystemProps, Logger logger) + public static Properties loadPropertyFile(Path propfile, boolean fail, boolean useSystemProps, Logger logger) throws IOException { final Properties baseProps = new Properties(); @@ -218,10 +218,10 @@ private static String getPropertyValue(String k, Properties p, Logger logger) { // else prefix the original string with the // resolved property ( so it can be parsed further ) // taking recursion into account. - if (nv == null || k.equals(nk)) { + if (nv == null || nv.equals(k) || k.equals(nk)) { ret.append("${").append(nk).append("}"); } else { - v = nv + v.replace("${" + nk + "}", nv); + v = nv + v; } } } diff --git a/src/main/java/org/apache/maven/shared/filtering/Resource.java b/src/main/java/org/apache/maven/shared/filtering/Resource.java new file mode 100644 index 00000000..c7c2026b --- /dev/null +++ b/src/main/java/org/apache/maven/shared/filtering/Resource.java @@ -0,0 +1,101 @@ +/* + * 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. + */ +package org.apache.maven.shared.filtering; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Olivier Lamy + * @since 2.3 + * + */ +public class Resource { + + List includes; + List excludes; + String directory; + String targetPath; + boolean filtering; + String mergeId; + + public Resource() {} + + public List getIncludes() { + return includes; + } + + public void setIncludes(List includes) { + this.includes = includes; + } + + public List getExcludes() { + return excludes; + } + + public void setExcludes(List excludes) { + this.excludes = excludes; + } + + public String getDirectory() { + return directory; + } + + public void setDirectory(String directory) { + this.directory = directory; + } + + public String getTargetPath() { + return targetPath; + } + + public void setTargetPath(String targetPath) { + this.targetPath = targetPath; + } + + public boolean isFiltering() { + return filtering; + } + + public void setFiltering(boolean filtering) { + this.filtering = filtering; + } + + public String getMergeId() { + return mergeId; + } + + public void setMergeId(String mergeId) { + this.mergeId = mergeId; + } + + public void addInclude(String include) { + if (includes == null) { + includes = new ArrayList<>(); + } + includes.add(include); + } + + public void addExclude(String exclude) { + if (excludes == null) { + excludes = new ArrayList<>(); + } + excludes.add(exclude); + } +} diff --git a/src/test/java/org/apache/maven/shared/filtering/AbstractInterpolatorFilterReaderLineEndingTest.java b/src/test/java/org/apache/maven/shared/filtering/AbstractInterpolatorFilterReaderLineEndingTest.java index e0cbf565..6d5b4e8b 100644 --- a/src/test/java/org/apache/maven/shared/filtering/AbstractInterpolatorFilterReaderLineEndingTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/AbstractInterpolatorFilterReaderLineEndingTest.java @@ -25,28 +25,24 @@ import org.apache.commons.io.IOUtils; import org.codehaus.plexus.interpolation.Interpolator; import org.codehaus.plexus.interpolation.RecursionInterceptor; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; +@ExtendWith(MockitoExtension.class) public abstract class AbstractInterpolatorFilterReaderLineEndingTest { @Mock private Interpolator interpolator; - @BeforeEach - public void onSetup() { - MockitoAnnotations.openMocks(this); - } - @Test - void defaults() throws Exception { + public void testDefaults() throws Exception { when(interpolator.interpolate(eq("${a}"), eq(""), isA(RecursionInterceptor.class))) .thenReturn("DONE_A"); @@ -89,7 +85,7 @@ void defaults() throws Exception { // MSHARED-198: custom delimiters doesn't work as expected @Test - void customDelimiters() throws Exception { + public void testCustomDelimiters() throws Exception { when(interpolator.interpolate(eq("aaaFILTER.a.MEaaa"), eq(""), isA(RecursionInterceptor.class))) .thenReturn("DONE"); when(interpolator.interpolate(eq("abcFILTER.a.MEabc"), eq(""), isA(RecursionInterceptor.class))) @@ -107,7 +103,7 @@ void customDelimiters() throws Exception { // MSHARED-235: reader exceeds readAheadLimit @Test - void markInvalid() throws IOException { + public void testMarkInvalid() throws IOException { try (Reader reader = getAtReader(new StringReader("@\").replace(p,\"]\").replace(q,\""), interpolator, "\\")) { assertEquals("@\").replace(p,\"]\").replace(q,\"", IOUtils.toString(reader)); } diff --git a/src/test/java/org/apache/maven/shared/filtering/AbstractMavenFilteringRequestTest.java b/src/test/java/org/apache/maven/shared/filtering/AbstractMavenFilteringRequestTest.java index 5c91afbb..8f62de4c 100644 --- a/src/test/java/org/apache/maven/shared/filtering/AbstractMavenFilteringRequestTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/AbstractMavenFilteringRequestTest.java @@ -28,32 +28,32 @@ /** * @author Karl Heinz Marbaise khmarbaise@apache.org. */ -class AbstractMavenFilteringRequestTest { +public class AbstractMavenFilteringRequestTest { private AbstractMavenFilteringRequest request = new AbstractMavenFilteringRequest(); private LinkedHashSet delimiters = new LinkedHashSet<>(); @Test - void setDelimitersShouldNotChangeAnythingIfUsingNull() { + public void setDelimitersShouldNotChangeAnythingIfUsingNull() { request.setDelimiters(null, false); assertThat(request.getDelimiters(), Matchers.contains("${*}", "@")); } @Test - void setDelimitersShouldNotChangeAnythingIfUsingEmpty() { + public void setDelimitersShouldNotChangeAnythingIfUsingEmpty() { request.setDelimiters(delimiters, false); assertThat(request.getDelimiters(), Matchers.contains("${*}", "@")); } @Test - void setDelimitersShouldAddOnlyTheGivenDelimiter() { + public void setDelimitersShouldAddOnlyTheGivenDelimiter() { delimiters.add("test"); request.setDelimiters(delimiters, false); assertThat(request.getDelimiters(), Matchers.contains("test")); } @Test - void setDelimitersShouldAddDefaultDelimitersForNullElements() { + public void setDelimitersShouldAddDefaultDelimitersForNullElements() { delimiters.add("test"); delimiters.add(null); delimiters.add("second"); @@ -62,27 +62,27 @@ void setDelimitersShouldAddDefaultDelimitersForNullElements() { } @Test - void setDelimitersShouldAddDefaultDelimitersIfUseDefaultDelimitersIfNullGiven() { + public void setDelimitersShouldAddDefaultDelimitersIfUseDefaultDelimitersIfNullGiven() { request.setDelimiters(null, true); assertThat(request.getDelimiters(), Matchers.contains("${*}", "@")); } @Test - void setDelimitersShouldAddDefaultDelimitersIfUseDefaultDelimitersIfNotNullGiven() { + public void setDelimitersShouldAddDefaultDelimitersIfUseDefaultDelimitersIfNotNullGiven() { LinkedHashSet delimiters = new LinkedHashSet<>(); request.setDelimiters(delimiters, true); assertThat(request.getDelimiters(), Matchers.contains("${*}", "@")); } @Test - void setDelimitersShouldAddDefaultDelimitersIfUseDefaultDelimitersIfSingleElementIsGiven() { + public void setDelimitersShouldAddDefaultDelimitersIfUseDefaultDelimitersIfSingleElementIsGiven() { delimiters.add("test"); request.setDelimiters(delimiters, true); assertThat(request.getDelimiters(), Matchers.contains("${*}", "@", "test")); } @Test - void setDelimitersShouldAddDefaultDelimitersForNullElement() { + public void setDelimitersShouldAddDefaultDelimitersForNullElement() { delimiters.add("test"); delimiters.add(null); delimiters.add("second"); diff --git a/src/test/java/org/apache/maven/shared/filtering/BoundedReaderTest.java b/src/test/java/org/apache/maven/shared/filtering/BoundedReaderTest.java index 3819a22c..87d5d232 100644 --- a/src/test/java/org/apache/maven/shared/filtering/BoundedReaderTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/BoundedReaderTest.java @@ -27,12 +27,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -class BoundedReaderTest { +public class BoundedReaderTest { private final Reader sr = new BufferedReader(new StringReader("01234567890")); @Test - void readTillEnd() throws IOException { + public void readTillEnd() throws IOException { try (BoundedReader mr = new BoundedReader(sr, 3)) { mr.mark(3); mr.read(); @@ -43,7 +43,7 @@ void readTillEnd() throws IOException { } @Test - void readMulti() throws IOException { + public void readMulti() throws IOException { char[] cbuf = new char[4]; for (int i = 0; i < cbuf.length; i++) { cbuf[i] = 'X'; @@ -61,7 +61,7 @@ void readMulti() throws IOException { } @Test - void readMultiWithOffset() throws IOException { + public void readMultiWithOffset() throws IOException { char[] cbuf = new char[4]; for (int i = 0; i < cbuf.length; i++) { @@ -80,7 +80,7 @@ void readMultiWithOffset() throws IOException { } @Test - void resetWorks() throws IOException { + public void resetWorks() throws IOException { try (BoundedReader mr = new BoundedReader(sr, 3)) { mr.read(); mr.read(); @@ -94,7 +94,7 @@ void resetWorks() throws IOException { } @Test - void skipTest() throws IOException { + public void skipTest() throws IOException { try (BoundedReader mr = new BoundedReader(sr, 3)) { mr.skip(2); mr.read(); diff --git a/src/test/java/org/apache/maven/shared/filtering/ConsoleHolder.java b/src/test/java/org/apache/maven/shared/filtering/ConsoleHolder.java deleted file mode 100644 index bf9a2e97..00000000 --- a/src/test/java/org/apache/maven/shared/filtering/ConsoleHolder.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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. - */ -package org.apache.maven.shared.filtering; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; - -/** - * Helping class to capture console input and output for tests. - * - * @author abelsromero - * @since 3.3.2 - */ -class ConsoleHolder { - - private PrintStream originalOut; - private PrintStream originalErr; - - private ByteArrayOutputStream newOut; - private ByteArrayOutputStream newErr; - - private ConsoleHolder() {} - - static ConsoleHolder start() { - final ConsoleHolder holder = new ConsoleHolder(); - - holder.originalOut = System.out; - holder.originalErr = System.err; - - holder.newOut = new DoubleOutputStream(holder.originalOut); - holder.newErr = new DoubleOutputStream(holder.originalErr); - - System.setOut(new PrintStream(holder.newOut)); - System.setErr(new PrintStream(holder.newErr)); - - return holder; - } - - void release() { - System.setOut(originalOut); - System.setOut(originalErr); - } - - String getOutput() { - return new String(newOut.toByteArray()); - } - - String getError() { - return new String(newErr.toByteArray()); - } - - static class DoubleOutputStream extends ByteArrayOutputStream { - - final OutputStream other; - - DoubleOutputStream(final OutputStream os) { - other = os; - } - - @Override - public synchronized void write(final byte[] b, final int off, final int len) { - try { - other.write(b, off, len); - } catch (IOException e) { - throw new RuntimeException(e); - } - super.write(b, off, len); - } - } -} diff --git a/src/test/java/org/apache/maven/shared/filtering/DefaultMavenFileFilterTest.java b/src/test/java/org/apache/maven/shared/filtering/DefaultMavenFileFilterTest.java index b0ca05a5..d7d85fbf 100644 --- a/src/test/java/org/apache/maven/shared/filtering/DefaultMavenFileFilterTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/DefaultMavenFileFilterTest.java @@ -18,12 +18,13 @@ */ package org.apache.maven.shared.filtering; -import javax.inject.Inject; - import java.io.File; import java.io.Reader; import java.io.StringReader; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -31,8 +32,11 @@ import java.util.List; import java.util.Properties; +import jakarta.inject.Inject; import org.apache.commons.io.IOUtils; -import org.apache.maven.project.MavenProject; +import org.apache.maven.api.model.Build; +import org.apache.maven.api.plugin.testing.stubs.ProjectStub; +import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -47,30 +51,32 @@ * */ @PlexusTest -class DefaultMavenFileFilterTest { +public class DefaultMavenFileFilterTest { @Inject - MavenFileFilter mavenFileFilter; + PlexusContainer container; - File to = new File(getBasedir(), "target/reflection-test.properties"); + Path to = Paths.get(getBasedir(), "target/reflection-test.properties"); @BeforeEach - void setUp() throws Exception { - Files.deleteIfExists(to.toPath()); + protected void setUp() throws Exception { + Files.deleteIfExists(to); } @Test - void overwriteFile() throws Exception { - File from = new File(getBasedir(), "src/test/units-files/reflection-test.properties"); + public void testOverwriteFile() throws Exception { + MavenFileFilter mavenFileFilter = container.lookup(MavenFileFilter.class); + + Path from = Paths.get(getBasedir(), "src/test/units-files/reflection-test.properties"); mavenFileFilter.copyFile(from, to, false, null, null); - from = new File(getBasedir(), "src/test/units-files/reflection-test-older.properties"); + from = Paths.get(getBasedir(), "src/test/units-files/reflection-test-older.properties"); // very old file :-) - from.setLastModified(1); + Files.setLastModifiedTime(from, FileTime.fromMillis(1)); - to.setLastModified(System.currentTimeMillis()); + Files.setLastModifiedTime(to, FileTime.fromMillis(System.currentTimeMillis())); mavenFileFilter.copyFile(from, to, false, null, null); @@ -79,13 +85,16 @@ void overwriteFile() throws Exception { } @Test - void nullSafeDefaultFilterWrappers() throws Exception { + public void testNullSafeDefaultFilterWrappers() throws Exception { + MavenFileFilter mavenFileFilter = container.lookup(MavenFileFilter.class); + mavenFileFilter.getDefaultFilterWrappers(null, null, false, null, null); + // shouldn't fail } @Test - void multiFilterFileInheritance() throws Exception { + public void testMultiFilterFileInheritance() throws Exception { DefaultMavenFileFilter mavenFileFilter = new DefaultMavenFileFilter(mock(BuildContext.class)); File testDir = new File(getBasedir(), "src/test/units-files/MSHARED-177"); @@ -98,7 +107,7 @@ void multiFilterFileInheritance() throws Exception { final Properties filterProperties = new Properties(); - mavenFileFilter.loadProperties(filterProperties, new File(getBasedir()), filters, new Properties()); + mavenFileFilter.loadProperties(filterProperties, Paths.get(getBasedir()), filters, new Properties()); assertEquals("first and second", filterProperties.getProperty("third_filter_key")); } @@ -106,12 +115,18 @@ void multiFilterFileInheritance() throws Exception { // MSHARED-161: DefaultMavenFileFilter.getDefaultFilterWrappers loads // filters from the current directory instead of using basedir @Test - void mavenBasedir() throws Exception { + public void testMavenBasedir() throws Exception { + MavenFileFilter mavenFileFilter = container.lookup(MavenFileFilter.class); + AbstractMavenFilteringRequest req = new AbstractMavenFilteringRequest(); req.setFileFilters(Collections.singletonList("src/main/filters/filefilter.properties")); - MavenProject mavenProject = new StubMavenProject(new File("src/test/units-files/MSHARED-161")); - mavenProject.getBuild().setFilters(Collections.singletonList("src/main/filters/buildfilter.properties")); + ProjectStub mavenProject = new ProjectStub(); + mavenProject.setBasedir(Paths.get("src/test/units-files/MSHARED-161")); + List filters = Collections.singletonList("src/main/filters/buildfilter.properties"); + mavenProject.setModel(mavenProject + .getModel() + .withBuild(Build.newBuilder().filters(filters).build())); req.setMavenProject(mavenProject); req.setInjectProjectBuildFilters(true); @@ -124,7 +139,9 @@ void mavenBasedir() throws Exception { // MSHARED-198: custom delimiters doesn't work as expected @Test - void customDelimiters() throws Exception { + public void testCustomDelimiters() throws Exception { + MavenFileFilter mavenFileFilter = container.lookup(MavenFileFilter.class); + AbstractMavenFilteringRequest req = new AbstractMavenFilteringRequest(); Properties additionalProperties = new Properties(); additionalProperties.setProperty("FILTER.a.ME", "DONE"); @@ -142,7 +159,9 @@ void customDelimiters() throws Exception { // MSHARED-199: Filtering doesn't work if 2 delimiters are used on the same line, the first one being left open @Test - void lineWithSingleAtAndExpression() throws Exception { + public void testLineWithSingleAtAndExpression() throws Exception { + MavenFileFilter mavenFileFilter = container.lookup(MavenFileFilter.class); + AbstractMavenFilteringRequest req = new AbstractMavenFilteringRequest(); Properties additionalProperties = new Properties(); additionalProperties.setProperty("foo", "bar"); diff --git a/src/test/java/org/apache/maven/shared/filtering/DefaultMavenReaderFilterTest.java b/src/test/java/org/apache/maven/shared/filtering/DefaultMavenReaderFilterTest.java index 6fe3556b..cb2ab371 100644 --- a/src/test/java/org/apache/maven/shared/filtering/DefaultMavenReaderFilterTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/DefaultMavenReaderFilterTest.java @@ -18,13 +18,13 @@ */ package org.apache.maven.shared.filtering; -import javax.inject.Inject; - import java.io.Reader; import java.io.StringReader; import java.util.Properties; +import jakarta.inject.Inject; import org.apache.commons.io.IOUtils; +import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Test; @@ -34,12 +34,14 @@ * @author Kristian Rosenvold */ @PlexusTest -class DefaultMavenReaderFilterTest { +public class DefaultMavenReaderFilterTest { @Inject - MavenReaderFilter readerFilter; + PlexusContainer container; @Test - void justDoSomeFiltering() throws Exception { + public void testJustDoSomeFiltering() throws Exception { + MavenReaderFilter readerFilter = container.lookup(MavenReaderFilter.class); + StringReader src = new StringReader("toto@titi.com ${foo}"); MavenReaderFilterRequest req = new MavenReaderFilterRequest(); Properties additionalProperties = new Properties(); diff --git a/src/test/java/org/apache/maven/shared/filtering/DefaultMavenResourcesFilteringTest.java b/src/test/java/org/apache/maven/shared/filtering/DefaultMavenResourcesFilteringTest.java index 228fb66e..52244224 100644 --- a/src/test/java/org/apache/maven/shared/filtering/DefaultMavenResourcesFilteringTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/DefaultMavenResourcesFilteringTest.java @@ -18,22 +18,23 @@ */ package org.apache.maven.shared.filtering; -import javax.inject.Inject; - -import java.io.File; -import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Properties; +import java.util.stream.Collectors; +import jakarta.inject.Inject; import org.apache.commons.io.FileUtils; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.model.Resource; -import org.apache.maven.settings.Settings; +import org.apache.maven.api.plugin.testing.stubs.ProjectStub; +import org.apache.maven.api.settings.Settings; +import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.interpolation.PrefixedObjectValueSource; import org.codehaus.plexus.interpolation.ValueSource; import org.codehaus.plexus.testing.PlexusTest; @@ -54,36 +55,35 @@ * @since 1.0-beta-1 */ @PlexusTest -class DefaultMavenResourcesFilteringTest { - - private File outputDirectory = new File(getBasedir(), "target/DefaultMavenResourcesFilteringTest"); - private File baseDir = new File(getBasedir()); - private StubMavenProject mavenProject = new StubMavenProject(baseDir); +public class DefaultMavenResourcesFilteringTest { @Inject + PlexusContainer container; + + private Path outputDirectory = Paths.get(getBasedir(), "target/DefaultMavenResourcesFilteringTest"); + private Path baseDir = Paths.get(getBasedir()); + private ProjectStub mavenProject = new ProjectStub().setBasedir(baseDir); private MavenResourcesFiltering mavenResourcesFiltering; @BeforeEach - void setUp() throws Exception { - if (outputDirectory.exists()) { - FileUtils.deleteDirectory(outputDirectory); - } - outputDirectory.mkdirs(); + protected void setUp() throws Exception { + FileUtils.deleteDirectory(outputDirectory.toFile()); + Files.createDirectories(outputDirectory); mavenProject.setVersion("1.0"); mavenProject.setGroupId("org.apache"); mavenProject.setName("test project"); + + mavenResourcesFiltering = container.lookup(MavenResourcesFiltering.class); } @Test - void simpleFiltering() throws Exception { - Properties projectProperties = new Properties(); - projectProperties.put("foo", "bar"); - projectProperties.put("java.version", "zloug"); - mavenProject.setProperties(projectProperties); + public void testSimpleFiltering() throws Exception { + mavenProject.addProperty("foo", "bar"); + mavenProject.addProperty("java.version", "zloug"); String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; - File initialImageFile = new File(unitFilesDir, "happy_duke.gif"); + Path initialImageFile = Paths.get(unitFilesDir, "happy_duke.gif"); Resource resource = new Resource(); List resources = new ArrayList<>(); @@ -104,7 +104,7 @@ void simpleFiltering() throws Exception { "UTF-8", filtersFile, nonFilteredFileExtensions, - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setUseDefaultFilterWrappers(true); mavenResourcesFiltering.filterResources(mavenResourcesExecution); @@ -112,7 +112,7 @@ void simpleFiltering() throws Exception { } @Test - void sessionFiltering() throws Exception { + public void testSessionFiltering() throws Exception { String unitFilesDir = getBasedir() + "/src/test/units-files/session-filtering"; @@ -124,11 +124,12 @@ void sessionFiltering() throws Exception { List filtersFile = new ArrayList<>(); - Settings settings = new Settings(); - settings.setLocalRepository( - System.getProperty("localRepository", System.getProperty("maven.repo.local", "/path/to/local/repo"))); + Settings settings = Settings.newBuilder() + .localRepository(System.getProperty( + "localRepository", System.getProperty("maven.repo.local", "/path/to/local/repo"))) + .build(); - MavenSession session = new StubMavenSession(settings); + StubSession session = new StubSession(settings); MavenResourcesExecution mre = new MavenResourcesExecution(); mre.setResources(resources); @@ -144,7 +145,7 @@ void sessionFiltering() throws Exception { Properties result = new Properties(); - try (FileInputStream in = new FileInputStream(new File(outputDirectory, "session-filter-target.txt"))) { + try (InputStream in = Files.newInputStream(outputDirectory.resolve("session-filter-target.txt"))) { result.load(in); } @@ -154,14 +155,12 @@ void sessionFiltering() throws Exception { } @Test - void withMavenResourcesExecution() throws Exception { - Properties projectProperties = new Properties(); - projectProperties.put("foo", "bar"); - projectProperties.put("java.version", "zloug"); - mavenProject.setProperties(projectProperties); + public void testWithMavenResourcesExecution() throws Exception { + mavenProject.addProperty("foo", "bar"); + mavenProject.addProperty("java.version", "zloug"); String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; - File initialImageFile = new File(unitFilesDir, "happy_duke.gif"); + Path initialImageFile = Paths.get(unitFilesDir, "happy_duke.gif"); Resource resource = new Resource(); List resources = new ArrayList<>(); @@ -181,21 +180,19 @@ void withMavenResourcesExecution() throws Exception { "UTF-8", filtersFile, nonFilteredFileExtensions, - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setEscapeString("\\"); mavenResourcesFiltering.filterResources(mavenResourcesExecution); assertFiltering(initialImageFile, true, false); } @Test - void withMavenResourcesExecutionWithAdditionalProperties() throws Exception { - Properties projectProperties = new Properties(); - projectProperties.put("foo", "bar"); - projectProperties.put("java.version", "zloug"); - mavenProject.setProperties(projectProperties); + public void testWithMavenResourcesExecutionWithAdditionalProperties() throws Exception { + mavenProject.addProperty("foo", "bar"); + mavenProject.addProperty("java.version", "zloug"); String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; - File initialImageFile = new File(unitFilesDir, "happy_duke.gif"); + Path initialImageFile = Paths.get(unitFilesDir, "happy_duke.gif"); Resource resource = new Resource(); List resources = new ArrayList<>(); @@ -218,20 +215,19 @@ void withMavenResourcesExecutionWithAdditionalProperties() throws Exception { "UTF-8", filtersFile, nonFilteredFileExtensions, - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setAdditionalProperties(additionalProperties); mavenResourcesExecution.setEscapeString("\\"); mavenResourcesFiltering.filterResources(mavenResourcesExecution); assertFiltering(initialImageFile, true, true); } - private void assertFiltering(File initialImageFile, boolean escapeTest, boolean additionalProperties) + private void assertFiltering(Path initialImageFile, boolean escapeTest, boolean additionalProperties) throws Exception { - assertEquals(7, outputDirectory.listFiles().length); + assertEquals(7, list(outputDirectory).size()); Properties result = new Properties(); - try (FileInputStream in = - new FileInputStream(new File(outputDirectory, "empty-maven-resources-filtering.txt"))) { + try (InputStream in = Files.newInputStream(outputDirectory.resolve("empty-maven-resources-filtering.txt"))) { result.load(in); } @@ -239,7 +235,7 @@ private void assertFiltering(File initialImageFile, boolean escapeTest, boolean result = new Properties(); - try (FileInputStream in = new FileInputStream(new File(outputDirectory, "maven-resources-filtering.txt"))) { + try (InputStream in = Files.newInputStream(outputDirectory.resolve("maven-resources-filtering.txt"))) { result.load(in); } @@ -259,37 +255,35 @@ private void assertFiltering(File initialImageFile, boolean escapeTest, boolean assertEquals("${}", result.getProperty("emptyexpression2")); assertEquals(System.getProperty("user.dir"), result.getProperty("userDir")); String userDir = result.getProperty("userDir"); - assertTrue(new File(userDir).exists()); - assertEquals(new File(System.getProperty("user.dir")), new File(userDir)); + assertTrue(Files.exists(Paths.get(userDir))); + assertEquals(Paths.get(System.getProperty("user.dir")), Paths.get(userDir)); assertEquals(System.getProperty("java.version"), result.getProperty("javaVersion")); String userHome = result.getProperty("userHome"); - assertTrue(new File(userHome).exists(), "'" + userHome + "' does not exist."); - assertEquals(new File(System.getProperty("user.home")), new File(userHome)); + assertTrue(Files.exists(Paths.get(userHome)), "'" + userHome + "' does not exist."); + assertEquals(Paths.get(System.getProperty("user.home")), Paths.get(userHome)); if (escapeTest) { assertEquals("${java.version}", result.getProperty("escapeJavaVersion")); assertEquals("@user.dir@", result.getProperty("escapeuserDir")); } - assertEquals(baseDir.toString(), result.get("base")); - assertEquals(new File(baseDir.toString()).getPath(), new File(result.getProperty("base")).getPath()); + assertEquals(baseDir.toString(), result.getProperty("base")); + assertEquals(Paths.get(baseDir.toString()), Paths.get(result.getProperty("base"))); - File imageFile = new File(outputDirectory, "happy_duke.gif"); - assertTrue(imageFile.exists()); + Path imageFile = outputDirectory.resolve("happy_duke.gif"); + assertTrue(Files.exists(imageFile)); // assertEquals( initialImageFile.length(), imageFile.length() ); assertTrue(filesAreIdentical(initialImageFile, imageFile)); } @Test - void addingTokens() throws Exception { - Properties projectProperties = new Properties(); - projectProperties.put("foo", "bar"); - projectProperties.put("java.version", "zloug"); - mavenProject.setProperties(projectProperties); + public void testAddingTokens() throws Exception { + mavenProject.addProperty("foo", "bar"); + mavenProject.addProperty("java.version", "zloug"); String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; - File initialImageFile = new File(unitFilesDir, "happy_duke.gif"); + Path initialImageFile = Paths.get(unitFilesDir, "happy_duke.gif"); Resource resource = new Resource(); List resources = new ArrayList<>(); @@ -304,13 +298,7 @@ void addingTokens() throws Exception { List nonFilteredFileExtensions = Collections.singletonList("gif"); MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution( - resources, - outputDirectory, - mavenProject, - "UTF-8", - null, - nonFilteredFileExtensions, - new StubMavenSession()); + resources, outputDirectory, mavenProject, "UTF-8", null, nonFilteredFileExtensions, new StubSession()); ValueSource vs = new PrefixedObjectValueSource(mavenResourcesExecution.getProjectStartExpressions(), mavenProject, true); @@ -319,17 +307,17 @@ void addingTokens() throws Exception { mavenResourcesFiltering.filterResources(mavenResourcesExecution); Properties result = - PropertyUtils.loadPropertyFile(new File(outputDirectory, "maven-resources-filtering.txt"), null); + PropertyUtils.loadPropertyFile(outputDirectory.resolve("maven-resources-filtering.txt"), null); assertFalse(result.isEmpty()); assertEquals(mavenProject.getName(), result.get("pomName")); assertFiltering(initialImageFile, false, false); } @Test - void noFiltering() throws Exception { + public void testNoFiltering() throws Exception { String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; - File initialImageFile = new File(unitFilesDir, "happy_duke.gif"); + Path initialImageFile = Paths.get(unitFilesDir, "happy_duke.gif"); Resource resource = new Resource(); List resources = new ArrayList<>(); @@ -345,16 +333,16 @@ void noFiltering() throws Exception { mre.setMavenProject(mavenProject); mre.setFilters(null); mre.setNonFilteredFileExtensions(Collections.emptyList()); - mre.setMavenSession(new StubMavenSession()); + mre.setMavenSession(new StubSession()); mavenResourcesFiltering.filterResources(mre); - assertEquals(7, outputDirectory.listFiles().length); + assertEquals(7, list(outputDirectory).size()); Properties result = - PropertyUtils.loadPropertyFile(new File(outputDirectory, "empty-maven-resources-filtering.txt"), null); + PropertyUtils.loadPropertyFile(outputDirectory.resolve("empty-maven-resources-filtering.txt"), null); assertTrue(result.isEmpty()); - result = PropertyUtils.loadPropertyFile(new File(outputDirectory, "maven-resources-filtering.txt"), null); + result = PropertyUtils.loadPropertyFile(outputDirectory.resolve("maven-resources-filtering.txt"), null); assertFalse(result.isEmpty()); assertEquals("${pom.version}", result.get("version")); @@ -362,81 +350,22 @@ void noFiltering() throws Exception { assertEquals("${foo}", result.get("foo")); assertEquals("@@", result.getProperty("emptyexpression")); assertEquals("${}", result.getProperty("emptyexpression2")); - File imageFile = new File(outputDirectory, "happy_duke.gif"); + Path imageFile = outputDirectory.resolve("happy_duke.gif"); assertTrue(filesAreIdentical(initialImageFile, imageFile)); } - @Test - void messageWhenCopyingFromSubDirectory() throws Exception { - - String subDirectory = "src/test/units-files/maven-resources-filtering"; - String unitFilesDir = String.format("%s/%s", getBasedir(), subDirectory); - - assertMessage( - unitFilesDir, - "Copying (\\d)+ resources from " + subDirectory + " to target/DefaultMavenResourcesFilteringTest"); - } - - @Test - void messageWhenCopyingFromBaseDir() throws Exception { - - String unitFilesDir = getBasedir(); - - assertMessage(unitFilesDir, "Copying (\\d)+ resources from . to target/DefaultMavenResourcesFilteringTest"); - } - - private void assertMessage(String directory, String expectedMessagePattern) throws Exception { - Resource resource = new Resource(); - List resources = new ArrayList<>(); - resources.add(resource); - - resource.setDirectory(directory); - resource.setFiltering(false); - - MavenResourcesExecution mre = new MavenResourcesExecution(); - mre.setResources(resources); - mre.setOutputDirectory(outputDirectory); - mre.setEncoding("UTF-8"); - mre.setMavenProject(mavenProject); - mre.setFilters(null); - mre.setNonFilteredFileExtensions(Collections.emptyList()); - mre.setMavenSession(new StubMavenSession()); - - ConsoleHolder console = ConsoleHolder.start(); - - mavenResourcesFiltering.filterResources(mre); - - String output = console.getError(); - String marker = DefaultMavenResourcesFiltering.class.getSimpleName(); - String message = output.substring(output.indexOf(marker) + marker.length() + 3) - .trim() - .replaceAll("\\\\", "/"); - - boolean matches = message.matches(expectedMessagePattern); - assertTrue(matches, "expected: '" + expectedMessagePattern + "' does not match actual: '" + message + "'"); - console.release(); - } - - private static boolean filesAreIdentical(File expected, File current) throws IOException { - if (expected.length() != current.length()) { + private static boolean filesAreIdentical(Path expected, Path current) throws IOException { + if (Files.size(expected) != Files.size(current)) { return false; } - byte[] expectedBuffer = Files.readAllBytes(expected.toPath()); - byte[] currentBuffer = Files.readAllBytes(current.toPath()); - if (expectedBuffer.length != currentBuffer.length) { - return false; - } - for (int i = 0, size = expectedBuffer.length; i < size; i++) { - if (expectedBuffer[i] != currentBuffer[i]) { - return false; - } - } - return true; + byte[] expectedBuffer = Files.readAllBytes(expected); + byte[] currentBuffer = Files.readAllBytes(current); + return Arrays.equals(expectedBuffer, currentBuffer); } @Test - void includeOneFile() throws Exception { + public void testIncludeOneFile() throws Exception { String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; @@ -458,16 +387,16 @@ void includeOneFile() throws Exception { "UTF-8", filtersFile, Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File[] files = outputDirectory.listFiles(); - assertEquals(1, files.length); - assertEquals("includefile.txt", files[0].getName()); + List files = list(outputDirectory); + assertEquals(1, files.size()); + assertEquals("includefile.txt", filename(files.get(0))); } @Test - void includeOneFileAndDirectory() throws Exception { + public void testIncludeOneFileAndDirectory() throws Exception { String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; Resource resource = new Resource(); @@ -489,27 +418,29 @@ void includeOneFileAndDirectory() throws Exception { "UTF-8", filtersFile, Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File[] files = outputDirectory.listFiles(); + List files = list(outputDirectory); assertNotNull(files); - assertEquals(2, files.length); - File includeFile = new File(outputDirectory, "includefile.txt"); - assertTrue(includeFile.exists()); + assertEquals(2, files.size()); + Path includeFile = outputDirectory.resolve("includefile.txt"); + assertTrue(Files.exists(includeFile)); - includeFile = new File(new File(outputDirectory, "includedir"), "include.txt"); - assertTrue(includeFile.exists()); + includeFile = outputDirectory.resolve("includedir/include.txt"); + assertTrue(Files.exists(includeFile)); } @Test - void flattenDirectoryStructure() throws Exception { - File baseDir = new File(getBasedir()); - StubMavenProject mavenProject = new StubMavenProject(baseDir); + public void testFlattenDirectoryStructure() throws Exception { + Path baseDir = Paths.get(getBasedir()); + ProjectStub mavenProject = new ProjectStub().setBasedir(baseDir); mavenProject.setVersion("1.0"); mavenProject.setGroupId("org.apache"); mavenProject.setName("test project"); + MavenResourcesFiltering mavenResourcesFiltering = container.lookup(MavenResourcesFiltering.class); + String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; Resource resource = new Resource(); @@ -531,29 +462,31 @@ void flattenDirectoryStructure() throws Exception { "UTF-8", filtersFile, Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setFlatten(true); mavenResourcesExecution.setOverwrite(true); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File[] files = outputDirectory.listFiles(); + List files = list(outputDirectory); assertNotNull(files); - assertEquals(2, files.length); - File includeFile = new File(outputDirectory, "includefile.txt"); - assertTrue(includeFile.exists()); + assertEquals(2, files.size()); + Path includeFile = outputDirectory.resolve("includefile.txt"); + assertTrue(Files.exists(includeFile)); - includeFile = new File(outputDirectory, "include.txt"); - assertTrue(includeFile.exists()); + includeFile = outputDirectory.resolve("include.txt"); + assertTrue(Files.exists(includeFile)); } @Test - void flattenDirectoryStructureWithoutOverride() throws Exception { - File baseDir = new File(getBasedir()); - StubMavenProject mavenProject = new StubMavenProject(baseDir); + public void testFlattenDirectoryStructureWithoutOverride() throws Exception { + Path baseDir = Paths.get(getBasedir()); + ProjectStub mavenProject = new ProjectStub().setBasedir(baseDir); mavenProject.setVersion("1.0"); mavenProject.setGroupId("org.apache"); mavenProject.setName("test project"); + MavenResourcesFiltering mavenResourcesFiltering = container.lookup(MavenResourcesFiltering.class); + String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; Resource resource = new Resource(); @@ -575,7 +508,7 @@ void flattenDirectoryStructureWithoutOverride() throws Exception { "UTF-8", filtersFile, Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setFlatten(true); mavenResourcesExecution.setOverwrite(false); try { @@ -587,7 +520,7 @@ void flattenDirectoryStructureWithoutOverride() throws Exception { } @Test - void excludeOneFile() throws Exception { + public void testExcludeOneFile() throws Exception { String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; @@ -610,26 +543,26 @@ void excludeOneFile() throws Exception { "UTF-8", filtersFile, Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File[] files = outputDirectory.listFiles(); - assertEquals(5, files.length); - File includeFile = new File(outputDirectory, "includefile.txt"); - assertTrue(includeFile.exists()); + List files = list(outputDirectory); + assertEquals(5, files.size()); + Path includeFile = outputDirectory.resolve("includefile.txt"); + assertTrue(Files.exists(includeFile)); - includeFile = new File(new File(outputDirectory, "includedir"), "include.txt"); - assertTrue(includeFile.exists()); + includeFile = outputDirectory.resolve("includedir/include.txt"); + assertTrue(Files.exists(includeFile)); - File imageFile = new File(outputDirectory, "happy_duke.gif"); - assertFalse(imageFile.exists()); + Path imageFile = outputDirectory.resolve("happy_duke.gif"); + assertFalse(Files.exists(imageFile)); - File excludeDir = new File(outputDirectory, "excludedir"); - assertFalse(excludeDir.exists()); + Path excludeDir = outputDirectory.resolve("excludedir"); + assertFalse(Files.exists(excludeDir)); } @Test - void targetAbsolutePath() throws Exception { + public void testTargetAbsolutePath() throws Exception { String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; @@ -641,14 +574,12 @@ void targetAbsolutePath() throws Exception { resource.addInclude("includ*"); String targetPath = getBasedir() + "/target/testAbsolutePath/"; - File targetPathFile = new File(targetPath); - resource.setTargetPath(targetPathFile.getAbsolutePath()); + Path targetPathFile = Paths.get(targetPath); + resource.setTargetPath(targetPathFile.toAbsolutePath().toString()); + + Files.createDirectories(targetPathFile); + FileUtils.cleanDirectory(targetPathFile.toFile()); - if (!targetPathFile.exists()) { - targetPathFile.mkdirs(); - } else { - FileUtils.cleanDirectory(targetPathFile); - } List filtersFile = new ArrayList<>(); filtersFile.add( getBasedir() + "/src/test/units-files/maven-resources-filtering/empty-maven-resources-filtering.txt"); @@ -660,16 +591,16 @@ void targetAbsolutePath() throws Exception { "UTF-8", filtersFile, Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File[] files = targetPathFile.listFiles(); - assertEquals(1, files.length); - assertEquals("includefile.txt", files[0].getName()); + List files = list(targetPathFile); + assertEquals(1, files.size()); + assertEquals("includefile.txt", filename(files.get(0))); } @Test - void targetPath() throws Exception { + public void testTargetPath() throws Exception { String unitFilesDir = getBasedir() + "/src/test/units-files/maven-resources-filtering"; @@ -691,19 +622,19 @@ void targetPath() throws Exception { "UTF-8", filtersFile, Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File targetPathFile = new File(outputDirectory, "testTargetPath"); + Path targetPathFile = outputDirectory.resolve("testTargetPath"); - File[] files = targetPathFile.listFiles(); - assertEquals(1, files.length); - assertEquals("includefile.txt", files[0].getName()); + List files = list(targetPathFile); + assertEquals(1, files.size()); + assertEquals("includefile.txt", filename(files.get(0))); } @SuppressWarnings("serial") @Test - void emptyDirectories() throws Exception { + public void testEmptyDirectories() throws Exception { List resources = new ArrayList<>(); resources.add(new Resource() { @@ -719,42 +650,46 @@ void emptyDirectories() throws Exception { "UTF-8", Collections.emptyList(), Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setIncludeEmptyDirs(true); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File[] childs = outputDirectory.listFiles(); + List childs = list(outputDirectory); assertNotNull(childs); - assertEquals(3, childs.length); - - for (File file : childs) { - if (file.getName().endsWith("dir1") - || file.getName().endsWith("empty-directory") - || file.getName().endsWith("empty-directory-child")) { - if (file.getName().endsWith("dir1")) { - assertEquals(1, file.list().length); - assertTrue(file.listFiles()[0].getName().endsWith("foo.txt")); + assertEquals(3, childs.size()); + + for (Path file : childs) { + String filename = filename(file); + if (filename.endsWith("dir1") + || filename.endsWith("empty-directory") + || filename.endsWith("empty-directory-child")) { + if (filename.endsWith("dir1")) { + assertEquals(1, list(file).size()); + assertTrue(filename(list(file).get(0)).endsWith("foo.txt")); } - if (file.getName().endsWith("empty-directory")) { - assertEquals(0, file.list().length); + if (filename.endsWith("empty-directory")) { + assertEquals(0, list(file).size()); } - if (file.getName().endsWith("empty-directory-child")) { - assertEquals(1, file.list().length); - assertTrue(file.listFiles()[0].isDirectory()); - assertEquals(0, file.listFiles()[0].listFiles().length); + if (filename.endsWith("empty-directory-child")) { + assertEquals(1, list(file).size()); + assertTrue(Files.isDirectory(list(file).get(0))); + assertEquals(0, list(list(file).get(0)).size()); } } else { - fail("unknow child file found " + file.getName()); + fail("unknow child file found " + file.getFileName()); } } } @SuppressWarnings("serial") @Test - void shouldReturnGitIgnoreFiles() throws Exception { + public void testShouldReturnGitIgnoreFiles() throws Exception { createTestDataStructure(); - File outputDirectory = new File(getBasedir(), "/target/testGitIgnoreFile"); + Path outputDirectory = Paths.get(getBasedir(), "target/testGitIgnoreFile"); + + FileUtils.deleteDirectory(outputDirectory.toFile()); + Files.createDirectories(outputDirectory); List resources = new ArrayList<>(); resources.add(new Resource() { @@ -768,39 +703,40 @@ void shouldReturnGitIgnoreFiles() throws Exception { outputDirectory, mavenProject, "UTF-8", - Collections.emptyList(), - Collections.emptyList(), - new StubMavenSession()); + Collections.emptyList(), + Collections.emptyList(), + new StubSession()); mavenResourcesExecution.setIncludeEmptyDirs(true); mavenResourcesExecution.setAddDefaultExcludes(false); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File[] children = outputDirectory.listFiles(); + List children = list(outputDirectory); assertNotNull(children); - assertEquals(3, children.length); - - for (File file : children) { - if (file.getName().endsWith("dir1") - || file.getName().endsWith("empty-directory") - || file.getName().endsWith("empty-directory-child")) { - if (file.getName().endsWith("dir1")) { - assertEquals(1, file.list().length); - assertTrue(file.listFiles()[0].getName().endsWith("foo.txt")); + assertEquals(3, children.size()); + + for (Path file : children) { + String filename = filename(file); + if (filename.endsWith("dir1") + || filename.endsWith("empty-directory") + || filename.endsWith("empty-directory-child")) { + if (filename.endsWith("dir1")) { + assertEquals(1, list(file).size()); + assertTrue(filename(list(file).get(0)).endsWith("foo.txt")); } - if (file.getName().endsWith("empty-directory")) { + if (filename.endsWith("empty-directory")) { - assertEquals(1, file.list().length); - assertTrue(file.listFiles()[0].getName().endsWith(".gitignore")); + assertEquals(1, list(file).size()); + assertTrue(filename(list(file).get(0)).endsWith(".gitignore")); } - if (file.getName().endsWith("empty-directory-child")) { - assertEquals(1, file.list().length); - assertTrue(file.listFiles()[0].isDirectory()); - assertEquals(1, file.listFiles()[0].listFiles().length); + if (filename.endsWith("empty-directory-child")) { + assertEquals(1, list(file).size()); + assertTrue(Files.isDirectory(list(file).get(0))); + assertEquals(1, list(list(file).get(0)).size()); - assertTrue(file.listFiles()[0].listFiles()[0].getName().endsWith(".gitignore")); + assertTrue(filename(list(list(file).get(0)).get(0)).endsWith(".gitignore")); } } else { - fail("unknown child file found " + file.getName()); + fail("unknown child file found " + file.getFileName()); } } } @@ -810,28 +746,28 @@ void shouldReturnGitIgnoreFiles() throws Exception { * copy the structure which does not work. */ private static void createTestDataStructure() throws IOException { - File sourceDirectory = new File(getBasedir(), "/target/sourceTestGitIgnoreFile"); - if (sourceDirectory.exists()) { - FileUtils.forceDelete(sourceDirectory); + Path sourceDirectory = Paths.get(getBasedir(), "/target/sourceTestGitIgnoreFile"); + if (Files.exists(sourceDirectory)) { + FileUtils.forceDelete(sourceDirectory.toFile()); } - File dir1 = new File(sourceDirectory, "dir1"); + Path dir1 = sourceDirectory.resolve("dir1"); - dir1.mkdirs(); - FileUtils.write(new File(dir1, "foo.txt"), "This is a Test File", "UTF-8"); + Files.createDirectories(dir1); + FileUtils.write(dir1.resolve("foo.txt").toFile(), "This is a Test Path", "UTF-8"); - File emptyDirectory = new File(sourceDirectory, "empty-directory"); - emptyDirectory.mkdirs(); + Path emptyDirectory = sourceDirectory.resolve("empty-directory"); + Files.createDirectories(emptyDirectory); - FileUtils.write(new File(emptyDirectory, ".gitignore"), "# .gitignore file", "UTF-8"); + FileUtils.write(emptyDirectory.resolve(".gitignore").toFile(), "# .gitignore file", "UTF-8"); - File emptyDirectoryChild = new File(sourceDirectory, "empty-directory-child"); - emptyDirectory.mkdirs(); + Path emptyDirectoryChild = sourceDirectory.resolve("empty-directory-child"); + Files.createDirectories(emptyDirectory); - File emptyDirectoryChildEmptyChild = new File(emptyDirectoryChild, "empty-child"); - emptyDirectoryChildEmptyChild.mkdirs(); + Path emptyDirectoryChildEmptyChild = emptyDirectoryChild.resolve("empty-child"); + Files.createDirectories(emptyDirectoryChildEmptyChild); - FileUtils.write(new File(emptyDirectoryChildEmptyChild, ".gitignore"), "# .gitignore file", "UTF-8"); + FileUtils.write(emptyDirectoryChildEmptyChild.resolve(".gitignore").toFile(), "# .gitignore file", "UTF-8"); } /** @@ -839,7 +775,7 @@ private static void createTestDataStructure() throws IOException { */ @SuppressWarnings("serial") @Test - void mSHARED81() throws Exception { + public void testMSHARED81() throws Exception { mavenProject.addProperty("escaped", "this is escaped"); mavenProject.addProperty("escaped.at", "this is escaped.at"); mavenProject.addProperty("foo", "this is foo"); @@ -858,31 +794,31 @@ void mSHARED81() throws Exception { setFiltering(true); } }); - File output = new File(outputDirectory, "MSHARED-81"); + Path output = outputDirectory.resolve("MSHARED-81"); MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution( resources, output, mavenProject, "UTF-8", - Collections.emptyList(), - Collections.emptyList(), - new StubMavenSession()); + Collections.emptyList(), + Collections.emptyList(), + new StubSession()); mavenResourcesExecution.setIncludeEmptyDirs(true); mavenResourcesExecution.setEscapeString("\\"); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - Properties filteredResult = PropertyUtils.loadPropertyFile(new File(output, "filtered.properties"), null); + Properties filteredResult = PropertyUtils.loadPropertyFile(output.resolve("filtered.properties"), null); Properties expectedFilteredResult = PropertyUtils.loadPropertyFile( - new File(getBasedir() + "/src/test/units-files/MSHARED-81", "expected-filtered.properties"), null); + Paths.get(getBasedir() + "/src/test/units-files/MSHARED-81", "expected-filtered.properties"), null); assertEquals(expectedFilteredResult, filteredResult); - Properties nonFilteredResult = PropertyUtils.loadPropertyFile(new File(output, "unfiltered.properties"), null); + Properties nonFilteredResult = PropertyUtils.loadPropertyFile(output.resolve("unfiltered.properties"), null); Properties expectedNonFilteredResult = PropertyUtils.loadPropertyFile( - new File(getBasedir() + "/src/test/units-files/MSHARED-81/resources", "unfiltered.properties"), null); + Paths.get(getBasedir() + "/src/test/units-files/MSHARED-81/resources", "unfiltered.properties"), null); assertEquals(nonFilteredResult, expectedNonFilteredResult); } @@ -890,6 +826,7 @@ void mSHARED81() throws Exception { /** * unit test for MRESOURCES-230 : https://issues.apache.org/jira/browse/MRESOURCES-230 */ + // @Test // public void testCorrectlyEscapesEscapeString() // throws Exception // { @@ -908,19 +845,19 @@ void mSHARED81() throws Exception { // } ); // resources.get( 0 ).addExclude( "expected.txt" ); // - // File output = new File( outputDirectory, "MRESOURCES-230" ); + // Path output = outputDirectory.resolve( "MRESOURCES-230" ); // MavenResourcesExecution mavenResourcesExecution = // new MavenResourcesExecution( resources, output, mavenProject, "UTF-8", // Collections.emptyList(), - // Collections.emptyList(), new StubMavenSession() ); + // Collections.emptyList(), new StubSession() ); // mavenResourcesExecution.setIncludeEmptyDirs( true ); // mavenResourcesExecution.setEscapeString( "\\" ); // // mavenResourcesFiltering.filterResources( mavenResourcesExecution ); // - // final String filtered = FileUtils.fileRead( new File( output, "resource.txt" ), "UTF-8" ); + // final String filtered = FileUtils.fileRead( output.resolve( "resource.txt" ), "UTF-8" ); // final String expected = - // FileUtils.fileRead( new File( getBasedir() + "/src/test/units-files/MRESOURCES-230/expected.txt" ) ); + // FileUtils.fileRead( Paths.get( getBasedir() + "/src/test/units-files/MRESOURCES-230/expected.txt" ) ); // // assertEquals( expected, filtered ); // } @@ -928,9 +865,8 @@ void mSHARED81() throws Exception { /** * unit test for edge cases : https://issues.apache.org/jira/browse/MSHARED-228 */ - @SuppressWarnings("serial") @Test - void edgeCases() throws Exception { + public void testEdgeCases() throws Exception { mavenProject.addProperty("escaped", "this is escaped"); mavenProject.addProperty("escaped.at", "this is escaped.at"); mavenProject.addProperty("foo", "this is foo"); @@ -953,7 +889,7 @@ void edgeCases() throws Exception { setFiltering(true); } }); - File output = new File(outputDirectory, "edge-cases"); + Path output = outputDirectory.resolve("edge-cases"); MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution( resources, output, @@ -961,30 +897,30 @@ void edgeCases() throws Exception { "UTF-8", Collections.emptyList(), Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setIncludeEmptyDirs(true); mavenResourcesExecution.setEscapeString("\\"); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - Properties filteredResult = PropertyUtils.loadPropertyFile(new File(output, "filtered.properties"), null); + Properties filteredResult = PropertyUtils.loadPropertyFile(output.resolve("filtered.properties"), null); Properties expectedFilteredResult = PropertyUtils.loadPropertyFile( - new File(getBasedir() + "/src/test/units-files/edge-cases", "expected-filtered.properties"), null); + Paths.get(getBasedir() + "/src/test/units-files/edge-cases", "expected-filtered.properties"), null); assertEquals(expectedFilteredResult, filteredResult); - Properties nonFilteredResult = PropertyUtils.loadPropertyFile(new File(output, "unfiltered.properties"), null); + Properties nonFilteredResult = PropertyUtils.loadPropertyFile(output.resolve("unfiltered.properties"), null); Properties expectedNonFilteredResult = PropertyUtils.loadPropertyFile( - new File(getBasedir() + "/src/test/units-files/edge-cases/resources", "unfiltered.properties"), null); + Paths.get(getBasedir() + "/src/test/units-files/edge-cases/resources", "unfiltered.properties"), null); - assertEquals(nonFilteredResult, expectedNonFilteredResult); + assertTrue(nonFilteredResult.equals(expectedNonFilteredResult)); } // MSHARED-220: Apply filtering to filenames @Test - void filterFileName() throws Exception { + public void testFilterFileName() throws Exception { String unitFilesDir = getBasedir() + "/src/test/units-files/maven-filename-filtering"; @@ -1001,22 +937,22 @@ void filterFileName() throws Exception { "UTF-8", Collections.emptyList(), Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setFilterFilenames(true); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File targetPathFile = new File(outputDirectory, "testTargetPath"); + Path targetPathFile = outputDirectory.resolve("testTargetPath"); - File[] files = targetPathFile.listFiles(); - assertEquals(1, files.length); - assertEquals("1.0.txt", files[0].getName()); + List files = list(targetPathFile); + assertEquals(1, files.size()); + assertEquals("1.0.txt", filename(files.get(0))); } /** * MRESOURCES-171: Use correct encoding when filtering properties-files */ @Test - void filterPropertiesFiles() throws Exception { + public void testFilterPropertiesFiles() throws Exception { String unitFilesDir = getBasedir() + "/src/test/units-files/MRESOURCES-171"; @@ -1032,20 +968,20 @@ void filterPropertiesFiles() throws Exception { "UTF-8", Collections.emptyList(), Collections.emptyList(), - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setPropertiesEncoding("ISO-8859-1"); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File targetPathFile = new File(outputDirectory, "testFilterPropertiesFiles"); - assertTrue(FileUtils.contentEquals( - new File(unitFilesDir, "test.properties"), new File(targetPathFile, "test.properties"))); - assertTrue(FileUtils.contentEquals(new File(unitFilesDir, "test.txt"), new File(targetPathFile, "test.txt"))); + Path targetPathFile = outputDirectory.resolve("testFilterPropertiesFiles"); + assertTrue( + contentEquals(Paths.get(unitFilesDir, "test.properties"), targetPathFile.resolve("test.properties"))); + assertTrue(contentEquals(Paths.get(unitFilesDir, "test.txt"), targetPathFile.resolve("test.txt"))); } @Test - void getEncoding() { - File propertiesFile = new File("file.properties"); - File regularFile = new File("file.xml"); + public void testGetEncoding() { + Path propertiesFile = Paths.get("file.properties"); + Path regularFile = Paths.get("file.xml"); // Properties files assertNull(DefaultMavenResourcesFiltering.getEncoding(propertiesFile, null, null)); @@ -1058,14 +994,26 @@ void getEncoding() { } @Test - void isPropertiesFile() { + public void testIsPropertiesFile() { // Properties files - assertTrue(DefaultMavenResourcesFiltering.isPropertiesFile(new File("file.properties"))); - assertTrue(DefaultMavenResourcesFiltering.isPropertiesFile(new File("some/parent/path", "file.properties"))); + assertTrue(DefaultMavenResourcesFiltering.isPropertiesFile(Paths.get("file.properties"))); + assertTrue(DefaultMavenResourcesFiltering.isPropertiesFile(Paths.get("some/parent/path", "file.properties"))); // Regular files - assertFalse(DefaultMavenResourcesFiltering.isPropertiesFile(new File("file"))); - assertFalse(DefaultMavenResourcesFiltering.isPropertiesFile(new File("some/parent/path", "file"))); - assertFalse(DefaultMavenResourcesFiltering.isPropertiesFile(new File("file.xml"))); - assertFalse(DefaultMavenResourcesFiltering.isPropertiesFile(new File("some/parent/path", "file.xml"))); + assertFalse(DefaultMavenResourcesFiltering.isPropertiesFile(Paths.get("file"))); + assertFalse(DefaultMavenResourcesFiltering.isPropertiesFile(Paths.get("some/parent/path", "file"))); + assertFalse(DefaultMavenResourcesFiltering.isPropertiesFile(Paths.get("file.xml"))); + assertFalse(DefaultMavenResourcesFiltering.isPropertiesFile(Paths.get("some/parent/path", "file.xml"))); + } + + private String filename(Path file) { + return file.getFileName().toString(); + } + + private List list(Path file) throws IOException { + return Files.list(file).collect(Collectors.toList()); + } + + private boolean contentEquals(Path p1, Path p2) throws IOException { + return FileUtils.contentEquals(p1.toFile(), p2.toFile()); } } diff --git a/src/test/java/org/apache/maven/shared/filtering/EscapeStringTest.java b/src/test/java/org/apache/maven/shared/filtering/EscapeStringTest.java index 768baba9..a3d8d418 100644 --- a/src/test/java/org/apache/maven/shared/filtering/EscapeStringTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/EscapeStringTest.java @@ -18,17 +18,18 @@ */ package org.apache.maven.shared.filtering; -import javax.inject.Inject; - -import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.Properties; +import jakarta.inject.Inject; import org.apache.commons.io.FileUtils; -import org.apache.maven.model.Resource; +import org.apache.maven.api.plugin.testing.stubs.ProjectStub; +import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,41 +41,38 @@ * @author Olivier Lamy */ @PlexusTest -class EscapeStringTest { +public class EscapeStringTest { @Inject - MavenResourcesFiltering mavenResourcesFiltering; + PlexusContainer container; - File outputDirectory = new File(getBasedir(), "target/EscapeStringTest"); + Path outputDirectory = Paths.get(getBasedir(), "target/EscapeStringTest"); - File unitDirectory = new File(getBasedir(), "src/test/units-files/escape-remove-char"); + Path unitDirectory = Paths.get(getBasedir(), "src/test/units-files/escape-remove-char"); @BeforeEach - void setUp() throws Exception { - if (outputDirectory.exists()) { - FileUtils.deleteDirectory(outputDirectory); - } - outputDirectory.mkdirs(); + protected void setUp() throws Exception { + FileUtils.deleteDirectory(outputDirectory.toFile()); + Files.createDirectories(outputDirectory); } @Test - void escape() throws Exception { - File baseDir = new File(getBasedir()); - StubMavenProject mavenProject = new StubMavenProject(baseDir); + public void testEscape() throws Exception { + Path baseDir = Paths.get(getBasedir()); + ProjectStub mavenProject = new ProjectStub().setBasedir(baseDir); mavenProject.setVersion("1.0"); mavenProject.setGroupId("org.apache"); mavenProject.setName("test project"); - Properties projectProperties = new Properties(); - projectProperties.put("foo", "bar"); - projectProperties.put("java.version", "zloug"); - projectProperties.put("replaceThis", "I am the replacement"); - mavenProject.setProperties(projectProperties); + mavenProject.addProperty("foo", "bar"); + mavenProject.addProperty("java.version", "zloug"); + mavenProject.addProperty("replaceThis", "I am the replacement"); + MavenResourcesFiltering mavenResourcesFiltering = container.lookup(MavenResourcesFiltering.class); Resource resource = new Resource(); List resources = new ArrayList<>(); resources.add(resource); - resource.setDirectory(unitDirectory.getPath()); + resource.setDirectory(unitDirectory.toString()); resource.setFiltering(true); List filtersFile = new ArrayList<>(); @@ -88,15 +86,15 @@ void escape() throws Exception { "UTF-8", filtersFile, nonFilteredFileExtensions, - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setUseDefaultFilterWrappers(true); mavenResourcesExecution.setEscapeString("!"); mavenResourcesFiltering.filterResources(mavenResourcesExecution); - File file = new File(outputDirectory, "content.xml"); - String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8); + Path file = outputDirectory.resolve("content.xml"); + String content = FileUtils.readFileToString(file.toFile(), StandardCharsets.UTF_8); assertTrue(content.contains("Content with replacement: I am the replacement !")); assertTrue( content.contains("Content with escaped replacement: Do not ${replaceThis} !")); diff --git a/src/test/java/org/apache/maven/shared/filtering/FilteringUtilsTest.java b/src/test/java/org/apache/maven/shared/filtering/FilteringUtilsTest.java index 5392b3d4..18fb5968 100644 --- a/src/test/java/org/apache/maven/shared/filtering/FilteringUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/FilteringUtilsTest.java @@ -18,19 +18,18 @@ */ package org.apache.maven.shared.filtering; -import java.io.File; import java.io.IOException; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.nio.file.StandardCopyOption; -import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Test; import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author John Casey @@ -38,15 +37,14 @@ * @since 1.0 * */ -@PlexusTest -class FilteringUtilsTest { - private static File testDirectory = new File(getBasedir(), "target/test-classes/"); +public class FilteringUtilsTest { + private static Path testDirectory = Paths.get(getBasedir(), "target/test-classes/"); @Test - void mSHARED1213CopyWithTargetAlreadyExisting0ByteFile() throws IOException { - File fromFile = new File(getBasedir() + "/src/test/units-files/MSHARED-1213/enunciate.xml"); - File toFile = new File(testDirectory, "MSHARED-1213-enunciate.xml"); - Files.write(toFile.toPath(), "".getBytes(StandardCharsets.UTF_8)); + public void testMSHARED1213CopyWithTargetAlreadyExisting0ByteFile() throws IOException { + Path fromFile = Paths.get(getBasedir() + "/src/test/units-files/MSHARED-1213/enunciate.xml"); + Path toFile = testDirectory.resolve("MSHARED-1213-enunciate.xml"); + Files.write(toFile, "".getBytes(StandardCharsets.UTF_8)); FilteringUtils.copyFile( fromFile, toFile, @@ -61,15 +59,15 @@ public Reader getReader(Reader fileReader) { }, false); assertEquals( - Files.readAllLines(fromFile.toPath(), StandardCharsets.UTF_8), - Files.readAllLines(toFile.toPath(), StandardCharsets.UTF_8)); + Files.readAllLines(fromFile, StandardCharsets.UTF_8), + Files.readAllLines(toFile, StandardCharsets.UTF_8)); } @Test - void mSHARED1213CopyWithTargetAlreadyExistingJunkFile() throws IOException { - File fromFile = new File(getBasedir() + "/src/test/units-files/MSHARED-1213/enunciate.xml"); - File toFile = new File(testDirectory, "MSHARED-1213-enunciate.xml"); - Files.write(toFile.toPath(), "junk".getBytes(StandardCharsets.UTF_8)); + public void testMSHARED1213CopyWithTargetAlreadyExistingJunkFile() throws IOException { + Path fromFile = Paths.get(getBasedir() + "/src/test/units-files/MSHARED-1213/enunciate.xml"); + Path toFile = testDirectory.resolve("MSHARED-1213-enunciate.xml"); + Files.write(toFile, "junk".getBytes(StandardCharsets.UTF_8)); FilteringUtils.copyFile( fromFile, toFile, @@ -84,15 +82,15 @@ public Reader getReader(Reader fileReader) { }, false); assertEquals( - Files.readAllLines(fromFile.toPath(), StandardCharsets.UTF_8), - Files.readAllLines(toFile.toPath(), StandardCharsets.UTF_8)); + Files.readAllLines(fromFile, StandardCharsets.UTF_8), + Files.readAllLines(toFile, StandardCharsets.UTF_8)); } @Test - void mSHARED1213CopyWithTargetAlreadyExistingSameFile() throws IOException { - File fromFile = new File(getBasedir() + "/src/test/units-files/MSHARED-1213/enunciate.xml"); - File toFile = new File(testDirectory, "MSHARED-1213-enunciate.xml"); - Files.copy(fromFile.toPath(), toFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + public void testMSHARED1213CopyWithTargetAlreadyExistingSameFile() throws IOException { + Path fromFile = Paths.get(getBasedir() + "/src/test/units-files/MSHARED-1213/enunciate.xml"); + Path toFile = testDirectory.resolve("MSHARED-1213-enunciate.xml"); + Files.copy(fromFile, toFile, StandardCopyOption.REPLACE_EXISTING); FilteringUtils.copyFile( fromFile, toFile, @@ -107,22 +105,22 @@ public Reader getReader(Reader fileReader) { }, false); assertEquals( - Files.readAllLines(fromFile.toPath(), StandardCharsets.UTF_8), - Files.readAllLines(toFile.toPath(), StandardCharsets.UTF_8)); + Files.readAllLines(fromFile, StandardCharsets.UTF_8), + Files.readAllLines(toFile, StandardCharsets.UTF_8)); } @Test - void escapeWindowsPathStartingWithDrive() { + public void testEscapeWindowsPathStartingWithDrive() { assertEquals("C:\\\\Users\\\\Administrator", FilteringUtils.escapeWindowsPath("C:\\Users\\Administrator")); } @Test - void escapeWindowsPathMissingDriveLetter() { + public void testEscapeWindowsPathMissingDriveLetter() { assertEquals(":\\Users\\Administrator", FilteringUtils.escapeWindowsPath(":\\Users\\Administrator")); } @Test - void escapeWindowsPathInvalidDriveLetter() { + public void testEscapeWindowsPathInvalidDriveLetter() { assertEquals("4:\\Users\\Administrator", FilteringUtils.escapeWindowsPath("4:\\Users\\Administrator")); } @@ -144,25 +142,9 @@ void escapeWindowsPathInvalidDriveLetter() { // MSHARED-179 @Test - void escapeWindowsPathNotAtBeginning() throws Exception { + public void testEscapeWindowsPathNotAtBeginning() throws Exception { assertEquals( "jdbc:derby:C:\\\\Users\\\\Administrator/test;create=true", FilteringUtils.escapeWindowsPath("jdbc:derby:C:\\Users\\Administrator/test;create=true")); } - - // MSHARED-1330 - @Test - void copyReadOnlyFileTwice() throws Exception { - File temp = File.createTempFile("pre-", ".txt"); - temp.setReadOnly(); - - File out = File.createTempFile("out-", ".txt"); - out.delete(); - - FilteringUtils.copyFile(temp, out, "UTF-8", new FilterWrapper[0]); - assertFalse(out.canWrite()); - - FilteringUtils.copyFile(temp, out, "UTF-8", new FilterWrapper[0]); - assertFalse(out.canWrite()); - } } diff --git a/src/test/java/org/apache/maven/shared/filtering/IncrementalResourceFilteringTest.java b/src/test/java/org/apache/maven/shared/filtering/IncrementalResourceFilteringTest.java index ed3b91e5..fbe36421 100644 --- a/src/test/java/org/apache/maven/shared/filtering/IncrementalResourceFilteringTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/IncrementalResourceFilteringTest.java @@ -18,13 +18,11 @@ */ package org.apache.maven.shared.filtering; -import javax.inject.Inject; - -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -32,8 +30,10 @@ import java.util.Properties; import java.util.Set; +import jakarta.inject.Inject; import org.apache.commons.io.FileUtils; -import org.apache.maven.model.Resource; +import org.apache.maven.api.plugin.testing.stubs.ProjectStub; +import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,12 +45,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @PlexusTest -class IncrementalResourceFilteringTest { - - @Inject - MavenResourcesFiltering mavenResourcesFiltering; +public class IncrementalResourceFilteringTest { - Path baseDirectory = new File(getBasedir()).toPath(); + Path baseDirectory = Paths.get(getBasedir()); Path outputDirectory = baseDirectory.resolve("target/IncrementalResourceFilteringTest"); Path unitDirectory = baseDirectory.resolve("src/test/units-files/incremental"); Path filters = unitDirectory.resolve("filters.txt"); @@ -59,16 +56,17 @@ class IncrementalResourceFilteringTest { Path outputFile01 = outputDirectory.resolve("file01.txt"); Path outputFile02 = outputDirectory.resolve("file02.txt"); + @Inject + PlexusContainer container; + @BeforeEach - void setUp() throws Exception { - if (outputDirectory.toFile().exists()) { - FileUtils.deleteDirectory(outputDirectory.toFile()); - } - outputDirectory.toFile().mkdirs(); + protected void setUp() throws Exception { + FileUtils.deleteDirectory(outputDirectory.toFile()); + Files.createDirectories(outputDirectory); } @Test - void simpleIncrementalFiltering() throws Exception { + public void testSimpleIncrementalFiltering() throws Exception { // run full build first filter("time"); @@ -103,7 +101,7 @@ void simpleIncrementalFiltering() throws Exception { } @Test - void outputChange() throws Exception { + public void testOutputChange() throws Exception { // run full build first filter("time"); @@ -122,7 +120,7 @@ void outputChange() throws Exception { } @Test - void filterChange() throws Exception { + public void testFilterChange() throws Exception { // run full build first filter("time"); @@ -140,59 +138,8 @@ void filterChange() throws Exception { assertTrue(ctx.getRefreshFiles().contains(outputFile02)); } - /** - * Check that missing targets are rebuilt even if source is not changed (MSHARED-1285) - */ - @Test - void missingTarget() throws Exception { - // run full build first - filter("time"); - - // erase target files - outputFile01.toFile().delete(); - outputFile02.toFile().delete(); - // report change only on one file - Set changedFiles = new HashSet<>(); - changedFiles.add(inputFile01); - TestIncrementalBuildContext ctx = new TestIncrementalBuildContext(baseDirectory, changedFiles); - ThreadBuildContext.setThreadBuildContext(ctx); - - filter("time"); - - assertTrue(ctx.getRefreshFiles().contains(outputFile01)); - assertTrue(ctx.getRefreshFiles().contains(outputFile02)); - assertTrue(outputFile01.toFile().exists()); - assertTrue(outputFile02.toFile().exists()); - } - - /** - * Check that updated targets with unchanged sources are updated (MSHARED-1285) - */ - @Test - void updatedTarget() throws Exception { - // run full build first - filter("time"); - - // touch target file02 - FileUtils.touch(outputFile02.toFile()); - Set changedFiles = new HashSet<>(); - changedFiles.add(inputFile01); - // report change only on target file - changedFiles.add(outputFile02); - TestIncrementalBuildContext ctx = new TestIncrementalBuildContext(baseDirectory, changedFiles); - ThreadBuildContext.setThreadBuildContext(ctx); - - // both files are updated - filter("notime"); - assertTime("notime", "file01.txt"); - assertTime("notime", "file02.txt"); - - assertTrue(ctx.getRefreshFiles().contains(outputFile01)); - assertTrue(ctx.getRefreshFiles().contains(outputFile02)); - } - @Test - void filterDeleted() throws Exception { + public void testFilterDeleted() throws Exception { // run full build first filter("time"); @@ -213,8 +160,7 @@ void filterDeleted() throws Exception { private void assertTime(String time, String relpath) throws IOException { Properties properties = new Properties(); - try (InputStream is = - Files.newInputStream(outputDirectory.resolve(relpath).toFile().toPath())) { + try (InputStream is = Files.newInputStream(outputDirectory.resolve(relpath))) { properties.load(is); } @@ -222,16 +168,15 @@ private void assertTime(String time, String relpath) throws IOException { } private void filter(String time) throws Exception { - File baseDir = new File(getBasedir()); - StubMavenProject mavenProject = new StubMavenProject(baseDir); + Path baseDir = Paths.get(getBasedir()); + ProjectStub mavenProject = new ProjectStub().setBasedir(baseDir); mavenProject.setVersion("1.0"); mavenProject.setGroupId("org.apache"); mavenProject.setName("test project"); - Properties projectProperties = new Properties(); - projectProperties.put("time", time); - projectProperties.put("java.version", "zloug"); - mavenProject.setProperties(projectProperties); + mavenProject.addProperty("time", time); + mavenProject.addProperty("java.version", "zloug"); + MavenResourcesFiltering mavenResourcesFiltering = container.lookup(MavenResourcesFiltering.class); String unitFilesDir = unitDirectory.resolve("files").toString(); @@ -246,12 +191,12 @@ private void filter(String time) throws Exception { MavenResourcesExecution mre = new MavenResourcesExecution(); mre.setResources(resources); - mre.setOutputDirectory(outputDirectory.toFile()); + mre.setOutputDirectory(outputDirectory); mre.setEncoding("UTF-8"); mre.setMavenProject(mavenProject); mre.setFilters(filtersFile); mre.setNonFilteredFileExtensions(Collections.emptyList()); - mre.setMavenSession(new StubMavenSession()); + mre.setMavenSession(new StubSession()); mre.setUseDefaultFilterWrappers(true); mavenResourcesFiltering.filterResources(mre); diff --git a/src/test/java/org/apache/maven/shared/filtering/InvalidMarkTest.java b/src/test/java/org/apache/maven/shared/filtering/InvalidMarkTest.java index 5e715a5a..f407b76b 100644 --- a/src/test/java/org/apache/maven/shared/filtering/InvalidMarkTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/InvalidMarkTest.java @@ -18,41 +18,41 @@ */ package org.apache.maven.shared.filtering; -import javax.inject.Inject; - -import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Collections; +import jakarta.inject.Inject; import org.apache.commons.io.FileUtils; -import org.apache.maven.model.Resource; -import org.codehaus.plexus.testing.PlexusTest; +import org.apache.maven.api.plugin.testing.stubs.ProjectStub; +import org.codehaus.plexus.PlexusContainer; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Mikolaj Izdebski */ -@PlexusTest -class InvalidMarkTest { +public class InvalidMarkTest { @Inject - MavenResourcesFiltering mavenResourcesFiltering; + PlexusContainer container; - File outputDirectory = new File(getBasedir(), "target/LongLineTest"); + Path outputDirectory = Paths.get(getBasedir(), "target/LongLineTest"); @BeforeEach - void setUp() throws Exception { - if (outputDirectory.exists()) { - FileUtils.deleteDirectory(outputDirectory); + protected void setUp() throws Exception { + if (Files.exists(outputDirectory)) { + FileUtils.deleteDirectory(outputDirectory.toFile()); } - outputDirectory.mkdirs(); + Files.createDirectories(outputDirectory); } - @Test - void escape() { + public void testEscape() throws Exception { + MavenResourcesFiltering mavenResourcesFiltering = container.lookup(MavenResourcesFiltering.class); + Resource resource = new Resource(); resource.setDirectory("src/test/units-files/MSHARED-325"); resource.setFiltering(true); @@ -60,14 +60,16 @@ void escape() { MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution( Collections.singletonList(resource), outputDirectory, - new StubMavenProject(new File(".")), + new ProjectStub().setBasedir(Paths.get(".")), "UTF-8", Collections.emptyList(), Collections.emptyList(), - new StubMavenSession()); + new StubSession()); - assertDoesNotThrow(() -> { + try { mavenResourcesFiltering.filterResources(mavenResourcesExecution); - }); + } catch (MavenFilteringException e) { + fail(); + } } } diff --git a/src/test/java/org/apache/maven/shared/filtering/MuliLinesMavenResourcesFilteringTest.java b/src/test/java/org/apache/maven/shared/filtering/MuliLinesMavenResourcesFilteringTest.java index fa8c63ac..d4a6c7d6 100644 --- a/src/test/java/org/apache/maven/shared/filtering/MuliLinesMavenResourcesFilteringTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/MuliLinesMavenResourcesFilteringTest.java @@ -18,17 +18,19 @@ */ package org.apache.maven.shared.filtering; -import javax.inject.Inject; - -import java.io.File; -import java.io.FileInputStream; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; +import jakarta.inject.Inject; import org.apache.commons.io.FileUtils; -import org.apache.maven.model.Resource; +import org.apache.maven.api.plugin.testing.stubs.ProjectStub; +import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -41,36 +43,32 @@ * */ @PlexusTest -class MuliLinesMavenResourcesFilteringTest { +public class MuliLinesMavenResourcesFilteringTest { @Inject - MavenResourcesFiltering mavenResourcesFiltering; + PlexusContainer container; - File outputDirectory = new File(getBasedir(), "target/MuliLinesMavenResourcesFilteringTest"); + Path outputDirectory = Paths.get(getBasedir(), "target/MuliLinesMavenResourcesFilteringTest"); @BeforeEach - void setUp() throws Exception { - if (outputDirectory.exists()) { - FileUtils.deleteDirectory(outputDirectory); - } - outputDirectory.mkdirs(); + protected void setUp() throws Exception { + FileUtils.deleteDirectory(outputDirectory.toFile()); + Files.createDirectories(outputDirectory); } /** - * @throws Exception */ @Test - void filteringTokenOnce() throws Exception { - File baseDir = new File(getBasedir()); - StubMavenProject mavenProject = new StubMavenProject(baseDir); + public void testFilteringTokenOnce() throws Exception { + Path baseDir = Paths.get(getBasedir()); + ProjectStub mavenProject = new ProjectStub().setBasedir(baseDir); mavenProject.setVersion("1.0"); mavenProject.setGroupId("org.apache"); mavenProject.setName("test project"); - Properties projectProperties = new Properties(); - projectProperties.put("foo", "bar"); - projectProperties.put("java.version", "zloug"); - mavenProject.setProperties(projectProperties); + mavenProject.addProperty("foo", "bar"); + mavenProject.addProperty("java.version", "zloug"); + MavenResourcesFiltering mavenResourcesFiltering = container.lookup(MavenResourcesFiltering.class); String unitFilesDir = getBasedir() + "/src/test/units-files/MRESOURCES-104"; @@ -92,14 +90,14 @@ void filteringTokenOnce() throws Exception { "UTF-8", filtersFile, nonFilteredFileExtensions, - new StubMavenSession()); + new StubSession()); mavenResourcesExecution.setUseDefaultFilterWrappers(true); mavenResourcesFiltering.filterResources(mavenResourcesExecution); Properties result = new Properties(); - try (FileInputStream in = new FileInputStream(new File(outputDirectory, "test.properties"))) { + try (InputStream in = Files.newInputStream(outputDirectory.resolve("test.properties"))) { result.load(in); } diff --git a/src/test/java/org/apache/maven/shared/filtering/MultiDelimiterInterpolatorFilterReaderLineEndingTest.java b/src/test/java/org/apache/maven/shared/filtering/MultiDelimiterInterpolatorFilterReaderLineEndingTest.java index 53deff8a..9c7e3841 100644 --- a/src/test/java/org/apache/maven/shared/filtering/MultiDelimiterInterpolatorFilterReaderLineEndingTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/MultiDelimiterInterpolatorFilterReaderLineEndingTest.java @@ -27,27 +27,23 @@ import org.apache.commons.io.IOUtils; import org.codehaus.plexus.interpolation.Interpolator; import org.codehaus.plexus.interpolation.RecursionInterceptor; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; -class MultiDelimiterInterpolatorFilterReaderLineEndingTest extends AbstractInterpolatorFilterReaderLineEndingTest { +@ExtendWith(MockitoExtension.class) +public class MultiDelimiterInterpolatorFilterReaderLineEndingTest + extends AbstractInterpolatorFilterReaderLineEndingTest { @Mock private Interpolator interpolator; - @Override - @BeforeEach - public void onSetup() { - MockitoAnnotations.initMocks(this); - } - @Override protected Reader getAaa_AaaReader(Reader in, Interpolator interpolator) { MultiDelimiterInterpolatorFilterReaderLineEnding reader = @@ -84,7 +80,7 @@ protected Reader getAtReader(Reader in, Interpolator interpolator, String escape // MSHARED-199: Filtering doesn't work if 2 delimiters are used on the same line, the first one being left open @Test - void lineWithSingleAtAndExpression() throws Exception { + public void testLineWithSingleAtAndExpression() throws Exception { when(interpolator.interpolate(eq("${foo}"), eq(""), isA(RecursionInterceptor.class))) .thenReturn("bar"); @@ -98,7 +94,7 @@ void lineWithSingleAtAndExpression() throws Exception { // http://stackoverflow.com/questions/21786805/maven-war-plugin-customize-filter-delimitters-in-webresources/ @Test - void atDollarExpression() throws Exception { + public void testAtDollarExpression() throws Exception { when(interpolator.interpolate(eq("${db.server}"), eq(""), isA(RecursionInterceptor.class))) .thenReturn("DB_SERVER"); when(interpolator.interpolate(eq("${db.port}"), eq(""), isA(RecursionInterceptor.class))) diff --git a/src/test/java/org/apache/maven/shared/filtering/PropertyUtilsTest.java b/src/test/java/org/apache/maven/shared/filtering/PropertyUtilsTest.java index 4e8d53fd..fd44f077 100644 --- a/src/test/java/org/apache/maven/shared/filtering/PropertyUtilsTest.java +++ b/src/test/java/org/apache/maven/shared/filtering/PropertyUtilsTest.java @@ -18,78 +18,85 @@ */ package org.apache.maven.shared.filtering; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStreamWriter; import java.io.Writer; -import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; import java.util.Properties; +import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.slf4j.Logger; import static org.codehaus.plexus.testing.PlexusExtension.getBasedir; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * @author Olivier Lamy * @since 1.0-beta-1 */ -class PropertyUtilsTest { - private static File testDirectory = new File(getBasedir(), "target/test-classes/"); +@PlexusTest +public class PropertyUtilsTest { + private static Path testDirectory = Paths.get(getBasedir(), "target/test-classes/"); @Test - void basic() throws Exception { - File basicProperties = File.createTempFile("basic", ".properties"); - basicProperties.deleteOnExit(); + public void testBasic() throws Exception { + Path basicProp = testDirectory.resolve("basic.properties"); - try (Writer writer = new OutputStreamWriter(new FileOutputStream(basicProperties), StandardCharsets.UTF_8)) { + Files.deleteIfExists(basicProp); + + try (Writer writer = Files.newBufferedWriter(basicProp)) { writer.write("ghost=${non_existent}\n"); writer.write("key=${untat_na_damgo}\n"); writer.write("untat_na_damgo=gani_man\n"); writer.flush(); } - Properties properties = PropertyUtils.loadPropertyFile(basicProperties, false, false); - assertEquals("gani_man", properties.getProperty("key")); - assertEquals("${non_existent}", properties.getProperty("ghost")); + Properties prop = PropertyUtils.loadPropertyFile(basicProp, false, false); + assertEquals("gani_man", prop.getProperty("key")); + assertEquals("${non_existent}", prop.getProperty("ghost")); } @Test - void systemProperties() throws Exception { - File systemProperties = File.createTempFile("system", ".properties"); - systemProperties.deleteOnExit(); + public void testSystemProperties() throws Exception { + Path systemProp = testDirectory.resolve("system.properties"); + + Files.deleteIfExists(systemProp); - try (Writer writer = new OutputStreamWriter(new FileOutputStream(systemProperties), StandardCharsets.UTF_8)) { + try (Writer writer = Files.newBufferedWriter(systemProp)) { writer.write("key=${user.dir}"); writer.flush(); } - Properties properties = PropertyUtils.loadPropertyFile(systemProperties, false, true); - assertEquals(System.getProperty("user.dir"), properties.getProperty("key")); + Properties prop = PropertyUtils.loadPropertyFile(systemProp, false, true); + assertEquals(prop.getProperty("key"), System.getProperty("user.dir")); } @Test - void exception() throws Exception { - File nonExistent = new File(testDirectory, "not_existent_file"); + public void testException() throws Exception { + Path nonExistent = testDirectory.resolve("not_existent_file"); - assertFalse(nonExistent.exists(), "property file exist: " + nonExistent); + assertFalse(Files.exists(nonExistent), "property file exist: " + nonExistent); - try { - PropertyUtils.loadPropertyFile(nonExistent, true, false); - fail("Expected exception not thrown"); - } catch (Exception ex) { - // exception ok - } + assertThrows(Exception.class, () -> PropertyUtils.loadPropertyFile(nonExistent, true, false)); } @Test - void loadPropertiesFile() throws Exception { - File propertyFile = new File(getBasedir() + "/src/test/units-files/propertyutils-test.properties"); - Properties baseProperties = new Properties(); - baseProperties.put("pom.version", "realVersion"); + public void testloadpropertiesFile() throws Exception { + Path propertyFile = Paths.get(getBasedir() + "/src/test/units-files/propertyutils-test.properties"); + Properties baseProps = new Properties(); + baseProps.put("pom.version", "realVersion"); - Properties interpolated = PropertyUtils.loadPropertyFile(propertyFile, baseProperties); + Properties interpolated = PropertyUtils.loadPropertyFile(propertyFile, baseProps); assertEquals("realVersion", interpolated.get("version")); assertEquals("${foo}", interpolated.get("foo")); assertEquals("realVersion", interpolated.get("bar")); @@ -102,19 +109,26 @@ void loadPropertiesFile() throws Exception { * @throws IOException if problem writing file */ @Test - void circularReferences() throws IOException { - File circularProperties = File.createTempFile("circular", ".properties"); - circularProperties.deleteOnExit(); + public void testCircularReferences() throws IOException { + Path basicProp = testDirectory.resolve("circular.properties"); + + Files.deleteIfExists(basicProp); - try (Writer writer = new OutputStreamWriter(new FileOutputStream(circularProperties), StandardCharsets.UTF_8)) { + try (Writer writer = Files.newBufferedWriter(basicProp)) { writer.write("test=${test2}\n"); writer.write("test2=${test2}\n"); writer.flush(); } - Properties properties = PropertyUtils.loadPropertyFile(circularProperties, null); - assertEquals("${test2}", properties.getProperty("test")); - assertEquals("${test2}", properties.getProperty("test2")); + Logger logger = mock(Logger.class); + + Properties prop = PropertyUtils.loadPropertyFile(basicProp, null, logger); + assertEquals("${test2}", prop.getProperty("test")); + assertEquals("${test2}", prop.getProperty("test2")); + assertWarn( + logger, + "Circular reference between properties detected: test2 => test2", + "Circular reference between properties detected: test => test2 => test2"); } /** @@ -123,56 +137,37 @@ void circularReferences() throws IOException { * @throws IOException if problem writing file */ @Test - void circularReferences3Vars() throws IOException { - File circularProperties = File.createTempFile("circular", ".properties"); - circularProperties.deleteOnExit(); + public void testCircularReferences3Vars() throws IOException { + Path basicProp = testDirectory.resolve("circular.properties"); + + Files.deleteIfExists(basicProp); - try (Writer writer = new OutputStreamWriter(new FileOutputStream(circularProperties), StandardCharsets.UTF_8)) { + try (Writer writer = Files.newBufferedWriter(basicProp)) { writer.write("test=${test2}\n"); writer.write("test2=${test3}\n"); writer.write("test3=${test}\n"); writer.flush(); } - Properties properties = PropertyUtils.loadPropertyFile(circularProperties, null); - assertEquals("${test2}", properties.getProperty("test")); - assertEquals("${test3}", properties.getProperty("test2")); - assertEquals("${test}", properties.getProperty("test3")); + Logger logger = mock(Logger.class); + + Properties prop = PropertyUtils.loadPropertyFile(basicProp, null, logger); + assertEquals("${test2}", prop.getProperty("test")); + assertEquals("${test3}", prop.getProperty("test2")); + assertEquals("${test}", prop.getProperty("test3")); + assertWarn( + logger, + "Circular reference between properties detected: test3 => test => test2 => test3", + "Circular reference between properties detected: test2 => test3 => test => test2", + "Circular reference between properties detected: test => test2 => test3 => test"); } - @Test - void nonCircularReferences1Var3Times() throws IOException { - File nonCircularProperties = File.createTempFile("non-circular", ".properties"); - nonCircularProperties.deleteOnExit(); - - try (Writer writer = - new OutputStreamWriter(new FileOutputStream(nonCircularProperties), StandardCharsets.UTF_8)) { - writer.write("depends=p1 >= ${version}, p2 >= ${version}, p3 >= ${version}\n"); - writer.write("version=1.2.3\n"); - writer.flush(); + private void assertWarn(Logger mock, String... expected) { + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + verify(mock, times(expected.length)).warn(argument.capture()); + List messages = argument.getAllValues(); + for (String str : expected) { + assertTrue(messages.contains(str)); } - - Properties properties = PropertyUtils.loadPropertyFile(nonCircularProperties, null); - assertEquals("p1 >= 1.2.3, p2 >= 1.2.3, p3 >= 1.2.3", properties.getProperty("depends")); - assertEquals("1.2.3", properties.getProperty("version")); - } - - @Test - void nonCircularReferences2Vars2Times() throws IOException { - File nonCircularProperties = File.createTempFile("non-circular", ".properties"); - nonCircularProperties.deleteOnExit(); - - try (Writer writer = - new OutputStreamWriter(new FileOutputStream(nonCircularProperties), StandardCharsets.UTF_8)) { - writer.write("test=${test2} ${test3} ${test2} ${test3}\n"); - writer.write("test2=${test3} ${test3}\n"); - writer.write("test3=test\n"); - writer.flush(); - } - - Properties properties = PropertyUtils.loadPropertyFile(nonCircularProperties, null); - assertEquals("test test test test test test", properties.getProperty("test")); - assertEquals("test test", properties.getProperty("test2")); - assertEquals("test", properties.getProperty("test3")); } } diff --git a/src/test/java/org/apache/maven/shared/filtering/StubMavenProject.java b/src/test/java/org/apache/maven/shared/filtering/StubMavenProject.java deleted file mode 100644 index 81d6f50f..00000000 --- a/src/test/java/org/apache/maven/shared/filtering/StubMavenProject.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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. - */ -package org.apache.maven.shared.filtering; - -import java.io.File; -import java.util.Properties; - -import org.apache.maven.project.MavenProject; - -/** - * @author Olivier Lamy - * @since 1.0-beta-1 - * - */ -public class StubMavenProject extends MavenProject { - private Properties properties; - - private File basedir; - - protected StubMavenProject(File basedir) { - this.basedir = basedir; - } - - @Override - public Properties getProperties() { - return this.properties; - } - - public void setProperties(Properties properties) { - this.properties = properties; - } - - public void addProperty(String key, String value) { - if (this.properties == null) { - this.properties = new Properties(); - } - this.properties.put(key, value); - } - - @Override - public File getBasedir() { - return basedir; - } -} diff --git a/src/test/java/org/apache/maven/shared/filtering/StubMavenSession.java b/src/test/java/org/apache/maven/shared/filtering/StubMavenSession.java deleted file mode 100644 index 4c24afa2..00000000 --- a/src/test/java/org/apache/maven/shared/filtering/StubMavenSession.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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. - */ -package org.apache.maven.shared.filtering; - -import java.util.Properties; - -import org.apache.maven.execution.DefaultMavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionResult; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.settings.Settings; -import org.codehaus.plexus.PlexusContainer; -import org.eclipse.aether.RepositorySystemSession; - -/** - * @author Olivier Lamy - * @since 1.0-beta-1 - * - */ -public class StubMavenSession extends MavenSession { - - private Properties userProperties; - - private Properties systemProperties; - - private final Settings settings; - - public StubMavenSession(Settings settings) { - this(null, null, settings); - } - - public StubMavenSession() { - this(null, null, null); - } - - public StubMavenSession(Properties userProperties) { - this(null, userProperties, null); - } - - public StubMavenSession(Properties systemProperties, Properties userProperties, Settings settings) { - - super( - (PlexusContainer) null, - (RepositorySystemSession) null, - new DefaultMavenExecutionRequest(), - (MavenExecutionResult) null); - - this.settings = settings; - - this.systemProperties = new Properties(); - if (systemProperties != null) { - this.systemProperties.putAll(systemProperties); - } - this.systemProperties.putAll(System.getProperties()); - - this.userProperties = new Properties(); - if (userProperties != null) { - this.userProperties.putAll(userProperties); - } - } - - @Override - public Settings getSettings() { - return settings; - } - - @Override - public Properties getSystemProperties() { - return this.systemProperties; - } - - @Override - public Properties getUserProperties() { - return this.userProperties; - } -} diff --git a/src/test/java/org/apache/maven/shared/filtering/StubSession.java b/src/test/java/org/apache/maven/shared/filtering/StubSession.java new file mode 100644 index 00000000..0fec2f06 --- /dev/null +++ b/src/test/java/org/apache/maven/shared/filtering/StubSession.java @@ -0,0 +1,389 @@ +/* + * 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. + */ +package org.apache.maven.shared.filtering; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.apache.maven.api.*; +import org.apache.maven.api.annotations.Nonnull; +import org.apache.maven.api.annotations.Nullable; +import org.apache.maven.api.model.Repository; +import org.apache.maven.api.settings.Settings; + +/** + */ +public class StubSession implements Session { + + private Map userProperties; + + private Map systemProperties; + + private final Settings settings; + + public StubSession(Settings settings) { + this(null, null, settings); + } + + public StubSession() { + this(null, null, null); + } + + public StubSession(Map userProperties) { + this(null, userProperties, null); + } + + public StubSession(Map systemProperties, Map userProperties, Settings settings) { + + this.settings = settings; + + this.systemProperties = new HashMap<>(); + if (systemProperties != null) { + this.systemProperties.putAll(systemProperties); + } + System.getProperties().forEach((k, v) -> this.systemProperties.put(k.toString(), v.toString())); + + this.userProperties = new HashMap<>(); + if (userProperties != null) { + this.userProperties.putAll(userProperties); + } + } + + @Override + public Settings getSettings() { + return settings; + } + + @Override + public Map getSystemProperties() { + return this.systemProperties; + } + + @Override + public Map getUserProperties() { + return this.userProperties; + } + + @Nonnull + public Map getEffectiveProperties(@Nullable Project project) { + HashMap result = new HashMap<>(getSystemProperties()); + if (project != null) { + result.putAll(project.getModel().getProperties()); + } + result.putAll(getUserProperties()); + return result; + } + + @Override + public LocalRepository getLocalRepository() { + return null; + } + + @Override + public Path getTopDirectory() { + return null; + } + + @Override + public Path getRootDirectory() { + return null; + } + + @Override + public List getRemoteRepositories() { + return null; + } + + @Override + public SessionData getData() { + return null; + } + + @Override + public Version getMavenVersion() { + return null; + } + + @Override + public int getDegreeOfConcurrency() { + return 0; + } + + @Override + public Instant getStartTime() { + return null; + } + + @Override + public List getProjects() { + return null; + } + + @Override + public Map getPluginContext(Project project) { + return null; + } + + @Override + public T getService(Class clazz) { + return null; + } + + @Override + public Session withLocalRepository(LocalRepository localRepository) { + return null; + } + + @Override + public Session withRemoteRepositories(List repositories) { + return null; + } + + @Override + public void registerListener(Listener listener) {} + + @Override + public void unregisterListener(Listener listener) {} + + @Override + public Collection getListeners() { + return null; + } + + @Override + public LocalRepository createLocalRepository(Path path) { + return null; + } + + @Override + public RemoteRepository createRemoteRepository(String id, String url) { + return null; + } + + @Override + public RemoteRepository createRemoteRepository(Repository repository) { + return null; + } + + @Override + public Artifact createArtifact(String groupId, String artifactId, String version, String extension) { + return null; + } + + @Override + public Artifact createArtifact( + String groupId, String artifactId, String version, String classifier, String extension, String type) { + return null; + } + + @Override + public ArtifactCoordinate createArtifactCoordinate(String s, String s1, String s2, String s3) { + return null; + } + + @Override + public ArtifactCoordinate createArtifactCoordinate(String coordString) { + return null; + } + + @Override + public ArtifactCoordinate createArtifactCoordinate( + String s, String s1, String s2, String s3, String s4, String s5) { + return null; + } + + @Override + public ArtifactCoordinate createArtifactCoordinate(Artifact artifact) { + return null; + } + + @Override + public DependencyCoordinate createDependencyCoordinate(ArtifactCoordinate artifactCoordinate) { + return null; + } + + @Override + public DependencyCoordinate createDependencyCoordinate(Dependency dependency) { + return null; + } + + @Override + public Map.Entry resolveArtifact(Artifact artifact) { + return null; + } + + @Override + public Map.Entry resolveArtifact(ArtifactCoordinate coordinate) { + return null; + } + + @Override + public Map resolveArtifacts(ArtifactCoordinate... artifactCoordinates) { + return null; + } + + @Override + public Map resolveArtifacts(Collection collection) { + return null; + } + + @Override + public Map resolveArtifacts(Artifact... artifacts) { + return null; + } + + @Override + public List flattenDependencies(Node node, PathScope scope) { + return null; + } + + @Override + public List resolveDependencies(DependencyCoordinate dependencyCoordinate) { + return null; + } + + @Override + public List resolveDependencies(List dependencyCoordinates) { + return null; + } + + @Override + public List resolveDependencies(Project project, PathScope scope) { + return null; + } + + @Override + public Version resolveVersion(ArtifactCoordinate artifact) { + return null; + } + + @Override + public List resolveVersionRange(ArtifactCoordinate artifact) { + return null; + } + + @Override + public void installArtifacts(Artifact... artifacts) {} + + @Override + public void installArtifacts(Collection artifacts) {} + + @Override + public void deployArtifact(RemoteRepository repository, Artifact... artifacts) {} + + @Override + public void setArtifactPath(Artifact artifact, Path path) {} + + @Override + public Optional getArtifactPath(Artifact artifact) { + return Optional.empty(); + } + + @Override + public boolean isVersionSnapshot(String version) { + return false; + } + + @Override + public Node collectDependencies(Artifact artifact) { + return null; + } + + @Override + public Node collectDependencies(Project project) { + return null; + } + + @Override + public Node collectDependencies(DependencyCoordinate dependencyCoordinate) { + return null; + } + + @Override + public Path getPathForLocalArtifact(Artifact artifact) { + return null; + } + + @Override + public Path getPathForRemoteArtifact(RemoteRepository remote, Artifact artifact) { + return null; + } + + @Override + public Version parseVersion(String version) { + return null; + } + + @Override + public VersionRange parseVersionRange(String versionRange) { + return null; + } + + @Override + public VersionConstraint parseVersionConstraint(String s) { + return null; + } + + @Override + public Map> resolveDependencies( + DependencyCoordinate dependencyCoordinate, PathScope scope, Collection desiredTypes) { + return Map.of(); + } + + @Override + public Map> resolveDependencies( + Project project, PathScope scope, Collection desiredTypes) { + return Map.of(); + } + + @Override + public Type requireType(String id) { + return null; + } + + @Override + public Language requireLanguage(String id) { + return null; + } + + @Override + public Packaging requirePackaging(String id) { + return null; + } + + @Override + public ProjectScope requireProjectScope(String id) { + return null; + } + + @Override + public DependencyScope requireDependencyScope(String id) { + return null; + } + + @Override + public PathScope requirePathScope(String id) { + return null; + } +} diff --git a/src/test/java/org/apache/maven/shared/filtering/TestReflectionProperties.java b/src/test/java/org/apache/maven/shared/filtering/TestReflectionProperties.java index a2926ff2..a31766e5 100644 --- a/src/test/java/org/apache/maven/shared/filtering/TestReflectionProperties.java +++ b/src/test/java/org/apache/maven/shared/filtering/TestReflectionProperties.java @@ -18,13 +18,17 @@ */ package org.apache.maven.shared.filtering; -import javax.inject.Inject; - -import java.io.File; -import java.io.FileInputStream; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; -import org.apache.maven.project.MavenProject; +import jakarta.inject.Inject; +import org.apache.maven.api.plugin.testing.stubs.ProjectStub; +import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.testing.PlexusTest; import org.junit.jupiter.api.Test; @@ -37,31 +41,30 @@ * */ @PlexusTest -class TestReflectionProperties { +public class TestReflectionProperties { @Inject - MavenFileFilter mavenFileFilter; + PlexusContainer container; @Test - void simpleFiltering() throws Exception { - MavenProject mavenProject = new MavenProject(); + public void testSimpleFiltering() throws Exception { + ProjectStub mavenProject = new ProjectStub(); mavenProject.setVersion("1.0"); mavenProject.setGroupId("org.apache"); - Properties userProperties = new Properties(); - userProperties.setProperty("foo", "bar"); + Map userProperties = new HashMap<>(); + userProperties.put("foo", "bar"); + MavenFileFilter mavenFileFilter = container.lookup(MavenFileFilter.class); - File from = new File(getBasedir() + "/src/test/units-files/reflection-test.properties"); - File to = new File(getBasedir() + "/target/reflection-test.properties"); + Path from = Paths.get(getBasedir() + "/src/test/units-files/reflection-test.properties"); + Path to = Paths.get(getBasedir() + "/target/reflection-test.properties"); - if (to.exists()) { - to.delete(); - } + Files.deleteIfExists(to); - mavenFileFilter.copyFile(from, to, true, mavenProject, null, false, null, new StubMavenSession(userProperties)); + mavenFileFilter.copyFile(from, to, true, mavenProject, null, false, null, new StubSession(userProperties)); Properties reading = new Properties(); - try (FileInputStream readFileInputStream = new FileInputStream(to)) { + try (InputStream readFileInputStream = Files.newInputStream(to)) { reading.load(readFileInputStream); } @@ -72,27 +75,25 @@ void simpleFiltering() throws Exception { } @Test - void simpleNonFiltering() throws Exception { + public void testSimpleNonFiltering() throws Exception { - MavenProject mavenProject = new MavenProject(); + ProjectStub mavenProject = new ProjectStub(); mavenProject.setVersion("1.0"); mavenProject.setGroupId("org.apache"); - Properties userProperties = new Properties(); - userProperties.setProperty("foo", "bar"); + Map userProperties = new HashMap<>(); + userProperties.put("foo", "bar"); + MavenFileFilter mavenFileFilter = container.lookup(MavenFileFilter.class); - File from = new File(getBasedir() + "/src/test/units-files/reflection-test.properties"); - File to = new File(getBasedir() + "/target/reflection-test.properties"); + Path from = Paths.get(getBasedir() + "/src/test/units-files/reflection-test.properties"); + Path to = Paths.get(getBasedir() + "/target/reflection-test.properties"); - if (to.exists()) { - to.delete(); - } + Files.deleteIfExists(to); - mavenFileFilter.copyFile( - from, to, false, mavenProject, null, false, null, new StubMavenSession(userProperties)); + mavenFileFilter.copyFile(from, to, false, mavenProject, null, false, null, new StubSession(userProperties)); Properties reading = new Properties(); - try (FileInputStream readFileInputStream = new FileInputStream(to); ) { + try (InputStream readFileInputStream = Files.newInputStream(to); ) { reading.load(readFileInputStream); }