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

The following examples show how to use org.apache.maven.plugin.AbstractMojo. 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
Source Project: javafx-maven-plugin   Source File: JavaFXRunMojoTestCase.java    License: Apache License 2.0 6 votes vote down vote up
private void setUpProject(File pomFile, AbstractMojo mojo) throws Exception {
    super.setUp();

    MockitoAnnotations.initMocks(this);

    ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
    buildingRequest.setResolveDependencies(true);
    when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
    DefaultRepositorySystemSession repositorySession = MavenRepositorySystemUtils.newSession();
    repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
            .newInstance(repositorySession, new LocalRepository(RepositorySystem.defaultUserLocalRepository)));
    when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);

    ProjectBuilder builder = lookup(ProjectBuilder.class);
    ProjectBuildingResult build = builder.build(pomFile, buildingRequest);
    MavenProject project = build.getProject();

    project.getBuild().setOutputDirectory(new File( "target/test-classes").getAbsolutePath());
    setVariableValueToObject(mojo, "project", project);
}
 
Example 2
Source Project: jax-maven-plugin   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
static Stream<String> getPluginRuntimeDependencyEntries(AbstractMojo mojo, MavenProject project, Log log,
        RepositorySystem repositorySystem, ArtifactRepository localRepository,
        List<ArtifactRepository> remoteRepositories) {
    PluginDescriptor pluginDescriptor = (PluginDescriptor) mojo.getPluginContext().get(PLUGIN_DESCRIPTOR);
    Plugin plugin = project.getBuild().getPluginsAsMap().get(pluginDescriptor.getPluginLookupKey());

    List<ArtifactResolutionResult> artifactResolutionResults = plugin //
            .getDependencies() //
            .stream() //
            .map(repositorySystem::createDependencyArtifact) //
            .map(a -> Util.resolve(log, a, repositorySystem, localRepository, remoteRepositories)) //
            .collect(Collectors.toList());

    Stream<Artifact> originalArtifacts = artifactResolutionResults.stream()
            .map(ArtifactResolutionResult::getOriginatingArtifact);

    Stream<Artifact> childArtifacts = artifactResolutionResults.stream()
            .flatMap(resolutionResult -> resolutionResult.getArtifactResolutionNodes().stream())
            .map(ResolutionNode::getArtifact);

    return Stream.concat(originalArtifacts, childArtifacts).map(Artifact::getFile).map(File::getAbsolutePath);
}
 
Example 3
Source Project: exec-maven-plugin   Source File: ExecJavaMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
private void setUpProject( File pomFile, AbstractMojo mojo )
    throws Exception
{
    super.setUp();
    
    MockitoAnnotations.initMocks( this );
    
    ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class );
    when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest );
    MavenRepositorySystemSession repositorySession = new MavenRepositorySystemSession();
    repositorySession.setLocalRepositoryManager( new SimpleLocalRepositoryManager( LOCAL_REPO ) );
    when( buildingRequest.getRepositorySession() ).thenReturn( repositorySession );
    
    ProjectBuilder builder = lookup( ProjectBuilder.class );

    MavenProject project = builder.build( pomFile, buildingRequest ).getProject();
    // this gets the classes for these tests of this mojo (exec plugin) onto the project classpath for the test
    project.getBuild().setOutputDirectory( new File( "target/test-classes" ).getAbsolutePath() );
    setVariableValueToObject( mojo, "project", project );
}
 
Example 4
Source Project: webstart   Source File: AbstractJnlpMojoTest.java    License: MIT License 6 votes vote down vote up
private void setUpProject( File pomFile, AbstractMojo mojo )
    throws Exception
{
    MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE );

    ArtifactRepositoryFactory artifactRepositoryFactory =
        (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.ROLE );

    ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy( true, "never", "never" );

    String localRepoUrl = "file://" + System.getProperty( "user.home" ) + "/.m2/repository";

    ArtifactRepository localRepository =
        artifactRepositoryFactory.createArtifactRepository( "local", localRepoUrl, new DefaultRepositoryLayout(),
                                                            policy, policy );

    ProfileManager profileManager = new DefaultProfileManager( getContainer() );

    MavenProject project = projectBuilder.buildWithDependencies( pomFile, localRepository, profileManager );

    //this gets the classes for these tests of this mojo (exec plugin) onto the project classpath for the test
    project.getBuild().setOutputDirectory( new File( "target/test-classes" ).getAbsolutePath() );
    setVariableValueToObject( mojo, "project", project );
}
 
Example 5
Source Project: roboconf-platform   Source File: AbstractTest.java    License: Apache License 2.0 6 votes vote down vote up
protected AbstractMojo findMojo( String projectName, String goalName ) throws Exception {

		// Find the project
		File baseDir = this.resources.getBasedir( projectName );
		Assert.assertNotNull( baseDir );
		Assert.assertTrue( baseDir.isDirectory());

		File pom = new File( baseDir, "pom.xml" );
		AbstractMojo mojo = (AbstractMojo) this.rule.lookupMojo( goalName, pom );
		Assert.assertNotNull( mojo );

		// Create the Maven project by hand (...)
		final MavenProject mvnProject = new MavenProject() ;
		mvnProject.setFile( pom ) ;

		this.rule.setVariableValueToObject( mojo, "project", mvnProject );
		Assert.assertNotNull( this.rule.getVariableValueFromObject( mojo, "project" ));

		// Initialize the project
		InitializeMojo initMojo = new InitializeMojo();
		initMojo.setProject( mvnProject );
		initMojo.execute();

		return mojo;
	}
 
Example 6
Source Project: servicecomb-toolkit   Source File: TestResourcesEx.java    License: Apache License 2.0 5 votes vote down vote up
private AbstractMojo mockMojo(String pluginGoal) {
  switch (pluginGoal) {
    case "generate":
      return new GenerateMojo();
    case "verify":
      return new VerifyMojo();
    default:
      throw new RuntimeException("undefined plugin goal");
  }
}
 
Example 7
Source Project: javafx-maven-plugin   Source File: JavaFXRunMojoTestCase.java    License: Apache License 2.0 5 votes vote down vote up
private String execute(AbstractMojo mojo) throws MojoFailureException, MojoExecutionException, InterruptedException {
    PrintStream out = System.out;
    StringOutputStream stringOutputStream = new StringOutputStream();
    System.setOut(new PrintStream(stringOutputStream));
    mojo.setLog(new DefaultLog(new ConsoleLogger(Logger.LEVEL_ERROR, "javafx:run")));

    try {
        mojo.execute();
    } finally {
        Thread.sleep(300);
        System.setOut(out);
    }

    return stringOutputStream.toString();
}
 
Example 8
Source Project: flow   Source File: BuildFrontendMojoTest.java    License: Apache License 2.0 5 votes vote down vote up
static void setProject(AbstractMojo mojo, File baseFolder)
        throws Exception {
    Build buildMock = mock(Build.class);
    when(buildMock.getFinalName()).thenReturn("finalName");
    MavenProject project = mock(MavenProject.class);
    when(project.getBasedir()).thenReturn(baseFolder);
    when(project.getBuild()).thenReturn(buildMock);
    when(project.getRuntimeClasspathElements()).thenReturn(getClassPath());
    ReflectionUtils.setVariableValueInObject(mojo, "project", project);
}
 
Example 9
Source Project: roboconf-platform   Source File: ResolveMojoTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test( expected = MojoExecutionException.class )
public void testWithInvalidRoboconfDependencies() throws Exception {

	// Prepare the project
	final String projectName = "project--valid";

	File baseDir = this.resources.getBasedir( projectName );
	Assert.assertNotNull( baseDir );
	Assert.assertTrue( baseDir.isDirectory());

	AbstractMojo mojo = findMojo( projectName, "resolve" );
	this.rule.setVariableValueToObject( mojo, "repoSystem", newRepositorySystem());
	this.rule.setVariableValueToObject( mojo, "repositories", new ArrayList<RemoteRepository>( 0 ));

	// Add dependencies
	MavenProject project = (MavenProject) this.rule.getVariableValueFromObject( mojo, "project" );
	project.setDependencyArtifacts( new HashSet<Artifact> ());

	Artifact notRbcfArtifact1 = new DefaultArtifact( "net.roboconf", "roboconf-core", "0.2", "runtime", "jar", null, new DefaultArtifactHandler());
	project.getDependencyArtifacts().add( notRbcfArtifact1 );

	Artifact notRbcfArtifact2 = new DefaultArtifact( "net.roboconf", "roboconf-core", "0.2", "runtime", "jar", null, new DefaultArtifactHandler());
	notRbcfArtifact2.setFile( new File( "file that does not exist" ));
	project.getDependencyArtifacts().add( notRbcfArtifact2 );

	Artifact notRbcfArtifact3 = new DefaultArtifact( "net.roboconf", "roboconf-core", "0.2", "runtime", "jar", null, new DefaultArtifactHandler());
	File temp = this.folder.newFile( "toto.zip" );
	Assert.assertTrue( temp.exists());

	notRbcfArtifact3.setFile( temp );
	project.getDependencyArtifacts().add( notRbcfArtifact3 );

	// Execute it
	File targetDir = new File( baseDir, MavenPluginConstants.TARGET_MODEL_DIRECTORY + "/" + Constants.PROJECT_DIR_GRAPH );
	Assert.assertFalse( targetDir.isDirectory());
	mojo.execute();
}
 
Example 10
Source Project: cougar   Source File: TestExceptionMessageHandling.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    final String baseDir = System.getProperty("user.dir");

    mojo = new IdlToDSMojo();
    mojo.setBaseDir(baseDir);
    mojo.setWsdlXslResource(RSRC);
    mojo.setXsdXslResource(RSRC);

    Field projectField = IdlToDSMojo.class.getDeclaredField("project");
    projectField.setAccessible(true);
    projectField.set(mojo, mock(MavenProject.class));

    Field iddAsResourceField = IdlToDSMojo.class.getDeclaredField("iddAsResource");
    iddAsResourceField.setAccessible(true);
    iddAsResourceField.setBoolean(mojo, true);

    Field logField = AbstractMojo.class.getDeclaredField("log");
    logField.setAccessible(true);
    logField.set(mojo, mock(Log.class));

    Service s = new Service();
    Field f = Service.class.getDeclaredField("serviceName");
    f.setAccessible(true);
    f.set(s, SERVICE_NAME);

    mojo.setServices(new Service[]{s});
}
 
Example 11
Source Project: mvn-golang   Source File: MavenUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
   * Scan project dependencies to find artifacts generated by mvn golang
   * project.
   *
   * @param mavenProject maven project, must not be null
   * @param includeTestDependencies flag to process dependencies marked for test
   * phases
   * @param mojo calling mojo, must not be null
   * @param session maven session, must not be null
   * @param execution maven execution, must not be null
   * @param resolver artifact resolver, must not be null
   * @param remoteRepositories list of remote repositories, must not be null
   * @return list of files found in artifacts generated by mvn golang plugin
   * @throws ArtifactResolverException exception thrown if some artifact can't
   * be resolved
   */
  @Nonnull
  @MustNotContainNull
  public static List<Tuple<Artifact, File>> scanForMvnGoArtifacts(
          @Nonnull final MavenProject mavenProject,
          final boolean includeTestDependencies,
          @Nonnull final AbstractMojo mojo,
          @Nonnull final MavenSession session,
          @Nonnull final MojoExecution execution,
          @Nonnull final ArtifactResolver resolver,
          @Nonnull @MustNotContainNull final List<ArtifactRepository> remoteRepositories
  ) throws ArtifactResolverException {
    final List<Tuple<Artifact, File>> result = new ArrayList<>();
//    final String phase = execution.getLifecyclePhase();

    final Set<String> alreadyFoundArtifactRecords = new HashSet<>();

    MavenProject currentProject = mavenProject;
    while (currentProject != null && !Thread.currentThread().isInterrupted()) {
      final Set<Artifact> projectDependencies = currentProject.getDependencyArtifacts();
      final List<Artifact> artifacts = new ArrayList<>(projectDependencies == null ? Collections.emptySet() : projectDependencies);
      mojo.getLog().debug("Detected dependency artifacts: " + artifacts);

      while (!artifacts.isEmpty() && !Thread.currentThread().isInterrupted()) {
        final Artifact artifact = artifacts.remove(0);

        if (Artifact.SCOPE_TEST.equals(artifact.getScope()) && !includeTestDependencies) {
          continue;
        }

        if (artifact.getType().equals(AbstractGolangMojo.GOARTIFACT_PACKAGING)) {
          final ArtifactResult artifactResult = resolver.resolveArtifact(makeResolveArtifactProjectBuildingRequest(session, remoteRepositories), artifact);
          final File zipFillePath = artifactResult.getArtifact().getFile();

          mojo.getLog().debug("Detected MVN-GOLANG marker inside ZIP dependency: " + artifact.getGroupId() + ':' + artifact.getArtifactId() + ':' + artifact.getVersion() + ':' + artifact.getType());

          if (ZipUtil.containsEntry(zipFillePath, GolangMvnInstallMojo.MVNGOLANG_DEPENDENCIES_FILE)) {
            final byte[] artifactFlagFile = ZipUtil.unpackEntry(zipFillePath, GolangMvnInstallMojo.MVNGOLANG_DEPENDENCIES_FILE, StandardCharsets.UTF_8);

            for (final String str : new String(artifactFlagFile, StandardCharsets.UTF_8).split("\\R")) {
              if (str.trim().isEmpty() || alreadyFoundArtifactRecords.contains(str)) {
                continue;
              }
              mojo.getLog().debug("Adding mvn-golang dependency: " + str);
              alreadyFoundArtifactRecords.add(str);
              try {
                artifacts.add(parseArtifactRecord(str, new MvnGolangArtifactHandler()));
              } catch (InvalidVersionSpecificationException ex) {
                throw new ArtifactResolverException("Can't make artifact: " + str, ex);
              }
            }
          }

          final File artifactFile = artifactResult.getArtifact().getFile();
          mojo.getLog().debug("Artifact file: " + artifactFile);
          if (doesContainFile(result, artifactFile)) {
            mojo.getLog().debug("Artifact file ignored as duplication: " + artifactFile);
          } else {
            result.add(Tuple.of(artifact, artifactFile));
          }
        }
      }
      currentProject = currentProject.hasParent() ? currentProject.getParent() : null;
    }

    return result;
  }
 
Example 12
Source Project: roboconf-platform   Source File: ResolveMojoTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testWithValidRoboconfDependencies() throws Exception {

	// Prepare the project
	final String projectName = "project--valid";

	File baseDir = this.resources.getBasedir( projectName );
	Assert.assertNotNull( baseDir );
	Assert.assertTrue( baseDir.isDirectory());

	AbstractMojo mojo = findMojo( projectName, "resolve" );
	this.rule.setVariableValueToObject( mojo, "repoSystem", newRepositorySystem());
	this.rule.setVariableValueToObject( mojo, "repositories", new ArrayList<RemoteRepository>( 0 ));

	// Create a Roboconf application
	File dir = this.folder.newFolder();
	File targetZipFile = this.folder.newFile();
	Assert.assertTrue( targetZipFile.delete());

	CreationBean bean = new CreationBean()
			.projectDescription( "some desc" ).projectName( "my-project" )
			.groupId( "net.roboconf" ).projectVersion( "1.0-SNAPSHOT" ).mavenProject( false );

	ProjectUtils.createProjectSkeleton( dir, bean );
	ZipArchiver zipArchiver = new ZipArchiver();
	zipArchiver.addDirectory( dir );
	zipArchiver.setCompress( true );
	zipArchiver.setDestFile( targetZipFile );
	zipArchiver.createArchive();

	Assert.assertTrue( targetZipFile.isFile());

	// Add dependencies
	MavenProject project = (MavenProject) this.rule.getVariableValueFromObject( mojo, "project" );
	project.setDependencyArtifacts( new HashSet<Artifact> ());

	Artifact rbcfArtifact3 = new DefaultArtifact( "net.roboconf", "roboconf-core", "0.2", "runtime", "jar", null, new DefaultArtifactHandler());
	rbcfArtifact3.setFile( targetZipFile );
	project.getDependencyArtifacts().add( rbcfArtifact3 );

	// Add it to our "local" repository
	this.artifactIdToArtifact.put( rbcfArtifact3.getArtifactId(), rbcfArtifact3 );

	// Execute it
	File targetDir = new File( baseDir, MavenPluginConstants.TARGET_MODEL_DIRECTORY + "/" + Constants.PROJECT_DIR_GRAPH );
	Assert.assertFalse( targetDir.isDirectory());
	mojo.execute();

	// Verify the import was copied in the right location
	File importDir = new File( targetDir, "net.roboconf/roboconf-core" );
	Assert.assertTrue( importDir.isDirectory());
	Assert.assertTrue( new File( importDir, "main.graph" ).isFile());
}