Java Code Examples for org.apache.maven.model.Model#getParent()

The following examples show how to use org.apache.maven.model.Model#getParent() . 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: CommandRequirements.java    From helidon-build-tools with 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 2
Source File: QuarkusJsonPlatformDescriptorResolver.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static String getGroupId(Model model) {
    if (model == null) {
        return null;
    }
    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 the groupId for the POM of " + model.getArtifactId());
}
 
Example 3
Source File: SetupProjectHelper.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
@Deprecated
public static boolean isFunktionParentPom(Project project) {
    MavenFacet mavenFacet = project.getFacet(MavenFacet.class);
    if (mavenFacet != null) {
        Model model = mavenFacet.getModel();
        if (model != null) {
            Parent parent = model.getParent();
            if (parent != null) {
                String groupId = parent.getGroupId();
                if (groupId != null && groupId.startsWith("io.fabric8.funktion")) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 4
Source File: PomHelper.java    From versions-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a count of how many parents a model has in the reactor.
 *
 * @param reactor The map of models keyed by path.
 * @param model The model.
 * @return The number of parents of this model in the reactor.
 */
public static int getReactorParentCount( Map<String, Model> reactor, Model model )
{
    if ( model.getParent() == null )
    {
        return 0;
    }
    else
    {
        Model parentModel = getModel( reactor, model.getParent().getGroupId(), model.getParent().getArtifactId() );
        if ( parentModel != null )
        {
            return getReactorParentCount( reactor, parentModel ) + 1;
        }
        return 0;
    }
}
 
Example 5
Source File: ScmPomVersionsMergeClient.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void merge(InputStream local, InputStream remote, InputStream base, OutputStream result) throws ScmException {
  Optional<Model> localModel = loadModel(local);
  if (!localModel.isPresent()) {
    // TODO implement merge of other files!
    throw new ScmException(ScmOperation.MERGE, "Unable to merge non-POM changes.");
  }

  byte[] remoteData = null;
  try {
    remoteData = ByteStreams.toByteArray(remote);
  } catch (IOException e) {
    throw new ScmException(ScmOperation.MERGE, "Unable to read remote content!", e);
  } finally {
    Closeables.closeQuietly(remote);
  }

  Optional<Model> remoteModel = loadModel(new ByteArrayInputStream(remoteData));
  Optional<Model> baseModel = loadModel(base);

  Model resultModel = loadModel(new ByteArrayInputStream(remoteData)).get();
  mergeVersions(localModel.get(), remoteModel.get(), baseModel.get(), resultModel);
  mergeParentVersions(localModel.get(), remoteModel.get(), baseModel.get(), resultModel);

  try {
    Document document = PomUtil.parsePOM(new ByteArrayInputStream(remoteData));
    PomUtil.setProjectVersion(resultModel, document, resultModel.getVersion());
    if (resultModel.getParent() != null) {
      PomUtil.setParentVersion(resultModel, document, resultModel.getParent().getVersion());
    }
    PomUtil.writePOM(document, result, false);
  } catch (Throwable t) {
    throw new ScmException(ScmOperation.MERGE, "Could not serialize merged POM!", t);
  }
}
 
Example 6
Source File: MavenUploadHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private String getGroupId(Model model) {
  String groupId = model.getGroupId();
  if (groupId == null && model.getParent() != null) {
    groupId = model.getParent().getGroupId();
  }
  return groupId;
}
 
Example 7
Source File: PomUpdater.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
private String groupId(Model model) {
	if (hasText(model.getGroupId())) {
		return model.getGroupId();
	}
	if (model.getParent() != null) {
		return model.getParent().getGroupId();
	}
	return "";
}
 
Example 8
Source File: PomUpdater.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
private List<VersionChange> updateParentIfPossible(ModelWrapper wrapper,
		VersionsFromBom versionsFromBom, Model model,
		List<VersionChange> sourceChanges) {
	String rootProjectName = wrapper.projectName();
	List<VersionChange> changes = new ArrayList<>(sourceChanges);
	if (model.getParent() == null || isEmpty(model.getParent().getVersion())) {
		log.debug("Can't set the value for parent... Will return {}", sourceChanges);
		return changes;
	}
	String parentGroupId = model.getParent().getGroupId();
	String parentArtifactId = model.getParent().getArtifactId();
	log.debug("Searching for a version of parent [{}:{}]", parentGroupId,
			parentArtifactId);
	String oldVersion = model.getParent().getVersion();
	String version = versionsFromBom.versionForProject(parentArtifactId);
	log.debug("Found version is [{}]", version);
	if (isEmpty(version)) {
		if (hasText(model.getParent().getRelativePath())) {
			version = versionsFromBom.versionForProject(rootProjectName);
		}
		else {
			log.warn("There is no info on the [{}:{}] version", parentGroupId,
					parentArtifactId);
			return changes;
		}
	}
	if (oldVersion.equals(version)) {
		log.debug(
				"Won't update the version of parent [{}:{}] since you're already using the proper one",
				parentGroupId, parentArtifactId);
		return changes;
	}
	log.info("Setting version of parent [{}] to [{}] for module [{}]",
			parentArtifactId, version, model.getArtifactId());
	if (hasText(version)) {
		changes.add(new VersionChange(parentGroupId, parentArtifactId, oldVersion,
				version));
	}
	return changes;
}
 
Example 9
Source File: Deploys.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private void initPomVersion() throws Throwable {
  // already set manually
  if (pomVersion != null) {
    return;
  }

  // already package to jar
  pomVersion = Deploys.class.getPackage().getImplementationVersion();
  if (pomVersion != null) {
    return;
  }

  // run in ide
  MavenXpp3Reader reader = new MavenXpp3Reader();
  Model model = reader.read(new FileReader("pom.xml"));
  pomVersion = model.getVersion();
  if (pomVersion != null) {
    return;
  }

  if (model.getParent() == null) {
    throw new IllegalStateException("can not find pom ServiceComb version");
  }

  pomVersion = model.getParent().getVersion();
  if (pomVersion != null) {
    return;
  }

  throw new IllegalStateException("can not find pom ServiceComb version");
}
 
Example 10
Source File: PomChangeParent.java    From butterfly with MIT License 5 votes vote down vote up
@Override
protected TOExecutionResult pomExecution(String relativePomFile, Model model) {
    String details;
    Parent parent = model.getParent();

    if (parent == null) {
        String message = String.format("Pom file %s does not have a parent", getRelativePath());

        switch (ifNotPresent) {
            case Warn:
                return TOExecutionResult.warning(this, new TransformationOperationException(message));
            case NoOp:
                return TOExecutionResult.noOp(this, message);
            case Fail:
                // Fail is the default
            default:
                return TOExecutionResult.error(this, new TransformationOperationException(message));
        }
    }

    if(groupId != null && artifactId != null && version != null) {
        parent.setGroupId(groupId);
        parent.setArtifactId(artifactId);
        parent.setVersion(version);
        String newParent = parent.toString();
        details = String.format("Parent for POM file (%s) has been set to %s", relativePomFile, newParent);
    } else if (groupId == null && artifactId == null && version != null) {
        String oldVersion = parent.getVersion();
        parent.setVersion(version);
        details = String.format("Parent's version for POM file (%s) has been changed from %s to %s", relativePomFile, oldVersion, version);
    } else {
        // FIXME this should be in a pre-validation
        return TOExecutionResult.error(this, new TransformationOperationException("Invalid POM parent transformation operation"));
    }

    return TOExecutionResult.success(this, details);
}
 
Example 11
Source File: ModelTree.java    From butterfly with MIT License 5 votes vote down vote up
@SuppressWarnings("PMD.SimplifyBooleanReturns")
private boolean isParentOf(Model model) {
    if (model.getParent() == null) {
        return false;
    }

    if (!this.model.getGroupId().equals(model.getParent().getGroupId())) return false;
    if (!this.model.getArtifactId().equals(model.getParent().getArtifactId())) return false;
    if (!this.model.getVersion().equals(model.getParent().getVersion())) return false;
    return true;
}
 
Example 12
Source File: PomGetParent.java    From butterfly with MIT License 5 votes vote down vote up
@Override
protected TUExecutionResult pomExecution(Model model) {
    Parent parent = model.getParent();
    if (parent == null) {
        return TUExecutionResult.nullResult(this, "Specified Maven artifact does not have a parent");
    }

    String parentCoordinates = String.format("%s:%s:%s", parent.getGroupId(), parent.getArtifactId(), parent.getVersion());

    return TUExecutionResult.value(this, parentCoordinates);
}
 
Example 13
Source File: GitVersioningModelProcessor.java    From maven-git-versioning-extension with MIT License 5 votes vote down vote up
private Model getParentModel(Model projectModel) {
    if (projectModel.getParent() == null) {
        return null;
    }

    File parentPomPath = new File(projectModel.getProjectDirectory(), projectModel.getParent().getRelativePath());
    final File parentPom;
    if (parentPomPath.isDirectory()) {
        parentPom = new File(parentPomPath, "pom.xml");
    } else {
        parentPom = parentPomPath;
    }

    if (!parentPom.exists()) {
        return null;
    }

    Model parentModel = unchecked(() -> readModel(parentPom));

    GAV parentModelGav = GAV.of(parentModel);
    GAV parentGav = GAV.of(projectModel.getParent());
    if (!parentModelGav.equals(parentGav)) {
        return null;
    }

    return parentModel;
}
 
Example 14
Source File: PomHelper.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the version from a raw model, interpolating from the parent if necessary.
 *
 * @param model The model.
 * @return The version.
 */
public static String getVersion( Model model )
{
    String targetVersion = model.getVersion();
    if ( targetVersion == null && model.getParent() != null )
    {
        targetVersion = model.getParent().getVersion();
    }
    return targetVersion;
}
 
Example 15
Source File: PomHelper.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the groupId from a raw model, interpolating from the parent if necessary.
 *
 * @param model The model.
 * @return The groupId.
 */
public static String getGroupId( Model model )
{
    String targetGroupId = model.getGroupId();
    if ( targetGroupId == null && model.getParent() != null )
    {
        targetGroupId = model.getParent().getGroupId();
    }
    return targetGroupId;
}
 
Example 16
Source File: CreateExtensionMojo.java    From quarkus with Apache License 2.0 4 votes vote down vote up
static String getVersion(Model basePom) {
    return basePom.getVersion() != null ? basePom.getVersion()
            : basePom.getParent() != null && basePom.getParent().getVersion() != null
                    ? basePom.getParent().getVersion()
                    : null;
}
 
Example 17
Source File: ScmPomVersionsMergeClient.java    From unleash-maven-plugin with Eclipse Public License 1.0 4 votes vote down vote up
private void mergeParentVersions(Model local, Model remote, Model base, Model result) throws ScmException {
  String localParentVersion = local.getParent() != null ? local.getParent().getVersion() : null;
  String remoteParentVersion = remote.getParent() != null ? remote.getParent().getVersion() : null;
  String baseParentVersion = base.getParent() != null ? base.getParent().getVersion() : null;

  boolean remoteParentRemoved = remoteParentVersion == null && baseParentVersion != null;
  boolean remoteParentAdded = remoteParentVersion != null && baseParentVersion == null;
  boolean remoteParentVersionChanged = !Objects.equal(remoteParentVersion, baseParentVersion);

  boolean localParentRemoved = localParentVersion == null && baseParentVersion != null;
  boolean localParentAdded = localParentVersion != null && baseParentVersion == null;
  boolean localParentVersionChanged = !Objects.equal(localParentVersion, baseParentVersion);

  if (localParentAdded) {
    // if locally added the base had no parent (remote remove and change is not relevant)
    if (remoteParentAdded) {
      if (Objects.equal(local.getParent().getArtifactId(), remote.getParent().getArtifactId())
          && Objects.equal(local.getParent().getGroupId(), remote.getParent().getGroupId())) {
        if (MavenVersionUtil.isNewerVersion(local.getParent().getVersion(), remote.getParent().getVersion())) {
          result.setParent(local.getParent());
        }
      } else {
        throw new ScmException(ScmOperation.MERGE,
            "Could not merge local and remote POM parent changes since both versions added different parent artifacts.");
      }
    } else {
      result.setParent(local.getParent());
    }
  } else if (localParentRemoved) {
    // if locally removed the base had a parent (remote add is not relevant and remote remove is ok)
    if (remoteParentVersionChanged) {
      throw new ScmException(ScmOperation.MERGE,
          "Could not merge POM parent version conflicts since in the local POM the parent had been removed and in the remote POM the parent had been changed.");
    } else {
      result.getParent().setVersion(localParentVersion);
    }
  } else if (localParentVersionChanged) {
    // if locally changed the base had a parent (remote add is not relevant)
    if (remoteParentVersionChanged) {
      if (Objects.equal(local.getParent().getArtifactId(), remote.getParent().getArtifactId())
          && Objects.equal(local.getParent().getGroupId(), remote.getParent().getGroupId())) {
        if (MavenVersionUtil.isNewerVersion(local.getParent().getVersion(), remote.getParent().getVersion())) {
          result.setParent(local.getParent());
        }
      } else {
        throw new ScmException(ScmOperation.MERGE,
            "Could not merge local and remote POM parent changes since both versions are referencing different parent artifacts.");
      }
    } else if (remoteParentRemoved) {
      throw new ScmException(ScmOperation.MERGE,
          "Could not merge POM parent version conflicts since in the local POM the parent had been updated while in the remote POM the parent had been removed.");
    } else {
      result.getParent().setVersion(localParentVersion);
    }
  }
}
 
Example 18
Source File: CreateExtensionMojo.java    From quarkus with Apache License 2.0 4 votes vote down vote up
static String getGroupId(Model basePom) {
    return basePom.getGroupId() != null ? basePom.getGroupId()
            : basePom.getParent() != null && basePom.getParent().getGroupId() != null
                    ? basePom.getParent().getGroupId()
                    : null;
}
 
Example 19
Source File: SetMojo.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
private void applyChange( MavenProject project, SortedMap<String, Model> reactor, Set<File> files, String groupId,
                          String artifactId, String oldVersion )
{

    getLog().debug( "Applying change " + groupId + ":" + artifactId + ":" + oldVersion + " -> " + newVersion );
    // this is a triggering change
    addChange( groupId, artifactId, oldVersion, newVersion );
    // now fake out the triggering change

    final Map.Entry<String, Model> current = PomHelper.getModelEntry( reactor, groupId, artifactId );
    current.getValue().setVersion( newVersion );

    addFile( files, project, current.getKey() );

    for ( Map.Entry<String, Model> sourceEntry : reactor.entrySet() )
    {
        final String sourcePath = sourceEntry.getKey();
        final Model sourceModel = sourceEntry.getValue();

        getLog().debug( sourcePath.length() == 0 ? "Processing root module as parent"
                        : "Processing " + sourcePath + " as a parent." );

        final String sourceGroupId = PomHelper.getGroupId( sourceModel );
        if ( sourceGroupId == null )
        {
            getLog().warn( "Module " + sourcePath + " is missing a groupId." );
            continue;
        }
        final String sourceArtifactId = PomHelper.getArtifactId( sourceModel );
        if ( sourceArtifactId == null )
        {
            getLog().warn( "Module " + sourcePath + " is missing an artifactId." );
            continue;
        }
        final String sourceVersion = PomHelper.getVersion( sourceModel );
        if ( sourceVersion == null )
        {
            getLog().warn( "Module " + sourcePath + " is missing a version." );
            continue;
        }

        addFile( files, project, sourcePath );

        getLog().debug( "Looking for modules which use "
            + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) + " as their parent" );

        for ( Map.Entry<String, Model> stringModelEntry : processAllModules ? reactor.entrySet() : //
                                                                PomHelper.getChildModels( reactor, sourceGroupId,
                                                                                    sourceArtifactId ).entrySet() )
        {
            final Model targetModel = stringModelEntry.getValue();
            final Parent parent = targetModel.getParent();
            getLog().debug( "Module: " + stringModelEntry.getKey() );
            if ( parent != null && sourceVersion.equals( parent.getVersion() ) )
            {
                getLog().debug( "    parent already is "
                    + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) + ":" + sourceVersion );
            }
            else
            {
                getLog().debug( "    parent is " + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId )
                    + ":" + ( parent == null ? "" : parent.getVersion() ));
                getLog().debug( "    will become " + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId )
                    + ":" + sourceVersion );
            }
            final boolean targetExplicit = PomHelper.isExplicitVersion( targetModel );
            if ( ( updateMatchingVersions || !targetExplicit ) //
                && ( parent != null && StringUtils.equals( parent.getVersion(), PomHelper.getVersion( targetModel ) ) ) )
            {
                getLog().debug( "    module is "
                    + ArtifactUtils.versionlessKey( PomHelper.getGroupId( targetModel ),
                                                    PomHelper.getArtifactId( targetModel ) )
                    + ":" + PomHelper.getVersion( targetModel ) );
                getLog().debug( "    will become "
                    + ArtifactUtils.versionlessKey( PomHelper.getGroupId( targetModel ),
                                                    PomHelper.getArtifactId( targetModel ) )
                    + ":" + sourceVersion );
                addChange( PomHelper.getGroupId( targetModel ), PomHelper.getArtifactId( targetModel ),
                           PomHelper.getVersion( targetModel ), sourceVersion );
                targetModel.setVersion( sourceVersion );
            }
            else
            {
                getLog().debug( "    module is "
                    + ArtifactUtils.versionlessKey( PomHelper.getGroupId( targetModel ),
                                                    PomHelper.getArtifactId( targetModel ) )
                    + ":" + PomHelper.getVersion( targetModel ) );
            }
        }
    }
}
 
Example 20
Source File: CqUtils.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
static String getVersion(Model basePom) {
    return basePom.getVersion() != null ? basePom.getVersion()
            : basePom.getParent() != null && basePom.getParent().getVersion() != null
                    ? basePom.getParent().getVersion()
                    : null;
}