下面列出了org.apache.commons.io.filefilter.RegexFileFilter#org.apache.maven.project.MavenProject 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private MavenSession newSession(MavenProject project, File localrepo, Properties properties) throws Exception {
MavenExecutionRequest request = new DefaultMavenExecutionRequest();
MavenExecutionResult result = new DefaultMavenExecutionResult();
DefaultRepositorySystemSession repoSession = MavenRepositorySystemUtils.newSession();
LocalRepository localRepo = new LocalRepository(localrepo);
repoSession.setLocalRepositoryManager(mojos.getContainer().lookup(LocalRepositoryManagerFactory.class, "simple").newInstance(repoSession, localRepo));
MavenSession session = new MavenSession(mojos.getContainer(), repoSession, request, result);
List<MavenProject> projects = new ArrayList<>();
projects.add(project);
for (String module : project.getModules()) {
MavenProject moduleProject = readMavenProject(new File(project.getBasedir(), module), properties);
moduleProject.setParent(project);
projects.add(moduleProject);
}
session.setProjects(projects);
return session;
}
protected String toString( MavenProject project )
{
StringBuilder buf = new StringBuilder();
buf.append( project.getGroupId() );
buf.append( ':' );
buf.append( project.getArtifactId() );
if ( project.getVersion() != null && project.getVersion().length() > 0 )
{
buf.append( ":" );
buf.append( project.getVersion() );
}
return buf.toString();
}
private File ensureThatArtifactFileIsSet(MavenProject project) {
Artifact artifact = project.getArtifact();
if (artifact == null) {
return null;
}
File oldFile = artifact.getFile();
if (oldFile != null) {
return oldFile;
}
Build build = project.getBuild();
if (build == null) {
return null;
}
String finalName = build.getFinalName();
String target = build.getDirectory();
if (finalName == null || target == null) {
return null;
}
File artifactFile = new File(target, finalName + "." + project.getPackaging());
if (artifactFile.exists() && artifactFile.isFile()) {
setArtifactFile(project, artifactFile);
}
return null;
}
private String getNewVersion( ExternalVersionStrategy strategy, MavenProject mavenProject )
throws ExternalVersionException
{
// snapshot detection against the old version.
boolean isSnapshot = ArtifactUtils.isSnapshot( mavenProject.getVersion() );
// lookup the new version
String newVersion = strategy.getVersion( mavenProject );
if ( newVersion != null )
{
newVersion = newVersion.trim();
}
boolean isNewSnapshot = ArtifactUtils.isSnapshot( newVersion );
// make sure we still have a SNAPSHOT if we had one previously.
if ( isSnapshot && !isNewSnapshot )
{
newVersion = newVersion + "-SNAPSHOT";
}
return newVersion;
}
@Messages({
"SG_Sources=Source Packages",
"SG_Test_Sources=Test Packages"
})
private void checkChanges(boolean fireChanges, boolean checkAlsoNonJavaStuff) {
boolean changed = false;
synchronized (lock) {
NbMavenProjectImpl project = project();
MavenProject mp = project.getOriginalMavenProject();
NbMavenProject watcher = project.getProjectWatcher();
File folder = FileUtilities.convertStringToFile(mp.getBuild().getSourceDirectory());
changed = changed | checkSourceGroupCache(folder, NAME_SOURCE, SG_Sources(), javaGroup, watcher);
folder = FileUtilities.convertStringToFile(mp.getBuild().getTestSourceDirectory());
changed = changed | checkSourceGroupCache(folder, NAME_TESTSOURCE, SG_Test_Sources(), javaGroup, watcher);
changed = changed | checkGeneratedGroupsCache();
if (checkAlsoNonJavaStuff) {
changed = changed | checkOtherGroupsCache(project.getOtherRoots(false), false);
changed = changed | checkOtherGroupsCache(project.getOtherRoots(true), true);
}
}
if (changed) {
if (fireChanges) {
cs.fireChange();
}
}
}
/**
* Disabled default behavior.
*
* @param project the project
*/
public static void disabledDefaultBehavior(MavenProject project) {
project.getProperties().put("dew.devops.skip", "true");
project.getProperties().put("maven.javadoc.skip", "true");
project.getProperties().put("maven.source.skip", "true");
project.getProperties().put("checkstyle.skip", "true");
project.getProperties().put("assembly.skipAssembly", "true");
project.getProperties().put("mdep.analyze.skip", "true");
project.getProperties().put("maven.main.skip", "true");
project.getProperties().put("gpg.skip", "true");
project.getProperties().put("maven.war.skip", "true");
project.getProperties().put("maven.resources.skip", "true");
project.getProperties().put("maven.test.skip", "true");
project.getProperties().put("maven.install.skip", "true");
project.getProperties().put("maven.deploy.skip", "true");
project.getProperties().put("maven.site.skip", "true");
}
/**
* Returns the plugin with the given groupId (if present) and artifactId.
*
* @param project MavenProject of project
* @param groupId group id
* @param artifactId artifact id
* @return return Plugin object for the specific plugin
*/
public static org.apache.maven.model.Plugin getPlugin(MavenProject project, String groupId, String artifactId) {
if (artifactId == null) {
throw new IllegalArgumentException("artifactId cannot be null");
}
List<org.apache.maven.model.Plugin> plugins = project.getBuildPlugins();
if (plugins != null) {
for (org.apache.maven.model.Plugin plugin : plugins) {
boolean matchesArtifactId = artifactId.equals(plugin.getArtifactId());
boolean matchesGroupId = groupId == null || groupId.equals(plugin.getGroupId());
if (matchesGroupId && matchesArtifactId) {
return plugin;
}
}
}
return null;
}
private MavenProject getMavenProject() {
MavenProject mavenProject = new MavenProject();
mavenProject.setName("testProject");
mavenProject.setGroupId("org.eclipse.jkube");
mavenProject.setArtifactId("test-project");
mavenProject.setVersion("0.1.0");
mavenProject.setDescription("test description");
Build build = new Build();
build.setOutputDirectory("./target");
build.setDirectory(".");
mavenProject.setBuild(build);
DistributionManagement distributionManagement = new DistributionManagement();
Site site = new Site();
site.setUrl("https://www.eclipse.org/jkube/");
distributionManagement.setSite(site);
mavenProject.setDistributionManagement(distributionManagement);
return mavenProject;
}
@Test
public void moduleBChanged_makeBoth() throws GitAPIException, IOException {
MavenProject moduleB = addModuleMock(AID_MODULE_B, true);
MavenProject moduleC = addModuleMock(AID_MODULE_C, false);
setUpstreamProjects(moduleC, moduleB, moduleA);
setDownstreamProjects(moduleB, moduleC);
setDownstreamProjects(moduleA, moduleB, moduleC);
setProjectSelections(moduleB);
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_BOTH);
underTest.act();
verify(mavenSessionMock).setProjects(Arrays.asList(moduleB, moduleC));
assertProjectPropertiesEqual(moduleB, Collections.emptyMap());
assertProjectPropertiesEqual(moduleC, Collections.emptyMap());
}
@Test
public void assemblyFiles(@Injectable final MojoParameters mojoParams,
@Injectable final MavenProject project,
@Injectable final Assembly assembly) throws AssemblyFormattingException, ArchiveCreationException, InvalidAssemblerConfigurationException, MojoExecutionException, AssemblyReadException, IllegalAccessException {
ReflectionUtils.setVariableValueInObject(assemblyManager, "trackArchiver", trackArchiver);
new Expectations() {{
mojoParams.getOutputDirectory();
result = "target/"; times = 3;
mojoParams.getProject();
project.getBasedir();
result = ".";
assemblyReader.readAssemblies((AssemblerConfigurationSource) any);
result = Arrays.asList(assembly);
}};
BuildImageConfiguration buildConfig = createBuildConfig();
assemblyManager.getAssemblyFiles("testImage", buildConfig, mojoParams, new AnsiLogger(new SystemStreamLog(),true,"build"));
}
@Override
List<MavenProject> findDependencies() {
final List<MavenProject> result = new ArrayList<>();
final List<String> scopeList = Arrays.asList(Artifact.SCOPE_COMPILE,
Artifact.SCOPE_RUNTIME, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_TEST);
for (final Object dependencyObject : getProject().getDependencies()) {
final Dependency dependency = (Dependency) dependencyObject;
if (scopeList.contains(dependency.getScope())) {
final MavenProject project = findProjectFromReactor(dependency);
if (project != null) {
result.add(project);
}
}
}
return result;
}
public Element addRarModule(MavenProject proj) throws Exception {
Element rarArchive = config.addArchive(getModuleUri(proj));
config.addDir(rarArchive, getRarSourceDirectory(proj), "/");
// get raXmlFile optional rar plugin parameter
String path = MavenProjectUtil.getPluginConfiguration(proj, "org.apache.maven.plugins", "maven-rar-plugin",
"raXmlFile");
if (path != null && !path.isEmpty()) {
File raXmlFile = new File(path);
config.addFile(rarArchive, raXmlFile, "/META-INF/ra.xml");
}
// add Manifest file
File manifestFile = MavenProjectUtil.getManifestFile(proj, "maven-rar-plugin");
addManifestFileWithParent(rarArchive, manifestFile);
return rarArchive;
}
private Set<File> filterUnchangedFiles(Set<File> originalFiles) throws MojoExecutionException {
MavenProject topLevelProject = session.getTopLevelProject();
try {
if (topLevelProject.getScm().getConnection() == null && topLevelProject.getScm().getDeveloperConnection() == null) {
throw new MojoExecutionException(
"You must supply at least one of scm.connection or scm.developerConnection in your POM file if you " +
"specify the filterModified or filter.modified option.");
}
String connectionUrl = MoreObjects.firstNonNull(topLevelProject.getScm().getConnection(), topLevelProject.getScm().getDeveloperConnection());
ScmRepository repository = scmManager.makeScmRepository(connectionUrl);
ScmFileSet scmFileSet = new ScmFileSet(topLevelProject.getBasedir());
String basePath = topLevelProject.getBasedir().getAbsoluteFile().getPath();
List<String> changedFiles =
scmManager.status(repository, scmFileSet).getChangedFiles().stream()
.map(f -> new File(basePath, f.getPath()).toString())
.collect(Collectors.toList());
return originalFiles.stream().filter(f -> changedFiles.contains(f.getPath())).collect(Collectors.toSet());
} catch (ScmException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
public static void addMavenBpelPlugin(MavenProject mavenProject){
Plugin plugin;
PluginExecution pluginExecution;
plugin = MavenUtils.createPluginEntry(mavenProject, GROUP_ID_ORG_WSO2_MAVEN, ARTIFACT_ID_MAVEN_BPEL_PLUGIN,
WSO2MavenPluginVersions.getPluginVersion(ARTIFACT_ID_MAVEN_BPEL_PLUGIN), true);
// FIXME : remove hard-coded version value (cannot use
// org.wso2.developerstudio.eclipse.capp.maven.utils.MavenConstants
// due to cyclic reference)
// pluginExecution=new PluginExecution();
// pluginExecution.addGoal("bpel");
// pluginExecution.setPhase("package");
// pluginExecution.setId("bpel");
// plugin.addExecution(pluginExecution)
mavenProject.getModel().addProperty(PROPERTY_CAPP_TYPE, "bpel/workflow");
}
/**
* replacement for MavenProject.getParent() which has bad long term memory behaviour. We offset it by recalculating/reparsing everything
* therefore should not be used lightly!
* pass a MavenProject instance and current configuration and other settings will be applied when loading the parent.
* @param project
* @return null or the parent mavenproject
*/
public MavenProject loadParentOf(MavenEmbedder embedder, MavenProject project) throws ProjectBuildingException {
MavenProject parent = null;
ProjectBuilder builder = embedder.lookupComponent(ProjectBuilder.class);
MavenExecutionRequest req = embedder.createMavenExecutionRequest();
M2Configuration active = configProvider.getActiveConfiguration();
req.addActiveProfiles(active.getActivatedProfiles());
req.setNoSnapshotUpdates(true);
req.setUpdateSnapshots(false);
req.setInteractiveMode(false);
req.setRecursive(false);
req.setOffline(true);
//#238800 important to merge, not replace
Properties uprops = req.getUserProperties();
uprops.putAll(MavenProjectCache.createUserPropsForProjectLoading(active.getProperties()));
req.setUserProperties(uprops);
ProjectBuildingRequest request = req.getProjectBuildingRequest();
request.setRemoteRepositories(project.getRemoteArtifactRepositories());
DefaultMaven maven = (DefaultMaven) embedder.lookupComponent(Maven.class);
request.setRepositorySession(maven.newRepositorySession(req));
if (project.getParentFile() != null) {
parent = builder.build(project.getParentFile(), request).getProject();
} else if (project.getModel().getParent() != null) {
parent = builder.build(project.getParentArtifact(), request).getProject();
}
//clear the project building request, it references multiple Maven Models via the RepositorySession cache
//is not used in maven itself, most likely used by m2e only..
if (parent != null) {
parent.setProjectBuildingRequest(null);
}
MavenEmbedder.normalizePaths(parent);
return parent;
}
@Override
protected void configureMojo(AbstractXJC2Mojo mojo) {
super.configureMojo(mojo);
mojo.setProject(new MavenProject());
mojo.setForceRegenerate(true);
mojo.setExtension(true);
}
private void generateDocument(MavenProject project) {
//generate document
String documentOutput =
outputDirectory + File.separator + "document";
try {
FileUtils.createDirectory(documentOutput);
GenerateUtil.generateDocument(contractLocation, documentOutput, "default");
} catch (RuntimeException | IOException e) {
throw new RuntimeException("Failed to generate document", e);
}
}
private Set<String> getChildModuleCanoncialPath( MavenProject project, List<String> modules ) throws IOException {
Set<String> paths = new TreeSet<>();
for (String module : modules) {
File file = new File( project.getBasedir(), module );
paths.add(file.getCanonicalPath());
}
return paths;
}
private Scm getScm() {
Iterator<? extends MavenProject> prj = result.allInstances().iterator();
if (!prj.hasNext()) {
return null;
}
MavenProject project = prj.next();
return project.getScm();
}
@Test
public void findYangFilesInDependencies() throws Exception {
final MavenProject project = mock(MavenProject.class);
prepareProject(project);
final Collection<ScannedDependency> files = ScannedDependency.scanDependencies(project);
assertNotNull(files);
assertEquals(2, files.size());
}
private MavenProject createProject( String artifactId, File baseDir )
{
MavenProject mock = mock( MavenProject.class );
when( mock.getGroupId() ).thenReturn( "c.s.e" );
when( mock.getArtifactId() ).thenReturn( artifactId );
when( mock.getVersion() ).thenReturn( "0.1.0-SNAPSHOT" );
when( mock.getBasedir() ).thenReturn( baseDir );
return mock;
}
protected void installDependencies() throws Exception {
Set<Artifact> artifacts = project.getArtifacts();
log.debug("Number of compile dependencies for " + project.getArtifactId() + " : " + artifacts.size());
for (Artifact artifact : artifacts) {
// skip if not an application type supported by Liberty
if (!isSupportedType(artifact.getType())) {
continue;
}
// skip assemblyArtifact if specified as a dependency
if (assemblyArtifact != null && matches(artifact, assemblyArtifact)) {
continue;
}
if (artifact.getScope().equals("compile")) {
if (isSupportedType(artifact.getType())) {
if (looseApplication && isReactorMavenProject(artifact)) { //Installing the reactor project artifacts
MavenProject dependProj = getReactorMavenProject(artifact);
installLooseApplication(dependProj);
} else {
installApp(resolveArtifact(artifact));
}
} else {
log.warn(MessageFormat.format(messages.getString("error.application.not.supported"),
project.getId()));
}
}
}
}
@Test
public void testAddingFileUsingFileSets() throws IOException, PackagingException {
AbstractVertxMojo mojo = mock(AbstractVertxMojo.class);
MavenProject project = mock(MavenProject.class);
when(mojo.getLog()).thenReturn(new SystemStreamLog());
when(project.getBasedir()).thenReturn(new File("."));
when(mojo.getProject()).thenReturn(project);
Archive archive = new Archive();
archive.setIncludeClasses(false);
archive.setDependencySets(Collections.emptyList());
archive.addFileSet(new FileSet()
.setOutputDirectory("config")
.addInclude("*.yaml")
.setDirectory("src/test/resources"));
File output = new File(out, "test-filesets.jar");
PackageConfig config = new PackageConfig()
.setProject(project)
.setMojo(mojo)
.setOutput(output)
.setArtifacts(Collections.emptySet())
.setArchive(archive);
service.doPackage(config);
assertThat(output).isFile();
JarFile jar = new JarFile(output);
List<String> list = jar.stream().map(ZipEntry::getName)
.filter(s -> ! s.endsWith("/")) // Directories
.collect(Collectors.toList());
assertThat(list).contains("META-INF/MANIFEST.MF", "config/testconfig.yaml", "config/testconfig2.yaml").hasSize(3);
}
private void createMavenWrapper(File createdPomFile, Properties props) {
try {
// we need to modify the maven environment used by the wrapper plugin since the project could have been
// created in a directory other than the current
MavenProject newProject = projectBuilder.build(
createdPomFile, new DefaultProjectBuildingRequest(session.getProjectBuildingRequest())).getProject();
MavenExecutionRequest newExecutionRequest = DefaultMavenExecutionRequest.copy(session.getRequest());
newExecutionRequest.setBaseDirectory(createdPomFile.getParentFile());
MavenSession newSession = new MavenSession(session.getContainer(), session.getRepositorySession(),
newExecutionRequest, session.getResult());
newSession.setCurrentProject(newProject);
setProxySystemPropertiesFromSession();
executeMojo(
plugin(
groupId("io.takari"),
artifactId("maven"),
version(ToolsUtils.getMavenWrapperVersion(props))),
goal("wrapper"),
configuration(
element(name("maven"), ToolsUtils.getProposedMavenVersion(props))),
executionEnvironment(
newProject,
newSession,
pluginManager));
} catch (Exception e) {
// no reason to fail if the wrapper could not be created
getLog().error("Unable to install the Maven wrapper (./mvnw) in the project", e);
}
}
@Test
public void testPropertyPriorityProject() throws Exception {
Properties systemProperties = new Properties();
systemProperties.setProperty( Constants.BUILDTIME_OUTPUT_LOG_PROPERTY, "systemProperty" );
MavenProject mavenProject = new MavenProject();
mavenProject.getProperties().setProperty( Constants.BUILDTIME_OUTPUT_LOG_PROPERTY, "projectProperty" );
Properties userProperties = new Properties();
when( session.getSystemProperties() ).thenReturn( systemProperties );
when( session.getUserProperties() ).thenReturn( userProperties );
when( session.getTopLevelProject() ).thenReturn( mavenProject );
assertEquals( "projectProperty", MavenHelper.getExecutionProperty( sessionEndEvent, Constants.BUILDTIME_OUTPUT_LOG_PROPERTY, "default" ) );
}
public WebXmlProcessing(Log log, String webXmlSourcePath,
String outputDirectory, MavenProject project,
String userSpecifiedServiceClassNames) {
this.log = log;
this.webXmlSourcePath = webXmlSourcePath;
this.outputDirectory = outputDirectory;
this.project = project;
this.userSpecifiedServiceClassNames = userSpecifiedServiceClassNames;
}
private void addDependencies(MavenProject project, String... keys) throws Exception {
File[] files = new File[keys.length];
for (int i = 0; i < keys.length; i++) {
files[i] = new File(properties.get(keys[i]));
}
addDependencies(project, files);
}
/**
* Update created pom.xml file with necessary dependencies and plug-ins so
* that it works with WSO2 MSF4J server
*
* @throws IOException
* @throws XmlPullParserException
*
*/
private void updatePom(IProject project) throws IOException, XmlPullParserException {
File mavenProjectPomLocation = project.getFile(POM_FILE).getLocation().toFile();
MavenProject mavenProject = MavenUtils.getMavenProject(mavenProjectPomLocation);
Parent msf4jParent = new Parent();
msf4jParent.setGroupId(MSF4J_SERVICE_PARENT_GROUP_ID);
msf4jParent.setArtifactId(MSF4J_SERVICE_PARENT_ARTIFACT_ID);
msf4jParent.setVersion(MSF4JArtifactConstants.getMSF4JServiceParentVersion());
mavenProject.getModel().setParent(msf4jParent);
Properties generatedProperties = mavenProject.getModel().getProperties();
generatedProperties.clear();
}
/** Replies the Maven project for the resource set.
*
* @param rs the manve project.
* @return the maven project.
*/
public static MavenProject get(ResourceSet rs) {
for (final Adapter a : rs.eAdapters()) {
if (a instanceof MavenProjectAdapter) {
return ((MavenProjectAdapter) a).project;
}
}
throw new RuntimeException(Messages.MavenProjectAdapter_0);
}
/** Read the configuration for the Initialize mojo.
*
* @param request the request.
* @param mojo the mojo execution.
* @param monitor the monitor.
* @return the configuration.
* @throws CoreException error in the eCore configuration.
*/
private SARLConfiguration readInitializeConfiguration(
ProjectConfigurationRequest request, MojoExecution mojo, IProgressMonitor monitor)
throws CoreException {
final SARLConfiguration config = new SARLConfiguration();
final MavenProject project = request.getMavenProject();
final File input = getParameterValue(project, "input", File.class, mojo, monitor, //$NON-NLS-1$
new File(SARLConfig.FOLDER_SOURCE_SARL));
final File output = getParameterValue(project, "output", File.class, mojo, monitor, //$NON-NLS-1$
new File(SARLConfig.FOLDER_SOURCE_GENERATED));
final File binOutput = getParameterValue(project, "binOutput", File.class, mojo, monitor, //$NON-NLS-1$
new File(SARLConfig.FOLDER_BIN));
final File testInput = getParameterValue(project, "testInput", File.class, mojo, monitor, //$NON-NLS-1$
new File(SARLConfig.FOLDER_TEST_SOURCE_SARL));
final File testOutput = getParameterValue(project, "testOutput", File.class, mojo, monitor, //$NON-NLS-1$
new File(SARLConfig.FOLDER_TEST_SOURCE_GENERATED));
final File testBinOutput = getParameterValue(project, "testBinOutput", File.class, mojo, monitor, //$NON-NLS-1$
new File(SARLConfig.FOLDER_TEST_BIN));
config.setInput(input);
config.setOutput(output);
config.setBinOutput(binOutput);
config.setTestInput(testInput);
config.setTestOutput(testOutput);
config.setTestBinOutput(testBinOutput);
return config;
}