org.apache.maven.execution.DefaultMavenExecutionRequest Java Examples

The following examples show how to use org.apache.maven.execution.DefaultMavenExecutionRequest. 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 File: InitializeMojoTest.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
private InitializeMojo createMojoInstance() throws PlexusContainerException {
    InitializeMojo mojo = new InitializeMojo();
    mojo.project = new MavenProject();
    mojo.repositorySystem = new DefaultRepositorySystem();
    mojo.repositorySystemSession = new DefaultRepositorySystemSession();
    mojo.buildPluginManager = new DefaultBuildPluginManager();
    mojo.container = new DefaultPlexusContainer(new DefaultContainerConfiguration());
    mojo.mavenSession = new MavenSession(mojo.container, mojo.repositorySystemSession, new DefaultMavenExecutionRequest(),
        new DefaultMavenExecutionResult());

    mojo.lifecycleExecutor = new DefaultLifecycleExecutor();
    mojo.scmManager = new DefaultScmManager();
    mojo.remoteRepositories = Collections.emptyList();
    mojo.projectBuildDir = OUT.getAbsolutePath();

    Build build = new Build();
    build.setOutputDirectory(OUT.getAbsolutePath());
    mojo.project.setBuild(build);

    return mojo;
}
 
Example #2
Source File: InstallDeployTest.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: PropertiesUtilsTest.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "deprecation" )
private ManipulationSession createUpdateSession() throws Exception
{
    ManipulationSession session = new ManipulationSession();

    session.setState( new DependencyState( p ) );
    session.setState( new VersioningState( p ) );
    session.setState( new CommonState( p ) );

    final MavenExecutionRequest req =
                    new DefaultMavenExecutionRequest().setUserProperties( p ).setRemoteRepositories( Collections.emptyList() );

    final PlexusContainer container = new DefaultPlexusContainer();
    final MavenSession mavenSession = new MavenSession( container, null, req, new DefaultMavenExecutionResult() );

    session.setMavenSession( mavenSession );

    return session;
}
 
Example #4
Source File: ProjectComparatorTest.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "deprecation" )
private ManipulationSession createUpdateSession() throws Exception
{
    ManipulationSession session = new ManipulationSession();

    final Properties p = new Properties();
    p.setProperty( "strictAlignment", "true" );
    p.setProperty( "strictViolationFails", "true" );
    p.setProperty( "versionSuffix", "redhat-1" );
    p.setProperty( "scanActiveProfiles", "true" );
    session.setState( new DependencyState( p ) );
    session.setState( new VersioningState( p ) );
    session.setState( new CommonState( p ) );

    final MavenExecutionRequest req =
                    new DefaultMavenExecutionRequest().setUserProperties( p ).setRemoteRepositories( Collections.emptyList() );

    final PlexusContainer container = new DefaultPlexusContainer();
    final MavenSession mavenSession = new MavenSession( container, null, req, new DefaultMavenExecutionResult() );

    session.setMavenSession( mavenSession );

    return session;
}
 
Example #5
Source File: JBBPGenerateMojoTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
private JBBPGenerateMojo findMojo(final String pomName, final String goal) throws Exception {
  final File pomFile = new File(this.getClass().getResource(pomName).toURI());
  final MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
  final ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
  final ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
  final MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject();
  return (JBBPGenerateMojo) this.lookupConfiguredMojo(project, goal);
}
 
Example #6
Source File: A_UsageStatisticsManager.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation") // there's no non-deprecated constructor for MavenSession :|
private void givenModes(NetworkModes networkMode, InteractivityModes interactivity) throws IllegalAccessException {
    DefaultMavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest();
    mavenExecutionRequest.setOffline(NetworkModes.OFFLINE == networkMode);
    mavenExecutionRequest.setInteractiveMode(InteractivityModes.INTERACTIVE == interactivity);
    mavenExecutionRequest.setSystemProperties(System.getProperties());

    LegacySupport legacySupport = mock(LegacySupport.class);
    when(legacySupport.getSession()).thenReturn(new MavenSession(null, null, mavenExecutionRequest, null));
    setVariableValueInObject(objectUnderTest, "legacySupport", legacySupport);
}
 
Example #7
Source File: AbstractWildFlyMojoTest.java    From wildfly-maven-plugin with GNU Lesser General Public License v2.1 5 votes vote down vote up
public MavenProject readMavenProject(Path pom)
        throws Exception {
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setBaseDirectory(pom.getParent().toFile());
    ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
    configuration.setRepositorySession(new DefaultRepositorySystemSession());
    MavenProject project = rule.lookup(ProjectBuilder.class).build(pom.toFile(), configuration).getProject();
    Assert.assertNotNull(project);
    return project;
}
 
Example #8
Source File: RunMojo.java    From wisdom with Apache License 2.0 5 votes vote down vote up
private MavenExecutionRequest getMavenExecutionRequest() {
    MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(session.getRequest());
    request.setStartTime(session.getStartTime());
    request.setExecutionListener(null);
    if (! initialBuild  && session.getGoals().contains("clean")) {
        // Here the package phase is required to restore the runtime environment
        request.setGoals(ImmutableList.of("clean", "package", "wisdom:internal-run"));
    } else {
        // It is safer to re-execute the package phase to have the new classes...
        request.setGoals(ImmutableList.of("package", "wisdom:internal-run"));
    }
    return request;
}
 
Example #9
Source File: InstallDeployTest.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
private MavenProject readMavenProject(File basedir, Properties properties) throws Exception {
  File pom = new File(basedir, "pom.xml");
  MavenExecutionRequest request = new DefaultMavenExecutionRequest();
  request.setUserProperties(properties);
  request.setBaseDirectory(basedir);
  ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
  configuration.setRepositorySession(new DefaultRepositorySystemSession());
  MavenProject project = mojos.lookup(ProjectBuilder.class).build(pom, configuration).getProject();
  Assert.assertNotNull(project);
  return project;
}
 
Example #10
Source File: YeomanMojoTest.java    From yeoman-maven-plugin with Apache License 2.0 5 votes vote down vote up
private MavenProject getMavenProject(String pomPath) throws Exception {
    File pom = new File(pomPath);
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setPom(pom);
    ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
    return lookup( ProjectBuilder.class ).build( pom, configuration ).getProject();
}
 
Example #11
Source File: DistributionEnforcingManipulatorTest.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
private void setMavenSession()
    throws Exception
{
    final MavenExecutionRequest req =
        new DefaultMavenExecutionRequest().setUserProperties( userCliProperties )
                                          .setRemoteRepositories( Collections.emptyList() );

    final PlexusContainer container = new DefaultPlexusContainer();
    final MavenSession mavenSession = new MavenSession( container, null, req, new DefaultMavenExecutionResult() );

    session.setMavenSession( mavenSession );

}
 
Example #12
Source File: AbstractInstallDriversMojoTest.java    From webdriverextensions-maven-plugin with Apache License 2.0 5 votes vote down vote up
private MavenProject getMavenProject(String pomPath) throws Exception {
    File pom = new File(pomPath);
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setPom(pom);
    ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
    return lookup(ProjectBuilder.class).build(pom, configuration).getProject();
}
 
Example #13
Source File: MavenExecutionUtils.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static MavenExecutionRequest getMavenExecutionRequest(MavenSession session, String phase) {
    MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(session.getRequest());
    request.setStartTime(session.getStartTime());
    request.setExecutionListener(null);
    request.setGoals(ImmutableList.of(phase));
    return request;
}
 
Example #14
Source File: AbstractXmlMojoTestCase.java    From xml-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected AbstractXmlMojo newMojo( String pDir )
        throws Exception
    {
        File testPom = new File( new File( getBasedir(), pDir ), "pom.xml" );
        
        MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
        ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
        ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
        MavenProject project = projectBuilder.build(testPom, buildingRequest).getProject();
//        final Build build = new Build();
//        build.setDirectory( "target" );
//        project.setBuild(build);
        project.getBuild().setDirectory("target");
        AbstractXmlMojo vm = (AbstractXmlMojo) lookupConfiguredMojo(project, getGoal());
        setVariableValueToObject( vm, "basedir", new File( getBasedir(), pDir ) );
        final Log log = new SilentLog();
        DefaultResourceManager rm = new DefaultResourceManager();
        setVariableValueToObject( rm, "logger", log );
        setVariableValueToObject( vm, "locator", rm );
        final Map<String, ResourceLoader> resourceLoaders = new HashMap<String, ResourceLoader>();
        resourceLoaders.put( "file", new FileResourceLoader() );
        resourceLoaders.put( "jar", new JarResourceLoader() );
        resourceLoaders.put( "classloader", new ThreadContextClasspathResourceLoader() );
        URLResourceLoader url = new URLResourceLoader();
        setVariableValueToObject( url, "logger", log );
        resourceLoaders.put( "url", url );
        setVariableValueToObject( rm, "resourceLoaders", resourceLoaders );

//        MavenProjectStub project = new MavenProjectStub()
//        {
//            public Build getBuild()
//            {
//                return build;
//            }
//        };
//        setVariableValueToObject( vm, "project", project );
        return vm;
    }
 
Example #15
Source File: JenkinsMavenEventSpyDisablementTest.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Test
public void when_disabled_maven_event_spy_must_not_call_reporter() throws Exception {
    MavenEventReporter reporterMustNeverBeInvoked = new MavenEventReporter() {
        @Override
        public void print(Object message) {
            throw new IllegalStateException();
        }

        @Override
        public void print(Xpp3Dom element) {
            throw new IllegalStateException();
        }

        @Override
        public void close() {
            throw new IllegalStateException();
        }
    };
    JenkinsMavenEventSpy spy = new JenkinsMavenEventSpy(reporterMustNeverBeInvoked) {
        @Override
        protected boolean isEventSpyDisabled() {
            return true;
        }
    };

    spy.init(new EventSpy.Context() {
        @Override
        public Map<String, Object> getData() {
            return new HashMap<String, Object>();
        }
    });

    DefaultMavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setPom(new File("path/to/pom.xml"));
    request.setGoals(Arrays.asList("clean", "source:jar", "deploy"));

    spy.onEvent(request);
    spy.close();
}
 
Example #16
Source File: JenkinsMavenEventSpyTest.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Test
public void testMavenExecutionRequest() throws Exception {
    DefaultMavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setPom(new File("path/to/pom.xml"));
    request.setGoals(Arrays.asList("clean", "source:jar", "deploy"));

    spy.onEvent(request);

    String actual = writer.toString();
    System.out.println(actual);
    Assert.assertThat(actual, CoreMatchers.containsString("MavenExecutionRequest"));
}
 
Example #17
Source File: CodeGenMojoTest.java    From copybook4java with MIT License 5 votes vote down vote up
private Mojo lookupConfiguredMojo(String goal, File pom) throws Exception
{
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setBaseDirectory(pom.getParentFile());
    ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
    // Fix for bug: https://git-wip-us.apache.org/repos/asf?p=maven-plugin-testing.git;a=commit;h=3cd5f47c586499e438a3f9393304ac9d1f9a7f53
    configuration.setRepositorySession(new DefaultRepositorySystemSession());
    MavenProject project = lookup(ProjectBuilder.class).build(pom, configuration).getProject();
    return super.lookupConfiguredMojo(project, goal);
}
 
Example #18
Source File: BetterAbstractMojoTestCase.java    From repairnator with MIT License 5 votes vote down vote up
protected MavenSession newMavenSession() {
    try {
        MavenExecutionRequest request = new DefaultMavenExecutionRequest();
        MavenExecutionResult result = new DefaultMavenExecutionResult();

        // populate sensible defaults, including repository basedir and remote repos
        MavenExecutionRequestPopulator populator;
        populator = getContainer().lookup( MavenExecutionRequestPopulator.class );
        populator.populateDefaults( request );

        // this is needed to allow java profiles to get resolved; i.e. avoid during project builds:
        // [ERROR] Failed to determine Java version for profile java-1.5-detected @ org.apache.commons:commons-parent:22, /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, line 909, column 14
        request.setSystemProperties( System.getProperties() );
        
        // and this is needed so that the repo session in the maven session 
        // has a repo manager, and it points at the local repo
        // (cf MavenRepositorySystemUtils.newSession() which is what is otherwise done)
        DefaultMaven maven = (DefaultMaven) getContainer().lookup( Maven.class );
        DefaultRepositorySystemSession repoSession =
            (DefaultRepositorySystemSession) maven.newRepositorySession( request );
        repoSession.setLocalRepositoryManager(
            new SimpleLocalRepositoryManagerFactory().newInstance(repoSession, 
                new LocalRepository( request.getLocalRepository().getBasedir() ) ));

        @SuppressWarnings("deprecation")
        MavenSession session = new MavenSession( getContainer(), 
            repoSession,
            request, result );
        return session;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: GolangMojoCfgTest.java    From mvn-golang with Apache License 2.0 5 votes vote down vote up
private <T> T findMojo(final Class<T> klazz, final String pomName, final String goal) throws Exception {
  final File pomFile = new File(GolangMojoCfgTest.class.getResource(pomName).toURI());
  final MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
  final ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
  buildingRequest.setSystemProperties(System.getProperties());
  final ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
  final MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject();
  return klazz.cast(this.lookupConfiguredMojo(project, goal));
}
 
Example #20
Source File: MavenExecutionUtils.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static MavenExecutionRequest getMavenExecutionRequest(MavenSession session, String phase) {
    MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(session.getRequest());
    request.setStartTime(session.getStartTime());
    request.setExecutionListener(null);
    request.setGoals(ImmutableList.of(phase));
    return request;
}
 
Example #21
Source File: BetterMojoRule.java    From swaggerhub-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected MavenSession newMavenSession() {
    try {
        MavenExecutionRequest request = new DefaultMavenExecutionRequest();
        MavenExecutionResult result = new DefaultMavenExecutionResult();

        // populate sensible defaults, including repository basedir and remote repos
        MavenExecutionRequestPopulator populator;
        populator = getContainer().lookup(MavenExecutionRequestPopulator.class);
        populator.populateDefaults(request);

        // this is needed to allow java profiles to get resolved; i.e. avoid during project builds:
        // [ERROR] Failed to determine Java version for profile java-1.5-detected @ org.apache.commons:commons-parent:22, /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, line 909, column 14
        request.setSystemProperties(System.getProperties());

        // and this is needed so that the repo session in the maven session
        // has a repo manager, and it points at the local repo
        // (cf MavenRepositorySystemUtils.newSession() which is what is otherwise done)
        DefaultMaven maven = (DefaultMaven) getContainer().lookup(Maven.class);
        DefaultRepositorySystemSession repoSession =
                (DefaultRepositorySystemSession) maven.newRepositorySession(request);
        repoSession.setLocalRepositoryManager(
                new SimpleLocalRepositoryManagerFactory().newInstance(repoSession,
                        new LocalRepository(request.getLocalRepository().getBasedir())));

        @SuppressWarnings("deprecation")
        MavenSession session = new MavenSession(getContainer(),
                repoSession,
                request, result);
        return session;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: MavenEmbedder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * a prepopulate maven execution request object, most notably but systemProperties and userProperties 
 * fields are prepopulated with default values, typically one should only add to these values, not replace them.
 * @return 
 */
public MavenExecutionRequest createMavenExecutionRequest(){
    MavenExecutionRequest req = new DefaultMavenExecutionRequest();

    ArtifactRepository localRepository = getLocalRepository();
    req.setLocalRepository(localRepository);
    req.setLocalRepositoryPath(localRepository.getBasedir());

    //TODO: do we need to validate settings files?
    File settingsXml = embedderConfiguration.getSettingsXml();
    if (settingsXml !=null && settingsXml.exists()) {
        req.setGlobalSettingsFile(settingsXml);
    }
    if (SettingsXmlConfigurationProcessor.DEFAULT_USER_SETTINGS_FILE != null && SettingsXmlConfigurationProcessor.DEFAULT_USER_SETTINGS_FILE.exists()) {
      req.setUserSettingsFile(SettingsXmlConfigurationProcessor.DEFAULT_USER_SETTINGS_FILE);
    }
    
    req.setSystemProperties(getSystemProperties());
    req.setUserProperties(embedderConfiguration.getUserProperties());
    try {
        //#212214 populating from settings needs to come first
        //it adds mirrors and proxies to the request
        //later on populateDefaults() will use these to replace/configure the default "central" repository
        // and the repository id used is important down the road for resolution in EnhancedLocalRepositoryManager
        populator.populateFromSettings(req, getSettings());
        populator.populateDefaults(req);
    } catch (MavenExecutionRequestPopulationException x) {
        // XXX where to display this?
        Exceptions.printStackTrace(x);
    }
    req.setOffline(isOffline());
    req.setRepositoryCache(new NbRepositoryCache());

    return req;
}
 
Example #23
Source File: CreateProjectMojo.java    From quarkus with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #24
Source File: RepositoryUtility.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
static MavenProject createMavenProject(Path pomFile, RepositorySystemSession session)
    throws MavenRepositoryException {
  // MavenCli's way to instantiate PlexusContainer
  ClassWorld classWorld =
      new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());
  ContainerConfiguration containerConfiguration =
      new DefaultContainerConfiguration()
          .setClassWorld(classWorld)
          .setRealm(classWorld.getClassRealm("plexus.core"))
          .setClassPathScanning(PlexusConstants.SCANNING_INDEX)
          .setAutoWiring(true)
          .setJSR250Lifecycle(true)
          .setName("linkage-checker");
  try {
    PlexusContainer container = new DefaultPlexusContainer(containerConfiguration);

    MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest();
    ProjectBuildingRequest projectBuildingRequest =
        mavenExecutionRequest.getProjectBuildingRequest();

    projectBuildingRequest.setRepositorySession(session);

    // Profile activation needs properties such as JDK version
    Properties properties = new Properties(); // allowing duplicate entries
    properties.putAll(projectBuildingRequest.getSystemProperties());
    properties.putAll(OsProperties.detectOsProperties());
    properties.putAll(System.getProperties());
    projectBuildingRequest.setSystemProperties(properties);

    ProjectBuilder projectBuilder = container.lookup(ProjectBuilder.class);
    ProjectBuildingResult projectBuildingResult =
        projectBuilder.build(pomFile.toFile(), projectBuildingRequest);
    return projectBuildingResult.getProject();
  } catch (PlexusContainerException | ComponentLookupException | ProjectBuildingException ex) {
    throw new MavenRepositoryException(ex);
  }
}
 
Example #25
Source File: VersioningCalculatorTest.java    From pom-manipulation-ext with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "deprecation" )
private VersioningState setupSession( final Properties properties, final Map<ProjectRef, String[]> versionMap )
    throws Exception
{
    // Originally the default used to be 0, this was changed to be 5 but this affects this test suite so revert
    // just for these tests.
    if ( ! properties.containsKey( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP ) )
    {
        properties.setProperty( VersioningState.INCREMENT_SERIAL_SUFFIX_PADDING_SYSPROP, "0" );
    }

    final ArtifactRepository ar =
        new MavenArtifactRepository( "test", TestUtils.MVN_CENTRAL, new DefaultRepositoryLayout(),
                                     new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy() );

    final MavenExecutionRequest req =
        new DefaultMavenExecutionRequest().setUserProperties( properties )
                                          .setRemoteRepositories( Collections.singletonList( ar ) );

    final PlexusContainer container = new DefaultPlexusContainer();

    final MavenSession mavenSession = new MavenSession( container, null, req, new DefaultMavenExecutionResult() );

    session = new ManipulationSession();
    session.setMavenSession( mavenSession );

    final VersioningState state = new VersioningState( properties );
    session.setState( state );

    final Map<String, byte[]> dataMap = new HashMap<>();
    if ( versionMap != null && !versionMap.isEmpty() )
    {
        for ( final Map.Entry<ProjectRef, String[]> entry : versionMap.entrySet() )
        {
            final String path = toMetadataPath( entry.getKey() );
            final byte[] data = setupMetadataVersions( entry.getValue() );
            dataMap.put( path, data );
        }
    }

    final Location mdLoc = MavenLocationExpander.EXPANSION_TARGET;
    final Transport mdTrans = new StubTransport( dataMap );

    modder =
        new TestVersionCalculator( new ManipulationSession(), mdLoc, mdTrans, temp.newFolder( "galley-cache" ) );

    return state;
}
 
Example #26
Source File: JCasGenMojoTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void test(String projectName, String... types) throws Exception {

    File projectSourceDirectory = getTestFile("src/test/resources/" + projectName);
    File projectDirectory = getTestFile("target/project-" + projectName + "-test");

    // Stage project to target folder
    FileUtils.copyDirectoryStructure(projectSourceDirectory, projectDirectory);
    
    File pomFile = new File(projectDirectory, "/pom.xml");
    assertNotNull(pomFile);
    assertTrue(pomFile.exists());

    // create the MavenProject from the pom.xml file
    MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
    ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
    ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
    MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject();
    assertNotNull(project);

    // copy resources
    File source = new File(projectDirectory, "src/main/resources");
    if (source.exists()) {
      FileUtils.copyDirectoryStructure(source, new File(project.getBuild().getOutputDirectory()));
    }
    
    // load the Mojo
    JCasGenMojo generate = (JCasGenMojo) this.lookupConfiguredMojo(project, "generate");
    assertNotNull(generate);

    // set the MavenProject on the Mojo (AbstractMojoTestCase does not do this by default)
    setVariableValueToObject(generate, "project", project);

    // execute the Mojo
    generate.execute();

    // check that the Java files have been generated
    File jCasGenDirectory = new File(project.getBasedir(), "target/generated-sources/jcasgen");
    
    // Record all the files that were generated
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(jCasGenDirectory);
    ds.setIncludes(new String[] { "**/*.java" });
    ds.scan();
    List<File> files = new ArrayList<>();
    for (String scannedFile : ds.getIncludedFiles()) {
      files.add(new File(ds.getBasedir(), scannedFile));
    }
    
    for (String type : types) {
      File wrapperFile = new File(jCasGenDirectory + "/" + type.replace('.', '/') + ".java");
      // no _type files in v3
//      File typeFile = new File(jCasGenDirectory + "/" + type.replace('.', '/') + "_Type.java");
      
      Assert.assertTrue(files.contains(wrapperFile));
      // no _type files in v3
//      Assert.assertTrue(files.contains(typeFile));
      
      files.remove(wrapperFile);
//      files.remove(typeFile);
    }
    
    // check that no extra files were generated
    Assert.assertTrue(files.isEmpty());

    // check that the generated sources are on the compile path
    Assert.assertTrue(project.getCompileSourceRoots().contains(jCasGenDirectory.getAbsolutePath()));
  }