Java Code Examples for org.apache.maven.model.Model

The following examples show how to use org.apache.maven.model.Model. 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
private String boot(File root, ReleaserProperties properties) {
	String bootVersion = properties.getFixedVersions().get(SPRING_BOOT);
	if (StringUtils.hasText(bootVersion)) {
		return bootVersion;
	}
	String pomWithBootStarterParent = properties.getPom()
			.getPomWithBootStarterParent();
	File pom = new File(root, pomWithBootStarterParent);
	if (!pom.exists()) {
		return "";
	}
	Model model = PomReader.pom(root, pomWithBootStarterParent);
	if (model == null) {
		return "";
	}
	String bootArtifactId = model.getParent().getArtifactId();
	log.debug("Boot artifact id is equal to [{}]", bootArtifactId);
	if (!BOOT_STARTER_PARENT_ARTIFACT_ID.equals(bootArtifactId)) {
		if (log.isDebugEnabled()) {
			throw new IllegalStateException("The pom doesn't have a ["
					+ BOOT_STARTER_PARENT_ARTIFACT_ID + "] artifact id");
		}
		return "";
	}
	return model.getParent().getVersion();
}
 
Example 2
Source Project: wisdom   Source File: MavenUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static Map getProperties(Model projectModel, String prefix) {
    Map<String, String> properties = new LinkedHashMap<>();
    Method[] methods = Model.class.getDeclaredMethods();
    for (Method method : methods) {
        String name = method.getName();
        if (name.startsWith("get")) {
            try {
                Object v = method.invoke(projectModel);
                if (v != null) {
                    name = prefix + Character.toLowerCase(name.charAt(3)) + name.substring(4);
                    if (v.getClass().isArray()) {
                        properties.put(name, Arrays.asList((Object[]) v).toString());
                    } else {
                        properties.put(name, v.toString());
                    }
                }
            } catch (Exception e) {  //NOSONAR
                // too bad
            }
        }
    }
    return properties;
}
 
Example 3
Source Project: LicenseScout   Source File: ArtifactServerUtil.java    License: Apache License 2.0 6 votes vote down vote up
private boolean evaluatePomLicenses(final Archive archive, final String filePath,
                                    final LicenseStoreData licenseStoreData, final Model model) {
    boolean licenseFound = false;
    final List<org.apache.maven.model.License> licenses = model.getLicenses();
    for (final org.apache.maven.model.License license : licenses) {
        final String licenseUrl = license.getUrl();
        final String licenseName = license.getName();
        log.debug("License name: " + licenseName);
        log.debug("License URL: " + licenseUrl);
        final boolean licenseFoundForUrl = LicenseUtil.handleLicenseUrl(licenseUrl, archive, filePath,
                licenseStoreData, log);
        licenseFound |= licenseFoundForUrl;
        boolean licenseFoundForName = false;
        if (!licenseFoundForUrl) {
            licenseFoundForName = LicenseUtil.handleLicenseName(licenseName, archive, filePath, licenseStoreData,
                    log);
            licenseFound |= licenseFoundForName;
        }
        if (!licenseFoundForUrl && !licenseFoundForName) {
            log.warn("Neither license name nor license URL mapping found for name/URL: " + licenseName + " / "
                    + licenseUrl);
        }
    }
    return licenseFound;
}
 
Example 4
Source Project: butterfly   Source File: PomChangeParentTest.java    License: MIT License 6 votes vote down vote up
@Test
public void changeParentTest() throws IOException, XmlPullParserException {
    Model pomModelBeforeChange = getOriginalPomModel("pom.xml");

    assertEquals(pomModelBeforeChange.getParent().getGroupId(), "com.test");
    assertEquals(pomModelBeforeChange.getParent().getArtifactId(), "foo-parent");
    assertEquals(pomModelBeforeChange.getParent().getVersion(), "1.0");

    PomChangeParent pomChangeParent = new PomChangeParent().setGroupId("com.newgroupid").setArtifactId("newartifactid").setVersion("2.0").relative("pom.xml");

    assertEquals(pomChangeParent.getGroupId(), "com.newgroupid");
    assertEquals(pomChangeParent.getArtifactId(), "newartifactid");
    assertEquals(pomChangeParent.getVersion(), "2.0");


    TOExecutionResult executionResult = pomChangeParent.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.SUCCESS);
    assertEquals(pomChangeParent.getDescription(), "Change parent artifact in POM file pom.xml");
    assertNull(executionResult.getException());

    Model pomModelAfterChange = getTransformedPomModel("pom.xml");
    assertEquals(pomModelAfterChange.getParent().getGroupId(), "com.newgroupid");
    assertEquals(pomModelAfterChange.getParent().getArtifactId(), "newartifactid");
    assertEquals(pomModelAfterChange.getParent().getVersion(), "2.0");
}
 
Example 5
Source Project: butterfly   Source File: PomAddParentTest.java    License: MIT License 6 votes vote down vote up
@Test
public void addParentTest() throws IOException, XmlPullParserException {
    Model pomModelBeforeChange = getOriginalPomModel("/src/main/resources/no_parent_pom.xml");
    assertNull(pomModelBeforeChange.getParent());

    PomAddParent pomAddParent = new PomAddParent().setGroupId("com.newgroupid").setArtifactId("newartifactid").setVersion("2.0").relative("/src/main/resources/no_parent_pom.xml");

    assertEquals(pomAddParent.getGroupId(), "com.newgroupid");
    assertEquals(pomAddParent.getArtifactId(), "newartifactid");
    assertEquals(pomAddParent.getVersion(), "2.0");

    TOExecutionResult executionResult = pomAddParent.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.SUCCESS);
    assertEquals(pomAddParent.getDescription(), "Add parent artifact com.newgroupid:newartifactid in POM file /src/main/resources/no_parent_pom.xml");
    assertEquals(executionResult.getDetails(), "Parent for POM file /src/main/resources/no_parent_pom.xml has been set to com.newgroupid:newartifactid:pom:2.0");
    assertNull(executionResult.getException());

    Model pomModelAfterChange = getTransformedPomModel("/src/main/resources/no_parent_pom.xml");
    assertEquals(pomModelAfterChange.getParent().getGroupId(), "com.newgroupid");
    assertEquals(pomModelAfterChange.getParent().getArtifactId(), "newartifactid");
    assertEquals(pomModelAfterChange.getParent().getVersion(), "2.0");

    // Checking indentation
    File baselineFile = new File(this.getClass().getResource("/test-app/src/main/resources/added_parent_pom.xml").getFile());
    assertTrue(Files.equal(baselineFile, new File(transformedAppFolder, "/src/main/resources/no_parent_pom.xml")), "File is not formatted properly.");
}
 
Example 6
Source Project: quarkus   Source File: LocalProject.java    License: Apache License 2.0 6 votes vote down vote up
public static LocalProject loadWorkspace(Path path, boolean required) throws BootstrapMavenException {
    path = path.normalize().toAbsolutePath();
    Path currentProjectPom = null;
    Model rootModel = null;
    if (!Files.isDirectory(path)) {
        // see if that's an actual pom
        try {
            rootModel = loadRootModel(path);
            if (rootModel != null) {
                currentProjectPom = path;
            }
        } catch (BootstrapMavenException e) {
            // ignore, it's not a POM file, we'll be looking for the POM later
        }
    }
    if (currentProjectPom == null) {
        currentProjectPom = locateCurrentProjectPom(path, required);
        if (currentProjectPom == null) {
            return null;
        }
        rootModel = loadRootModel(currentProjectPom);
    }
    return loadWorkspace(currentProjectPom, rootModel);
}
 
Example 7
Source Project: butterfly   Source File: ModelTree.java    License: MIT License 6 votes vote down vote up
/**
     * This is a tree of Maven artifacts, which are represented by {@link Model} objects.
     * The idea here is, given a list of Maven pom.xml {@link File} objects, create a tree
     * based on dependency among them, but specifying explicitly which Maven artifact should
     * be at the root of the tree. That means, if any artifact in the list is not a child,
     * directly or indirectly, of the root artifact, then it will end up no being in the tree.
     * <br>
     * As a result of building this tree, it is possible to know, out of the initial pom.xml files list,
     * which ones actually inherit, directly or not, from the root artifact. The result is retrieved
     * by calling {@link #getPomFilesInTree()}
     *
     * @param rootGroupId the group id of the artifact that should be at the root of the tree
     * @param rootArtifactId the artifact id of the artifact that should be at the root of the tree
     * @param rootVersion the version of the artifact that should be at the root of the tree
     * @param pomFiles a list of pom.xml files used to make the tree
     */
    public ModelTree(String rootGroupId, String rootArtifactId, String rootVersion, List<File> pomFiles) {
        Model rootModel = new Model();
        rootModel.setGroupId(rootGroupId);
        rootModel.setArtifactId(rootArtifactId);
        rootModel.setVersion(rootVersion);

        List<Model> models = new ArrayList<>();
        models.add(rootModel);

        for (File pomFile : pomFiles) {
            models.add(createModel(pomFile));
        }

// TODO we can comment this out in the future if we need this feature
//        modelsNotInTree = add(models);
        add(models);
    }
 
Example 8
Source Project: helidon-build-tools   Source File: CommandRequirements.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Require that a valid Maven project configuration exists.
 *
 * @param commonOptions The options.
 */
static void requireValidMavenProjectConfig(CommonOptions commonOptions) {
    try {
        Path projectDir = commonOptions.project();
        Path pomFile = PomUtils.toPomFile(projectDir);
        Path projectConfigFile = ProjectConfig.toDotHelidon(projectDir);
        if (!Files.exists(projectConfigFile)) {
            // Find the helidon version if we can and create the config file
            Model model = PomUtils.readPomModel(pomFile);
            Parent parent = model.getParent();
            String helidonVersion = null;
            if (parent != null && parent.getGroupId().startsWith("io.helidon.")) {
                helidonVersion = parent.getVersion();
            }
            ensureProjectConfig(projectDir, helidonVersion);
        }
    } catch (IllegalArgumentException e) {
        String message = e.getMessage();
        if (message.contains("does not exist")) {
            message = NOT_A_PROJECT_DIR;
        }
        Requirements.failed(message);
    }
}
 
Example 9
private List<Artifact> getDeployDependencies(Artifact artifact, List<Exclusion> exclusions, boolean testScope, Map<String, String> properties, DeployType type) {
    ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest();
    descriptorRequest.setRepositories(AetherUtil.newRepositories(deployConfig));
    descriptorRequest.setArtifact(artifact);
    Model model = AetherUtil.readPom(artifact);
    if (model == null) {
        throw new IllegalStateException("Unable to read POM for " + artifact.getFile());
    }
    try {
        ArtifactDescriptorResult descriptorResult = system.readArtifactDescriptor(session, descriptorRequest);

        return descriptorResult.getDependencies().stream()
                .filter(d -> type == DeployType.DEFAULT || (type == DeployType.APPLICATION && !d.getArtifact().getExtension().equals("zip")) || (type == DeployType.ARTIFACT && !d.getArtifact().getExtension().equals("jar")))
                .filter(d -> "compile".equalsIgnoreCase(d.getScope()) || ("test".equalsIgnoreCase(d.getScope()) && testScope))
                .filter(d -> !exclusions.contains(new Exclusion(d.getArtifact().getGroupId(), d.getArtifact().getArtifactId(), null, null)))
                .map(Dependency::getArtifact)
                .map(d -> this.checkWithModel(model, d, properties))
                .collect(Collectors.toList());

    } catch (ArtifactDescriptorException e) {
        LOG.error("Unable to resolve dependencies for deploy artifact '{}', unable to auto-discover ", artifact, e);
    }
    return Collections.emptyList();
}
 
Example 10
Source Project: butterfly   Source File: PomChangeParentVersionTest.java    License: MIT License 6 votes vote down vote up
@Test
public void warnTest() throws IOException, XmlPullParserException {
    Model pomModelBeforeChange = getOriginalPomModel("/src/main/resources/no_parent_pom.xml");
    assertNull(pomModelBeforeChange.getParent());

    PomChangeParentVersion pomChangeParentVersion = new PomChangeParentVersion().relative("/src/main/resources/no_parent_pom.xml").warnIfNotPresent();
    pomChangeParentVersion.setVersion("2.0");

    assertEquals(pomChangeParentVersion.getVersion(), "2.0");

    TOExecutionResult executionResult = pomChangeParentVersion.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.WARNING);
    assertEquals(pomChangeParentVersion.getDescription(), "Change artifact's parent version in POM file /src/main/resources/no_parent_pom.xml");
    assertNull(executionResult.getException());
    assertEquals(executionResult.getWarnings().size(), 1);
    assertEquals(executionResult.getWarnings().get(0).getClass(), TransformationOperationException.class);
    assertEquals(executionResult.getWarnings().get(0).getMessage(), "Pom file /src/main/resources/no_parent_pom.xml does not have a parent");

    Model pomModelAfterChange = getTransformedPomModel("/src/main/resources/no_parent_pom.xml");
    assertNull(pomModelAfterChange.getParent());

    assertNotChangedFile("/src/main/resources/no_parent_pom.xml");
}
 
Example 11
Source Project: maven-git-versioning-extension   Source File: GAVTest.java    License: MIT License 6 votes vote down vote up
@Test
void of_model() {
    // Given
    Model model = new Model();
    model.setGroupId("group");
    model.setArtifactId("artifact");
    model.setVersion("version");

    // When
    GAV gav = GAV.of(model);

    // Then
    assertThat(gav).isNotNull();
    assertThat(gav.getGroupId()).isEqualTo("group");
    assertThat(gav.getArtifactId()).isEqualTo("artifact");
    assertThat(gav.getVersion()).isEqualTo("version");
}
 
Example 12
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 13
Source Project: butterfly   Source File: PomAddParentTest.java    License: MIT License 6 votes vote down vote up
@Test
public void failTest() throws IOException, XmlPullParserException {
    Model pomModelBeforeChange = getOriginalPomModel("pom.xml");
    assertEquals(pomModelBeforeChange.getParent().getGroupId(), "com.test");
    assertEquals(pomModelBeforeChange.getParent().getArtifactId(), "foo-parent");
    assertEquals(pomModelBeforeChange.getParent().getVersion(), "1.0");

    PomAddParent pomAddParent = new PomAddParent().setGroupId("com.newgroupid").setArtifactId("newartifactid").setVersion("2.0").relative("pom.xml").failIfPresent();

    assertEquals(pomAddParent.getGroupId(), "com.newgroupid");
    assertEquals(pomAddParent.getArtifactId(), "newartifactid");
    assertEquals(pomAddParent.getVersion(), "2.0");

    TOExecutionResult executionResult = pomAddParent.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.ERROR);
    assertEquals(pomAddParent.getDescription(), "Add parent artifact com.newgroupid:newartifactid in POM file pom.xml");
    assertEquals(executionResult.getException().getClass(), TransformationOperationException.class);
    assertEquals(executionResult.getException().getMessage(), "Pom file /pom.xml already has a parent");

    Model pomModelAfterChange = getTransformedPomModel("pom.xml");
    assertEquals(pomModelAfterChange.getParent().getGroupId(), "com.test");
    assertEquals(pomModelAfterChange.getParent().getArtifactId(), "foo-parent");
    assertEquals(pomModelAfterChange.getParent().getVersion(), "1.0");

    assertNotChangedFile("pom.xml");
}
 
Example 14
private void fixParentProject(IProject p, IProject parentProject)
		throws CoreException {
	IFile existingPom = p.getFile("pom.xml");
	Model model = MavenPlugin.getMavenModelManager().readMavenModel(existingPom);
	Model parent = MavenPlugin.getMavenModelManager().readMavenModel(parentProject.getFile("pom.xml"));
	//Parent oldParent = model.getParent();
	Parent newParent = new Parent();
	newParent.setGroupId(parent.getGroupId());
	newParent.setArtifactId(parent.getArtifactId());
	newParent.setRelativePath(calculateRelativePath(p, parentProject));
	newParent.setVersion(parent.getVersion());
	model.setParent(newParent);
	// outright deletion doesn't work on windows as the process has a ref to the file itself
	// so creating a temp '_newpom_.xml'
	final IFile newPom = p.getFile("_newpom_.xml");
	MavenPlugin.getMavenModelManager().createMavenModel(newPom, model);
	// then copying that content over to the pom.xml
	existingPom.setContents(newPom.getContents(), true,  true, new NullProgressMonitor());
	// and deleting the temp pom
	newPom.delete(true,  false, new NullProgressMonitor());
	
}
 
Example 15
private void applyTest( final EnforcingMode mode, final Model model, final Model expectChanged )
    throws Exception
{
    setModeProperty( mode );

    setMavenSession();

    manipulator.init( session );

    final Project project = new Project( model );
    final List<Project> projects = new ArrayList<>();
    projects.add( project );

    final Set<Project> changed = manipulator.applyChanges( projects );

    if ( expectChanged != null )
    {
        assertThat( changed.isEmpty(), equalTo( false ) );
        assertThat( changed.contains( new Project( expectChanged ) ), equalTo( true ) );
    }
    else
    {
        assertThat( changed.isEmpty(), equalTo( true ) );
    }
}
 
Example 16
Source Project: quarkus   Source File: LocalProject.java    License: Apache License 2.0 6 votes vote down vote up
private static Model loadRootModel(Path pomXml) throws BootstrapMavenException {
    Model model = null;
    while (pomXml != null && Files.exists(pomXml)) {
        model = readModel(pomXml);
        final Parent parent = model.getParent();
        if (parent != null
                && parent.getRelativePath() != null
                && !parent.getRelativePath().isEmpty()) {
            pomXml = pomXml.getParent().resolve(parent.getRelativePath()).normalize();
            if (Files.isDirectory(pomXml)) {
                pomXml = pomXml.resolve(POM_XML);
            }
        } else {
            final Path parentDir = pomXml.getParent().getParent();
            pomXml = parentDir == null ? null : parentDir.resolve(POM_XML);
        }
    }
    return model;
}
 
Example 17
Source Project: butterfly   Source File: PomAddPluginTest.java    License: MIT License 6 votes vote down vote up
@Test
public void defaultIfPresentTest() throws IOException, XmlPullParserException {
    Model pomModelBeforeChange = getOriginalPomModel("pom.xml");
    assertEquals(pomModelBeforeChange.getBuild().getPlugins().size(), 3);
    assertEquals(pomModelBeforeChange.getBuild().getPlugins().get(0).getGroupId(), "org.codehaus.mojo");
    assertEquals(pomModelBeforeChange.getBuild().getPlugins().get(0).getArtifactId(), "cobertura-maven-plugin");

    // Trying to add the same plugin
    PomAddPlugin pomAddPlugin = new PomAddPlugin().setArtifact("org.codehaus.mojo:cobertura-maven-plugin").relative("pom.xml");
    TOExecutionResult executionResult = pomAddPlugin.execution(transformedAppFolder, transformationContext);
    assertEquals(executionResult.getType(), TOExecutionResult.Type.ERROR);
    assertNull(executionResult.getDetails());
    assertEquals(executionResult.getException().getMessage(), "Plugin org.codehaus.mojo:cobertura-maven-plugin is already present in pom.xml");

    Model pomModelAfterChange = getTransformedPomModel("pom.xml");
    assertEquals(pomModelAfterChange.getBuild().getPlugins().size(), 3);
    assertEquals(pomModelAfterChange.getBuild().getPlugins().size(), 3);
    assertEquals(pomModelAfterChange.getBuild().getPlugins().get(0).getGroupId(), "org.codehaus.mojo");
    assertEquals(pomModelAfterChange.getBuild().getPlugins().get(0).getArtifactId(), "cobertura-maven-plugin");

    assertNotChangedFile("pom.xml");
}
 
Example 18
Source Project: scava   Source File: BuildManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void rewritePOM(File pomFile) throws BuildException {
	try (Reader reader = new FileReader(pomFile)) {
		MavenXpp3Reader pomReader = new MavenXpp3Reader();
		
		Model model = pomReader.read(reader);
		reader.close();
		
		model.addRepository(createRepo("maven_central", "http://repo.maven.apache.org/maven2/", "default"));
		
		for (String id: eclipseRepos.keySet()) {
			model.addRepository(createRepo(id, eclipseRepos.get(id), "p2"));
		}
		
		Build modelBuild = model.getBuild();
		if (modelBuild == null) {
			model.setBuild(new Build());
		}
		
		model.getBuild().addPlugin(createPlugin("org.eclipse.tycho", "tycho-maven-plugin", "0.21.0", true));
		model.getBuild().addPlugin(createPlugin("org.eclipse.tycho", "target-platform-configuration", "0.21.0", false));
		model.getBuild().addPlugin(createPlugin("org.apache.maven.plugins", "maven-dependency-plugin", "2.8", false));
		
		MavenXpp3Writer pomWriter = new MavenXpp3Writer();
		pomWriter.write(new FileWriter(pomFile), model);
	} 
	catch (Exception e) {
		throw new BuildException("POM rewriting (to add plugin dependencies, cause) failed unexpectedly", e);
	}
}
 
Example 19
Source Project: jkube   Source File: MavenUtilTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private MavenProject loadMavenProjectFromPom() throws IOException, XmlPullParserException {
    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
    File pomfile = new File(getClass().getResource("/util/test-pom.xml").getFile());
    final FileReader reader = new FileReader(pomfile);
    final Model model  = mavenreader.read(reader);
    model.setPomFile(pomfile);
    model.getBuild().setOutputDirectory(temporaryFolder.newFolder("outputDirectory").getAbsolutePath());
    model.getBuild().setDirectory(temporaryFolder.newFolder("build").getAbsolutePath());
    return new MavenProject(model);
}
 
Example 20
Source Project: gitflow-incremental-builder   Source File: MavenSessionMock.java    License: MIT License 5 votes vote down vote up
private static MavenProject createProject(Path path) {
    MavenProject project = new MavenProject();
    Model model = new Model();
    model.setProperties(new Properties());
    project.setModel(model);
    project.setArtifactId(path.getFileName().toString());
    project.setGroupId(path.getFileName().toString());
    project.setVersion("1");
    project.setFile(path.resolve("pom.xml").toFile());
    return project;
}
 
Example 21
Source Project: versions-maven-plugin   Source File: PomHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Builds a map of raw models keyed by module path.
 *
 * @param project The project to build from.
 * @param logger The logger for logging.
 * @return A map of raw models keyed by path relative to the project's basedir.
 * @throws IOException if things go wrong.
 */
public static Map<String, Model> getReactorModels( MavenProject project, Log logger )
    throws IOException
{
    Map<String, Model> result = new LinkedHashMap<>();
    final Model model = getRawModel( project );
    final String path = "";
    result.put( path, model );
    result.putAll( getReactorModels( path, model, project, logger ) );
    return result;
}
 
Example 22
Source Project: butterfly   Source File: PomChangePackaging.java    License: MIT License 5 votes vote down vote up
@Override
protected TOExecutionResult pomExecution(String relativePomFile, Model model) {
    model.setPackaging(packagingType);
    String details = String.format("Packaging for POM file %s has been changed to %s", relativePomFile, packagingType);

    return TOExecutionResult.success(this, details);
}
 
Example 23
Source Project: netbeans   Source File: POMInheritancePanel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    //#164852 somehow a folder dataobject slipped in, test mimetype to avoid that.
    // the root cause of the problem is unknown though
    if (current != null && Constants.POM_MIME_TYPE.equals(current.getPrimaryFile().getMIMEType())) { //NOI18N
        File file = FileUtil.toFile(current.getPrimaryFile());
        // can be null for stuff in jars?
        if (file != null) {
            try {
                List<Model> lin = EmbedderFactory.getProjectEmbedder().createModelLineage(file);
                final Children ch = Children.create(new PomChildren(lin), false);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                       treeView.setRootVisible(false);
                       explorerManager.setRootContext(new AbstractNode(ch));
                    } 
                });
            } catch (final ModelBuildingException ex) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                       treeView.setRootVisible(true);
                       explorerManager.setRootContext(POMModelPanel.createErrorNode(ex));
                    }
                });
            }
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                   treeView.setRootVisible(false);
                   explorerManager.setRootContext(createEmptyNode());
                } 
            });
        }
    }
}
 
Example 24
Source Project: sarl   Source File: NewMavenSarlProjectWizard.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean performFinish() {
	if (!super.performFinish()) {
		return false;
	}
	final Job job = new WorkspaceJob("Force the SARL nature") { //$NON-NLS-1$
		@SuppressWarnings({ "deprecation", "synthetic-access" })
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			final Model model = NewMavenSarlProjectWizard.this.lastModel;
			if (model != null) {
				final Plugin plugin = Iterables.find(model.getBuild().getPlugins(), it -> PLUGIN_ARTIFACT_ID.equals(it.getArtifactId()));
				plugin.setExtensions(true);
				final IWorkspace workspace = ResourcesPlugin.getWorkspace();
				final IWorkspaceRoot root = workspace.getRoot();
				final IProject project = NewMavenSarlProjectWizard.this.importConfiguration.getProject(root, model);
				// Fixing the "extensions" within the pom file
				final IFile pomFile = project.getFile(IMavenConstants.POM_FILE_NAME);
				pomFile.delete(true, new NullProgressMonitor());
				MavenPlugin.getMavenModelManager().createMavenModel(pomFile, model);
				// Update the project
				final SubMonitor submon = SubMonitor.convert(monitor);
				MavenPlugin.getProjectConfigurationManager().updateProjectConfiguration(project, submon.newChild(1));
				project.refreshLocal(IResource.DEPTH_ONE, submon.newChild(1));
			}
			return Status.OK_STATUS;
		}
	};
	job.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
	job.schedule();
	return true;
}
 
Example 25
Source Project: quarkus   Source File: ModelUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String getGroupId(Model model) {
    String groupId = model.getGroupId();
    if (groupId != null) {
        return groupId;
    }
    final Parent parent = model.getParent();
    if (parent != null) {
        groupId = parent.getGroupId();
        if (groupId != null) {
            return groupId;
        }
    }
    throw new IllegalStateException("Failed to determine groupId for project model");
}
 
Example 26
Source Project: buck   Source File: PomIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUseTemplateIfProvided() throws Exception {
  MavenPublishable withoutTemplate =
      createMavenPublishable("//example:no-template", "example.com:project:1.0.0", null);
  Model noTemplate = parse(Pom.generatePomFile(pathResolver, withoutTemplate));

  MavenPublishable withTemplate =
      createMavenPublishable(
          "//example:template",
          "example.com:project:1.0.0",
          FakeSourcePath.of(
              TestDataHelper.getTestDataDirectory(getClass())
                  .resolve("poms/template-pom.xml")
                  .toString()));
  Model templated = parse(Pom.generatePomFile(pathResolver, withTemplate));

  // Template sets developers and an example dep. Check that these aren't in the non-templated
  // version
  assertTrue(noTemplate.getDevelopers().isEmpty());
  assertTrue(noTemplate.getDependencies().isEmpty());

  // Now check the same fields in the templated version.
  Developer seenDev = Iterables.getOnlyElement(templated.getDevelopers());
  assertEquals("susan", seenDev.getId());
  assertEquals("Susan The Developer", seenDev.getName());
  assertEquals(ImmutableList.of("Owner"), seenDev.getRoles());

  Dependency seenDep = Iterables.getOnlyElement(templated.getDependencies());
  assertEquals("com.google.guava", seenDep.getGroupId());
  assertEquals("guava", seenDep.getArtifactId());
  assertEquals("19.0", seenDep.getVersion());
}
 
Example 27
Source Project: developer-studio   Source File: MavenUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static MavenProject createMavenProject(String groupId, String artifactId, String version, String packagingType) {
	Model model = new Model();
	model.setGroupId(groupId);
	model.setArtifactId(artifactId);
	model.setVersion(version);
	model.setModelVersion("4.0.0");
	model.setName(artifactId);
	model.setDescription(artifactId);
	if (packagingType!=null){
		model.setPackaging(packagingType);
	}
	return new MavenProject(model);
}
 
Example 28
Source Project: helidon-build-tools   Source File: PomUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean ensurePluginVersion(Model model, String helidonPluginVersion) {
    Properties properties = model.getProperties();
    String existing = properties.getProperty(HELIDON_PLUGIN_VERSION_PROPERTY);
    if (existing == null || !existing.equals(helidonPluginVersion)) {
        model.addProperty(HELIDON_PLUGIN_VERSION_PROPERTY, helidonPluginVersion);
        return true;
    } else {
        return false;
    }
}
 
Example 29
Source Project: quarkus   Source File: SetupVerifier.java    License: Apache License 2.0 5 votes vote down vote up
public static void verifySetupWithVersion(File pomFile) throws Exception {
    MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
    Model model = xpp3Reader.read(new FileInputStream(pomFile));

    MavenProject project = new MavenProject(model);
    Properties projectProps = project.getProperties();
    assertNotNull(projectProps);
    assertFalse(projectProps.isEmpty());
    final String quarkusVersion = getPlatformDescriptor().getQuarkusVersion();
    assertEquals(quarkusVersion, projectProps.getProperty(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLUGIN_VERSION_NAME));
}
 
Example 30
private Model getModelFromProject(IProject project) {
  IMavenProjectFacade facade = mavenProjectRegistry.getProject(project);
  if (facade != null) {
    IFile pom = facade.getPom();
    try {
      return maven.readModel(pom.getContents());
    } catch (CoreException e) {
      return null;
    }
  }
  return null;
}