我真的需要一些建议......
这是我的情况: 我有一个主要的maven项目P1,有几个资源可以根据目标环境进行过滤。
我希望将我的过滤器文件放在另一个名为P2的项目中,仅用于托管过滤器文件(对于此项目以及其他项目),以便独立于P1管理其配置。
第一个问题:还有其他人这样做吗?这是个好主意吗?现在我的问题是如何使用P2过滤器过滤P1资源。在我的P1 POM中,使用目录" ../ P2"因为我不喜欢使用过滤器,第二,我使用Jenkins进行生成,而Jenkins P1和P2则不在同一个父目录中。
所以我想让P1将P2称为jar依赖。但是如何定义Maven过滤器不是目录中的文件,而是jar依赖项中的资源?我找到的唯一方法是使用"自定义资源过滤器" Maven资源插件(https://maven.apache.org/plugins/maven-resources-plugin/examples/custom-resource-filters.html),我在其中链接到进行过滤的P2自定义类。
这个解决方案正在通过Maven为战争创造。但是开发人员需要使用Maven Eclipse WTP功能,以便在他们的服务器上部署项目,并特别使用动态资源过滤(无需运行maven构建)。和#34;自定义资源过滤器"不能使用Eclipse WTP实时资源过滤。
所以我真的不知道该怎么做......你会给我什么建议?或者为什么你没有这个问题?
非常感谢
答案 0 :(得分:0)
嗯,我最后做的是保留P2项目的过滤器。在我的P2项目中,我创建了一个受默认ResourceFilter类启发的类。
package com.ads.xx.xx;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.maven.model.Resource;
import org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering;
import org.apache.maven.shared.filtering.MavenFileFilter;
import org.apache.maven.shared.filtering.MavenFilteringException;
import org.apache.maven.shared.filtering.MavenResourcesExecution;
import org.apache.maven.shared.filtering.MavenResourcesFiltering;
import org.apache.maven.shared.utils.PathTool;
import org.apache.maven.shared.utils.ReaderFactory;
import org.apache.maven.shared.utils.io.FileUtils;
import org.apache.maven.shared.utils.io.FileUtils.FilterWrapper;
import org.apache.maven.shared.utils.io.IOUtil;
import org.codehaus.plexus.util.Scanner;
import org.sonatype.plexus.build.incremental.BuildContext;
/**
* @plexus.component role="org.apache.maven.shared.filtering.MavenResourcesFiltering"
* role-hint="default"
*
*/
public class ResourceFilterxxxGlobal extends DefaultMavenResourcesFiltering implements MavenResourcesFiltering {
private static final String[] EMPTY_STRING_ARRAY = { };
private static final String[] DEFAULT_INCLUDES = { "**/**" };
private List<String> defaultNonFilteredFileExtensions;
/**
* @plexus.requirement
*/
public BuildContext buildContext;
/**
* @plexus.requirement role-hint="default"
*/
private MavenFileFilter mavenFileFilter;
public ResourceFilterAtamsGlobal() {
super();
}
public void filterResources(MavenResourcesExecution mavenResourcesExecution)
throws MavenFilteringException {
List<String> listeFiltres = new ArrayList<String>();
String environnement = mavenResourcesExecution.getMavenProject().getProperties().getProperty("environnement");
String fonctionnel = mavenResourcesExecution.getMavenProject().getProperties().getProperty("fonctionnel");
String application = mavenResourcesExecution.getMavenProject().getProperties().getProperty("application");
listeFiltres.add("filters/plateformes/" + environnement + "_technique.properties");
listeFiltres.add("filters/applications/" + application + "/fonctionnel/" + fonctionnel + ".properties");
listeFiltres.add("filters/applications/" + application + "/specifique/" + environnement + "_specifique.properties");
final Properties fileProps = new Properties();
DataInputStream dis = null;
try {
for (String filtrePath : listeFiltres) {
dis = new DataInputStream(getClass().getClassLoader().getResourceAsStream(filtrePath));
if (dis == null) {
System.out.println("Le fichier " + filtrePath + " n'existe pas.");
throw new MavenFilteringException("Le fichier " + filtrePath + " n'existe pas.");
}
fileProps.load(dis);
mavenResourcesExecution.getMavenProject().getProperties().putAll(fileProps);
dis.close();
}
}
catch (IOException e) {
e.printStackTrace();
throw new MavenFilteringException();
}
finally {
try {
if (dis != null) {
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("Le fichier de filtre n'existe pas.");
throw new MavenFilteringException("Le fichier de filtre n'existe pas.");
}
}
System.out.println("Propriétés trouvées : " + fileProps.entrySet());
mavenResourcesExecution.getMavenProject().getProperties().putAll(fileProps);
if ( mavenResourcesExecution == null )
{
throw new MavenFilteringException( "mavenResourcesExecution cannot be null" );
}
if ( mavenResourcesExecution.getResources() == null )
{
getLogger().info( "No resources configured skip copying/filtering" );
return;
}
if ( mavenResourcesExecution.getOutputDirectory() == null )
{
throw new MavenFilteringException( "outputDirectory cannot be null" );
}
if ( mavenResourcesExecution.isUseDefaultFilterWrappers() )
{
List<FileUtils.FilterWrapper> filterWrappers = new ArrayList<FileUtils.FilterWrapper>();
if ( mavenResourcesExecution.getFilterWrappers() != null )
{
filterWrappers.addAll( mavenResourcesExecution.getFilterWrappers() );
}
filterWrappers.addAll( mavenFileFilter.getDefaultFilterWrappers( mavenResourcesExecution ) );
mavenResourcesExecution.setFilterWrappers( filterWrappers );
}
if ( mavenResourcesExecution.getEncoding() == null || mavenResourcesExecution.getEncoding().length() < 1 )
{
getLogger().warn( "Using platform encoding (" + ReaderFactory.FILE_ENCODING
+ " actually) to copy filtered resources, i.e. build is platform dependent!" );
}
else
{
getLogger().info(
"Using '" + mavenResourcesExecution.getEncoding() + "' encoding to copy filtered resources." );
}
for ( Resource resource : mavenResourcesExecution.getResources() )
{
if ( getLogger().isDebugEnabled() )
{
String ls = System.getProperty( "line.separator" );
StringBuffer debugMessage =
new StringBuffer( "resource with targetPath " ).append( resource.getTargetPath() ).append( ls );
debugMessage.append( "directory " ).append( resource.getDirectory() ).append( ls );
debugMessage.append( "excludes " ).append( resource.getExcludes() == null ? " empty "
: resource.getExcludes().toString() ).append( ls );
debugMessage.append( "includes " ).append( resource.getIncludes() == null ? " empty "
: resource.getIncludes().toString() );
getLogger().debug( debugMessage.toString() );
}
String targetPath = resource.getTargetPath();
File resourceDirectory = new File( resource.getDirectory() );
if ( !resourceDirectory.isAbsolute() )
{
resourceDirectory =
new File( mavenResourcesExecution.getResourcesBaseDirectory(), resourceDirectory.getPath() );
}
if ( !resourceDirectory.exists() )
{
getLogger().info( "skip non existing resourceDirectory " + resourceDirectory.getPath() );
continue;
}
// this part is required in case the user specified "../something" as destination
// see MNG-1345
File outputDirectory = mavenResourcesExecution.getOutputDirectory();
boolean outputExists = outputDirectory.exists();
if ( !outputExists && !outputDirectory.mkdirs() )
{
throw new MavenFilteringException( "Cannot create resource output directory: " + outputDirectory );
}
boolean ignoreDelta = !outputExists || buildContext.hasDelta( mavenResourcesExecution.getFileFilters() )
|| buildContext.hasDelta( getRelativeOutputDirectory( mavenResourcesExecution ) );
getLogger().debug( "ignoreDelta " + ignoreDelta );
Scanner scanner = buildContext.newScanner( resourceDirectory, ignoreDelta );
setupScanner( resource, scanner );
scanner.scan();
if ( mavenResourcesExecution.isIncludeEmptyDirs() )
{
try
{
File targetDirectory =
targetPath == null ? outputDirectory : new File( outputDirectory, targetPath );
copyDirectoryLayout( resourceDirectory, targetDirectory, scanner );
}
catch ( IOException e )
{
throw new MavenFilteringException(
"Cannot copy directory structure from " + resourceDirectory.getPath() + " to "
+ outputDirectory.getPath() );
}
}
List<String> includedFiles = Arrays.asList( scanner.getIncludedFiles() );
getLogger().info(
"Copying " + includedFiles.size() + " resource" + ( includedFiles.size() > 1 ? "s" : "" ) + (
targetPath == null ? "" : " to " + targetPath ) );
for ( String name : includedFiles )
{
File source = new File( resourceDirectory, name );
File destinationFile =
getDestinationFile( outputDirectory, targetPath, name, mavenResourcesExecution );
boolean filteredExt =
filteredFileExtension( source.getName(), mavenResourcesExecution.getNonFilteredFileExtensions() );
mavenFileFilter.copyFile( source, destinationFile, resource.isFiltering() && filteredExt,
mavenResourcesExecution.getFilterWrappers(),
mavenResourcesExecution.getEncoding(),
mavenResourcesExecution.isOverwrite() );
}
// deal with deleted source files
scanner = buildContext.newDeleteScanner( resourceDirectory );
setupScanner( resource, scanner );
scanner.scan();
List<String> deletedFiles = Arrays.asList( scanner.getIncludedFiles() );
for ( String name : deletedFiles )
{
File destinationFile =
getDestinationFile( outputDirectory, targetPath, name, mavenResourcesExecution );
destinationFile.delete();
buildContext.refresh( destinationFile );
}
}
}
private File getDestinationFile( File outputDirectory, String targetPath, String name, MavenResourcesExecution mavenResourcesExecution )
throws MavenFilteringException
{
String destination = name;
if ( mavenResourcesExecution.isFilterFilenames() && mavenResourcesExecution.getFilterWrappers().size() > 0 )
{
destination = filterFileName( destination, mavenResourcesExecution.getFilterWrappers() );
}
if ( targetPath != null )
{
destination = targetPath + "/" + destination;
}
File destinationFile = new File( destination );
if ( !destinationFile.isAbsolute() )
{
destinationFile = new File( outputDirectory, destination );
}
if ( !destinationFile.getParentFile().exists() )
{
destinationFile.getParentFile().mkdirs();
}
return destinationFile;
}
private String[] setupScanner( Resource resource, Scanner scanner )
{
String[] includes = null;
if ( resource.getIncludes() != null && !resource.getIncludes().isEmpty() )
{
includes = (String[]) resource.getIncludes().toArray( EMPTY_STRING_ARRAY );
}
else
{
includes = DEFAULT_INCLUDES;
}
scanner.setIncludes( includes );
String[] excludes = null;
if ( resource.getExcludes() != null && !resource.getExcludes().isEmpty() )
{
excludes = (String[]) resource.getExcludes().toArray( EMPTY_STRING_ARRAY );
scanner.setExcludes( excludes );
}
scanner.addDefaultExcludes();
return includes;
}
private void copyDirectoryLayout( File sourceDirectory, File destinationDirectory, Scanner scanner )
throws IOException
{
if ( sourceDirectory == null )
{
throw new IOException( "source directory can't be null." );
}
if ( destinationDirectory == null )
{
throw new IOException( "destination directory can't be null." );
}
if ( sourceDirectory.equals( destinationDirectory ) )
{
throw new IOException( "source and destination are the same directory." );
}
if ( !sourceDirectory.exists() )
{
throw new IOException( "Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ")." );
}
List<String> includedDirectories = Arrays.asList( scanner.getIncludedDirectories() );
for ( String name : includedDirectories )
{
File source = new File( sourceDirectory, name );
if ( source.equals( sourceDirectory ) )
{
continue;
}
File destination = new File( destinationDirectory, name );
destination.mkdirs();
}
}
private String getRelativeOutputDirectory( MavenResourcesExecution execution )
{
String relOutDir = execution.getOutputDirectory().getAbsolutePath();
if ( execution.getMavenProject() != null && execution.getMavenProject().getBasedir() != null )
{
String basedir = execution.getMavenProject().getBasedir().getAbsolutePath();
relOutDir = PathTool.getRelativeFilePath( basedir, relOutDir );
if ( relOutDir == null )
{
relOutDir = execution.getOutputDirectory().getPath();
}
else
{
relOutDir = relOutDir.replace( '\\', '/' );
}
}
return relOutDir;
}
/*
* Filter the name of a file using the same mechanism for filtering the content of the file.
*/
private String filterFileName( String name, List<FilterWrapper> wrappers )
throws MavenFilteringException
{
Reader reader = new StringReader( name );
for ( FilterWrapper wrapper : wrappers )
{
reader = wrapper.getReader( reader );
}
StringWriter writer = new StringWriter();
try
{
IOUtil.copy( reader, writer );
}
catch ( IOException e )
{
throw new MavenFilteringException( "Failed filtering filename" + name, e );
}
String filteredFilename = writer.toString();
if ( getLogger().isDebugEnabled() )
{
getLogger().debug( "renaming filename " + name + " to " + filteredFilename );
}
return filteredFilename;
}
}
然后,在P1项目中,我通过以下方式调用它:
<profile>
<id>local</id>
<activation>
<file>
<exists>../Apl/pom.xml</exists>
</file>
</activation>
<build>
<filters>
<filter>../Apl/src/main/resources/filters/plateformes/${environnement}_technique.properties</filter>
<filter>../Apl/src/main/resources/filters/applications/${application}/specifique/${environnement}_specifique.properties</filter>
<filter>../Apl/src/main/resources/filters/applications/${application}/fonctionnel/${fonctionnel}.properties</filter>
</filters>
</build>
</profile>
<profile>
<id>serveur</id>
<activation>
<file>
<missing>../Apl/pom.xml</missing>
</file>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<dependencies>
<dependency>
<groupId>com.ads.xxx</groupId>
<artifactId>apl</artifactId>
<version>1.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</profile>
本地配置文件适用于开发人员,而服务器配置文件则通过Jenkins部署在远程服务器上。它运作得很好。