下面列出了怎么用org.apache.maven.plugin.MojoFailureException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void unknownPlaceholderIsLeftAsIs()
throws MojoFailureException
{
Properties properties = new Properties();
properties.setProperty( "p1", "${p2}" );
properties.setProperty( "p2", "value" );
properties.setProperty( "p3", "${unknown}" );
String value1 = resolver.getPropertyValue( "p1", properties, new Properties() );
String value2 = resolver.getPropertyValue( "p2", properties, new Properties() );
String value3 = resolver.getPropertyValue( "p3", properties, new Properties() );
assertEquals( "value", value1 );
assertEquals( "value", value2 );
assertEquals( "${unknown}", value3 );
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (skip) {
getLog().info("Skipping appengine:genRepoInfoFile");
return;
}
try {
getAppEngineFactory()
.genRepoInfoFile()
.generate(
GenRepoInfoFileConfiguration.builder()
.outputDirectory(outputDirectory == null ? null : outputDirectory.toPath())
.sourceDirectory(sourceDirectory == null ? null : sourceDirectory.toPath())
.build());
} catch (AppEngineException aee) {
if (!ignoreErrors) {
throw new MojoExecutionException(HOW_TO_FIX_MSG, aee);
} else {
logger.warning(HOW_TO_FIX_MSG);
}
}
}
private void failIfSnapshotsAreReferenced(Multimap<MavenProject, ArtifactCoordinates> snapshotsByProject,
Map<MavenProject, PomPropertyResolver> propertyResolvers) throws MojoFailureException {
if (!snapshotsByProject.values().isEmpty()) {
this.log.error(
"\tThere are references to SNAPSHOT plugins! The following list contains all SNAPSHOT plugins grouped by module:");
for (MavenProject project : snapshotsByProject.keySet()) {
PomPropertyResolver propertyResolver = propertyResolvers.get(project);
Collection<ArtifactCoordinates> snapshots = snapshotsByProject.get(project);
if (!snapshots.isEmpty()) {
this.log.error("\t\t[PROJECT] " + ProjectToString.INSTANCE.apply(project));
for (ArtifactCoordinates plugin : snapshots) {
String resolvedVersion = propertyResolver.expandPropertyReferences(plugin.getVersion());
String coordinates = plugin.toString();
if (!Objects.equal(resolvedVersion, plugin.getVersion())) {
coordinates = coordinates + " (resolves to " + resolvedVersion + ")";
}
this.log.error("\t\t\t[PLUGIN] " + coordinates);
}
}
}
throw new MojoFailureException("The project cannot be released due to one or more SNAPSHOT plugins!");
}
}
@Override
public void executeAll() throws MojoFailureException {
if (name == null || name.isEmpty()) {
throw new MojoFailureException("Connector name must be specified as the parameter");
}
if (name.startsWith("camel-")) {
name = name.substring("camel-".length());
}
if (name.endsWith(KAFKA_CONNECTORS_SUFFIX)) {
name = name.substring(0, name.length() - KAFKA_CONNECTORS_SUFFIX.length());
}
try {
createConnector();
} catch (Exception e) {
throw new MojoFailureException("Fail to create connector " + name, e);
}
}
/**
* {@inheritDoc}
*/
public void execute() throws MojoExecutionException, MojoFailureException
{
if (getHome() == null)
throw new MojoFailureException("Home isn't set");
try
{
ProcessController pc = ProcessController.getInstance();
int exitCode = pc.stop(getHome());
if (exitCode != 0)
throw new MojoFailureException("IronJacamar instance exit code: " + exitCode);
getLog().info("Stopped IronJacamar instance from: " + getHome());
}
catch (Throwable t)
{
throw new MojoFailureException(t.getMessage(), t);
}
}
private String getNextSnapshotVersion(String currentVersion) throws MojoFailureException, VersionParseException {
// get next snapshot version
final String nextSnapshotVersion;
if (!settings.isInteractiveMode()
&& StringUtils.isNotBlank(developmentVersion)) {
nextSnapshotVersion = developmentVersion;
} else {
GitFlowVersionInfo versionInfo = new GitFlowVersionInfo(
currentVersion);
if (digitsOnlyDevVersion) {
versionInfo = versionInfo.digitsVersionInfo();
}
nextSnapshotVersion = versionInfo
.nextSnapshotVersion(versionDigitToIncrement);
}
if (StringUtils.isBlank(nextSnapshotVersion)) {
throw new MojoFailureException(
"Next snapshot version is blank.");
}
return nextSnapshotVersion;
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
repackage();
executeMojo(
plugin(
groupId("org.codehaus.mojo"),
artifactId("exec-maven-plugin"),
version("1.6.0")
),
goal("exec"),
configuration(
element("executable", "java"),
element(name("arguments"),
element(name("argument"), "-jar"),
element(name("argument"), outputDirectory + "/" + finalName + ".jar")
)
),
executionEnvironment(project, session, buildPluginManager)
);
}
public void execute() throws MojoFailureException, MojoExecutionException {
removeFromWatching();
try {
startChameleon();
super.execute();
} catch (IOException | BundleException e) {
// Others exception are related to the Chameleon startup / handling
getLog().error("Cannot start the Chameleon instance", e);
throw new MojoExecutionException("Cannot start the Chameleon instance", e);
} finally {
// This property is set when launching the Chameleon instance to find the configuration. Clear it.
System.clearProperty("application.configuration");
stopChameleon();
}
}
protected void installDependencies( final String outputDirectory, final String repositoryName )
throws MojoExecutionException, MojoFailureException
{
if ( generateRepository )
{
// The repo where the jar files will be installed
ArtifactRepository artifactRepository =
artifactRepositoryFactory.createDeploymentArtifactRepository( "appassembler", "file://"
+ outputDirectory + "/" + repositoryName, getArtifactRepositoryLayout(), false );
for ( Artifact artifact : artifacts )
{
installArtifact( artifact, artifactRepository, this.useTimestampInSnapshotFileName );
}
// install the project's artifact in the new repository
installArtifact( projectArtifact, artifactRepository );
}
}
/**
* @param pom the pom to update.
* @throws MojoExecutionException when things go wrong
* @throws MojoFailureException when things go wrong in a very bad way
* @throws XMLStreamException when things go wrong with XML streaming
* @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader)
*/
protected void update( ModifiedPomXMLEventReader pom )
throws MojoExecutionException, MojoFailureException, XMLStreamException
{
if ( getProject().getDependencyManagement() != null && isProcessingDependencyManagement() )
{
unlockSnapshots( pom, getProject().getDependencyManagement().getDependencies() );
}
if ( getProject().getDependencies() != null && isProcessingDependencies() )
{
unlockSnapshots( pom, getProject().getDependencies() );
}
if ( getProject().getParent() != null && isProcessingParent() )
{
unlockParentSnapshot( pom, getProject().getParent() );
}
}
/**
* {@inheritDoc}
*/
public void execute()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Generating flattened POM of project " + this.project.getId() + "..." );
File originalPomFile = this.project.getFile();
Model flattenedPom = createFlattenedPom( originalPomFile );
String headerComment = extractHeaderComment( originalPomFile );
File flattenedPomFile = getFlattenedPomFile();
writePom( flattenedPom, flattenedPomFile, headerComment );
if ( isUpdatePomFile() )
{
this.project.setPomFile( flattenedPomFile );
}
}
/**
* Executes git fetch and compares local branch with the remote.
*
* @param branchName
* Branch name to fetch and compare.
* @throws MojoFailureException
* @throws CommandLineException
*/
protected void gitFetchRemoteAndCompare(final String branchName)
throws MojoFailureException, CommandLineException {
if (gitFetchRemote(branchName)) {
getLog().info(
"Comparing local branch '" + branchName + "' with remote '"
+ gitFlowConfig.getOrigin() + "/" + branchName
+ "'.");
String revlistout = executeGitCommandReturn("rev-list",
"--left-right", "--count", branchName + "..."
+ gitFlowConfig.getOrigin() + "/" + branchName);
String[] counts = org.apache.commons.lang3.StringUtils.split(
revlistout, '\t');
if (counts != null && counts.length > 1) {
if (!"0".equals(org.apache.commons.lang3.StringUtils
.deleteWhitespace(counts[1]))) {
throw new MojoFailureException("Remote branch '"
+ gitFlowConfig.getOrigin() + "/" + branchName
+ "' is ahead of the local branch '" + branchName
+ "'. Execute git pull.");
}
}
}
}
/**
* Check that no Exception is thrown when a file that does not exist is
* injected into {@link GenerateDdlMojo#persistenceXml} and then executed.
*
* @throws org.apache.maven.plugin.MojoExecutionException
* @throws org.apache.maven.plugin.MojoFailureException
* @throws java.io.IOException
*/
@Test
public void persistenceXmlDoesntExist() throws MojoExecutionException,
MojoFailureException,
IOException {
mojo.setOutputDirectory(new File(TEST_DIR));
final String[] packages = new String[]{
"de.jpdigital.maven.plugins.hibernate5ddl.tests.entities",
"de.jpdigital.maven.plugins.hibernate5ddl.tests.entities2"
};
mojo.setPackages(packages);
final String[] dialects = new String[]{
"mysql5"
};
mojo.setDialects(dialects);
mojo.setPersistenceXml(new File("file/doesnt/exist"));
mojo.execute();
}
@Test
public void wrapsMavenLogger() throws MojoFailureException, MojoExecutionException {
Log logMock = mock(Log.class);
when(logMock.isInfoEnabled()).thenReturn(true);
AbstractSlf4jMojo objectUnderTest = new AbstractSlf4jMojo() {
@Override
protected void doExecute() throws MojoExecutionException, MojoFailureException {
LoggerFactory.getLogger(getClass()).info("Hello JUnit!");
}
};
objectUnderTest.setLog(logMock);
objectUnderTest.execute();
verify(logMock).info("Hello JUnit!");
}
private void filterVersionPattern(List<ArtifactVersion> availableVersions, PluginParameters pluginParameters) throws MojoFailureException {
if (pluginParameters.getParameterParam() != null && pluginParameters.getParameterParam().getOldVersionPattern() != null) {
String versionPattern = pluginParameters.getParameterParam().getOldVersionPattern();
Pattern pattern;
try {
pattern = Pattern.compile(versionPattern);
} catch (PatternSyntaxException e) {
throw new MojoFailureException("Could not compile provided versionPattern '" + versionPattern + "' as regular expression: " + e.getMessage(), e);
}
for (Iterator<ArtifactVersion> versionIterator = availableVersions.iterator(); versionIterator.hasNext(); ) {
ArtifactVersion version = versionIterator.next();
Matcher matcher = pattern.matcher(version.toString());
if (!matcher.matches()) {
versionIterator.remove();
if (getLog().isDebugEnabled()) {
getLog().debug("Filtering version '" + version.toString() + "' because it does not match configured versionPattern '" + versionPattern + "'.");
}
}
}
} else {
getLog().debug("Parameter <oldVersionPattern> not configured, i.e. no version filtered.");
}
}
@Test
public void testCustomArguments() throws MojoFailureException, MojoExecutionException, IOException {
cleanup();
less.execute();
mojo.cleanCssArguments = "--debug -c ie7 -b";
mojo.execute();
File site = new File(FAKE_PROJECT_TARGET, "classes/assets/css/site-min.css");
assertThat(site).isFile();
assertThat(FileUtils.readFileToString(site))
.contains("h1{color:red}");
File style = new File(FAKE_PROJECT_TARGET, "classes/assets/less/style-min.css");
assertThat(style).isFile();
assertThat(FileUtils.readLines(style)).hasSize(2); // We don't remove line break.
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
super.execute();
ProtostuffCompiler compiler = new ProtostuffCompiler();
final Path sourcePath = getSourcePath();
List<String> protoFiles = findProtoFiles(sourcePath);
ModuleConfiguration moduleConfiguration = ImmutableModuleConfiguration.builder()
.name("html")
.includePaths(singletonList(sourcePath))
.generator(CompilerModule.HTML_COMPILER)
.output(target.getAbsolutePath())
.putOptions(HtmlGenerator.PAGES, pages)
.addAllProtoFiles(protoFiles)
.build();
compiler.compile(moduleConfiguration);
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("Analyzing for " + this.gav);
this.dir = Paths.get(this.projectBuildDir, "wildfly-swarm-archive");
this.modulesDir = this.dir.resolve("modules");
try {
walkModulesDir();
walkDependencies();
} catch (IOException e) {
throw new MojoFailureException("Unable to inspect modules/ dir", e);
}
Graph.Artifact artifact = this.graph.getClosestArtifact(this.gav);
if (artifact == null) {
throw new MojoFailureException("Unable to find artifact: " + this.gav);
}
DumpGraphVisitor visitor = new DumpGraphVisitor();
artifact.accept(visitor);
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
Log log = getLog();
File testOutputFolder = new File(getProject().getBuild().getTestOutputDirectory());
if (!testOutputFolder.isDirectory()) {
log.warn("Test folder doesn't exist -- nothing to instrument");
return;
}
List<String> classpath;
try {
classpath = getProject().getTestClasspathElements();
} catch (DependencyResolutionRequiredException ex) {
throw new MojoExecutionException("Dependency resolution problem", ex);
}
log.debug("Processing test output folder ... ");
instrumentPath(log, classpath, testOutputFolder);
}
/**
* Executes CLI commands based on the configuration.
*
* @param config the configuration used to execute the CLI commands
*
* @throws MojoFailureException if the JBoss Home directory is required and invalid
* @throws MojoExecutionException if an error occurs executing the CLI commands
*/
public void execute(final CommandConfiguration config) throws MojoFailureException, MojoExecutionException {
if (config.isOffline()) {
// The jbossHome is required for offline CLI
if (!ServerHelper.isValidHomeDirectory(config.getJBossHome())) {
throw new MojoFailureException("Invalid JBoss Home directory is not valid: " + config.getJBossHome());
}
executeInNewProcess(config);
} else {
if (config.isFork()) {
executeInNewProcess(config);
} else {
executeInProcess(config);
}
}
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
FromJavaRadlExtractor radlFromJavaExtractor = new FromJavaRadlExtractor();
File tempArgumentsFile = null;
try {
tempArgumentsFile = generateProjectArgumentsFile();
radlFromJavaExtractor.run(
new Arguments(new String[] { "@" + tempArgumentsFile.getAbsolutePath() }));
getLog().info(String.format(MSG, docsDir));
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
finally {
IO.delete(tempArgumentsFile);
}
}
/**
* @param pom the pom to update.
* @throws MojoExecutionException when things go wrong
* @throws MojoFailureException when things go wrong in a very bad way
* @throws XMLStreamException when things go wrong with XML streaming
* @see AbstractVersionsUpdaterMojo#update(ModifiedPomXMLEventReader)
* @since 1.0-alpha-1
*/
protected void update( ModifiedPomXMLEventReader pom )
throws MojoExecutionException, MojoFailureException, XMLStreamException
{
Map<Property, PropertyVersions> propertyVersions =
this.getHelper().getVersionPropertiesMap( getProject(), properties, includeProperties, excludeProperties,
autoLinkItems );
for ( Map.Entry<Property, PropertyVersions> entry : propertyVersions.entrySet() )
{
Property property = entry.getKey();
PropertyVersions version = entry.getValue();
final String currentVersion = getProject().getProperties().getProperty( property.getName() );
if ( currentVersion == null )
{
continue;
}
boolean canUpdateProperty = true;
for ( ArtifactAssociation association : version.getAssociations() )
{
if ( !( isIncluded( association.getArtifact() ) ) )
{
getLog().info( "Not updating the property ${" + property.getName()
+ "} because it is used by artifact " + association.getArtifact().toString()
+ " and that artifact is not included in the list of " + " allowed artifacts to be updated." );
canUpdateProperty = false;
break;
}
}
if ( canUpdateProperty )
{
int segment =
determineUnchangedSegment( allowMajorUpdates, allowMinorUpdates, allowIncrementalUpdates );
updatePropertyToNewestVersion( pom, property, version, currentVersion, allowDowngrade, segment );
}
}
}
@Override
protected void executeMojo() throws MojoExecutionException, MojoFailureException {
final String cleanerGroupId = this.mavenHelper.getConfig("cleaner.groupId"); //$NON-NLS-1$
final String cleanerArtifactId = this.mavenHelper.getConfig("cleaner.artifactId"); //$NON-NLS-1$
final String cleanerVersion = this.mavenHelper.getPluginDependencyVersion(cleanerGroupId, cleanerArtifactId);
final String cleanerMojo = this.mavenHelper.getConfig("cleaner.mojo"); //$NON-NLS-1$
executeMojo(
cleanerGroupId, cleanerArtifactId, cleanerVersion, cleanerMojo,
MessageFormat.format(
this.mavenHelper.getConfig("cleaner.configuration"), //$NON-NLS-1$
getOutput().getAbsolutePath(),
getTestOutput().getAbsolutePath()));
}
@Before
public void setUp()
throws Exception
{
mojo = new AbstractVersionsDependencyUpdaterMojo()
{
protected void update( ModifiedPomXMLEventReader pom )
throws MojoExecutionException, MojoFailureException, XMLStreamException
{
}
};
}
public static void validateExternalPropertyActivation(MavenProject project, List<ImageConfiguration> images) throws MojoFailureException {
String prop = getExternalConfigActivationProperty(project);
if(prop == null) {
return;
}
if(images.size() == 1) {
return;
}
// With more than one image, externally activating propertyConfig get's tricky. We can only allow it to affect
// one single image. Go through each image and check if they will be controlled by default properties.
// If more than one image matches, fail.
int imagesWithoutExternalConfig = 0;
for (ImageConfiguration image : images) {
if(PropertyConfigHandler.canCoexistWithOtherPropertyConfiguredImages(image.getExternalConfig())) {
continue;
}
// else, it will be affected by the external property.
imagesWithoutExternalConfig++;
}
if(imagesWithoutExternalConfig > 1) {
throw new MojoFailureException("Configuration error: Cannot use property "+EXTERNALCONFIG_ACTIVATION_PROPERTY+" on projects with multiple images without explicit image external configuration.");
}
}
@Override
protected final void doExecute() throws MojoExecutionException, MojoFailureException {
String pattern = "glob:" + globPattern;
getLog().debug("Using pattern '" + pattern + "'");
PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + globPattern);
for (Path sourceDir : sourceDirs()) {
walk(sourceDir, pathMatcher);
}
}
private File init() throws MojoFailureException {
File m2 = new File(localRepositoryDirectory);
if (!m2.exists()) {
m2.mkdir();
}
return m2;
}
protected SwarmExecutor jarExecutor() throws MojoFailureException {
getLog().info("Starting .jar");
final String finalName = this.project.getBuild().getFinalName();
return executor(Paths.get(this.project.getBuild().getOutputDirectory()),
finalName.endsWith(".jar") ? finalName : finalName + ".jar",
true);
}
/**
* Execute goal.
*
* @throws MojoExecutionException execution of the main class or one of the
* threads it generated failed.
* @throws MojoFailureException something bad happened...
*/
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (!project.getArtifactId().equals(connectorsProjectName)) {
getLog().debug("Skipping project " + project.getArtifactId() + " since it is not " + connectorsProjectName + " can be configured with <connectors-project-name> option.");
return;
}
executeComponentsReadme();
}
@Test
void apply_skipTrue() throws IllegalAccessException, NoSuchFieldException, IOException, MojoExecutionException, MojoFailureException {
ClasspathScanMojo mojo = new ClasspathScanMojo();
setSkip(mojo, true);
File outputDirectory = setOutputDirectory(mojo);
mojo.execute();
File metaInfFolder = new File(outputDirectory, "META-INF");
assertThat(metaInfFolder.exists())
.isEqualTo(Boolean.FALSE);
}