Java Code Examples for org.apache.maven.plugin.MojoFailureException

The following examples show how to use org.apache.maven.plugin.MojoFailureException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@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 );
}
 
Example 2
Source Project: app-maven-plugin   Source File: GenRepoInfoFileMojo.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
  }
}
 
Example 3
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!");
  }
}
 
Example 4
@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);
    }
}
 
Example 5
Source Project: ironjacamar   Source File: Stop.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@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);
   }
}
 
Example 6
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;
}
 
Example 7
Source Project: kumuluzee   Source File: RunJarMojo.java    License: MIT License 6 votes vote down vote up
@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)
    );
}
 
Example 8
Source Project: wisdom   Source File: KarmaIntegrationTestMojo.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 9
Source Project: appassembler   Source File: AbstractScriptGeneratorMojo.java    License: MIT License 6 votes vote down vote up
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 );
    }
}
 
Example 10
Source Project: versions-maven-plugin   Source File: UnlockSnapshotsMojo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @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() );
    }
}
 
Example 11
Source Project: flatten-maven-plugin   Source File: FlattenMojo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@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 );
    }
}
 
Example 12
Source Project: gitflow-maven-plugin   Source File: AbstractGitFlowMojo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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.");
            }
        }
    }
}
 
Example 13
/**
 * 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();
}
 
Example 14
Source Project: deadcode4j   Source File: An_AbstractSlf4jMojo.java    License: Apache License 2.0 6 votes vote down vote up
@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!");
}
 
Example 15
Source Project: japicmp   Source File: JApiCmpMojo.java    License: Apache License 2.0 6 votes vote down vote up
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.");
	}
}
 
Example 16
Source Project: wisdom   Source File: CSSMinifierMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
@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.

}
 
Example 17
Source Project: protostuff-compiler   Source File: HtmlGeneratorMojo.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 18
Source Project: wildfly-swarm   Source File: AnalyzeMojo.java    License: Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example 19
@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);
}
 
Example 20
/**
 * 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);
        }
    }
}
 
Example 21
Source Project: RADL   Source File: RadlFromCodePlugin.java    License: Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 22
/**
 * @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 );
        }

    }
}
 
Example 23
Source Project: sarl   Source File: CleanMojo.java    License: Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example 24
@Before
public void setUp()
    throws Exception
{
    mojo = new AbstractVersionsDependencyUpdaterMojo()
    {
        protected void update( ModifiedPomXMLEventReader pom )
            throws MojoExecutionException, MojoFailureException, XMLStreamException
        {
        }
    };
}
 
Example 25
Source Project: docker-maven-plugin   Source File: ConfigHelper.java    License: Apache License 2.0 5 votes vote down vote up
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.");
    }
}
 
Example 26
Source Project: git-code-format-maven-plugin   Source File: AbstractFormatMojo.java    License: MIT License 5 votes vote down vote up
@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);
  }
}
 
Example 27
Source Project: fabric8-forge   Source File: DownloadArchetypesMojo.java    License: Apache License 2.0 5 votes vote down vote up
private File init() throws MojoFailureException {
    File m2 = new File(localRepositoryDirectory);
    if (!m2.exists()) {
        m2.mkdir();
    }
    return m2;
}
 
Example 28
Source Project: wildfly-swarm   Source File: StartMojo.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 29
/**
 * 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();
}
 
Example 30
Source Project: joinfaces   Source File: ClasspathScanMojoTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}