Java Code Examples for org.apache.maven.project.MavenProject#getFile()

The following examples show how to use org.apache.maven.project.MavenProject#getFile() . 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: NbMavenProjectImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected List<File> getParents() {
    LinkedList<File> ret = new LinkedList<>();
    MavenProject project = getOriginalMavenProject();
    while(true) {
        try {
            MavenProject parent = loadParentOf(getEmbedder(), project);
            File parentFile = parent != null ? parent.getFile() : null;
            if(parentFile != null) {
                ret.add(parentFile);
                project = parent;
            } else {
                break;
            }
        } catch (ProjectBuildingException ex) {
            break;
        }
    } 
    return ret;
}
 
Example 2
Source File: MavenEmbedder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * normalize all File references in the object tree.
 * @param project 
 * @since 2.36
 */
public static void normalizePaths(MavenProject project) {
    if (project == null) {
        return;
    }
    File f = project.getFile();
    if (f != null) {
        project.setFile(FileUtil.normalizeFile(f));
    }
    normalizePath(project.getArtifact());
    normalizePaths(project.getAttachedArtifacts());
    f = project.getParentFile();
    if (f != null) {
        project.setParentFile(FileUtil.normalizeFile(f));
    }
    normalizePath(project.getParentArtifact());
    
    normalizePaths(project.getArtifacts());
    normalizePaths(project.getDependencyArtifacts());
    normalizePaths(project.getExtensionArtifacts());
    normalizePaths(project.getPluginArtifacts());
    
    normalizePath(project.getModel());
    normalizePath(project.getOriginalModel());
}
 
Example 3
Source File: AbstractVersionModifyingMojo.java    From revapi with Apache License 2.0 6 votes vote down vote up
void updateProjectParentVersion(MavenProject project, Version version) throws MojoExecutionException {
    try {
        VTDGen gen = new VTDGen();
        gen.enableIgnoredWhiteSpace(true);
        gen.parseFile(project.getFile().getAbsolutePath(), true);

        VTDNav nav = gen.getNav();
        AutoPilot ap = new AutoPilot(nav);
        ap.selectXPath("namespace-uri(.)");
        String ns = ap.evalXPathToString();

        nav.toElementNS(VTDNav.FIRST_CHILD, ns, "parent");
        nav.toElementNS(VTDNav.FIRST_CHILD, ns, "version");
        int pos = nav.getText();

        XMLModifier mod = new XMLModifier(nav);
        mod.updateToken(pos, version.toString());

        try (OutputStream out = new FileOutputStream(project.getFile())) {
            mod.output(out);
        }
    } catch (IOException | ModifyException | NavException | XPathParseException | TranscodeException e) {
        throw new MojoExecutionException("Failed to update the parent version of project " + project, e);
    }
}
 
Example 4
Source File: SimpleReactorReader.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public File findArtifact(Artifact artifact) {
  MavenProject project = getProject(artifact);
  if (project != null) {
    if ("pom".equals(artifact.getExtension())) {
      return project.getFile();
    } else if ("jar".equals(artifact.getExtension()) && "".equals(artifact.getClassifier())) {
      return new File(project.getBuild().getOutputDirectory());
    }
  }
  Artifact _artifact = getArtifact(artifact);
  if (_artifact != null) {
    return _artifact.getFile();
  }
  return null;
}
 
Example 5
Source File: DefaultPomHelper.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Set<MavenProject> expandProjects ( final Collection<MavenProject> projects, final Log log, final MavenSession session )
{
    try
    {
        final Set<MavenProject> result = new HashSet<MavenProject> ();

        final Queue<MavenProject> queue = new LinkedList<MavenProject> ( projects );
        while ( !queue.isEmpty () )
        {
            final MavenProject project = queue.poll ();
            log.debug ( "Checking project: " + project );
            if ( project.getFile () == null )
            {
                log.info ( "Skipping non-local project: " + project );
                continue;
            }
            if ( !result.add ( project ) )
            {
                // if the project was already in our result, there is no need to process twice
                continue;
            }
            // add all children to the queue
            queue.addAll ( loadChildren ( project, log, session ) );
            if ( hasLocalParent ( project ) )
            {
                // if we have a parent, add the parent as well
                queue.add ( project.getParent () );
            }
        }
        return result;
    }
    catch ( final Exception e )
    {
        throw new RuntimeException ( e );
    }
}
 
Example 6
Source File: PomUtil.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Serializes the passed document which should contain POM content to the project file of the passed Maven project.
 *
 * @param document the document to be serialized.
 * @param project the project from which the serialization target will be retrieved.
 */
public static final void writePOM(Document document, MavenProject project) {
  File pom = project.getFile();
  Preconditions.checkArgument(pom != null && pom.exists() && pom.isFile(),
      "The passed project does not contain a valid POM file reference.");

  try {
    writePOM(document, new FileOutputStream(pom), true);
  } catch (Throwable t) {
    throw new RuntimeException("Could not serialize the project object model of the following module: "
        + ProjectToString.INSTANCE.apply(project), t);
  }
}
 
Example 7
Source File: MavenPluginUtil.java    From galleon with Apache License 2.0 4 votes vote down vote up
public InstallRequest getInstallLayoutRequest(final Path layoutDir, final MavenProject project) throws IOException {
    final File pomFile = project.getFile();
    final Logger logger = getLogger();
    final InstallRequest installReq = new InstallRequest();
    try (DirectoryStream<Path> wdStream = Files.newDirectoryStream(layoutDir, entry -> Files.isDirectory(entry))) {
        for (Path groupDir : wdStream) {
            final String groupId = groupDir.getFileName().toString();
            try (DirectoryStream<Path> groupStream = Files.newDirectoryStream(groupDir)) {
                for (Path artifactDir : groupStream) {
                    final String artifactId = artifactDir.getFileName().toString();
                    try (DirectoryStream<Path> artifactStream = Files.newDirectoryStream(artifactDir)) {
                        for (Path versionDir : artifactStream) {
                            if(logger.isDebugEnabled()) {
                                logger.debug("Preparing feature-pack " + versionDir.toAbsolutePath());
                            }
                            final Path zippedFP = layoutDir.resolve(
                                    groupId + '_' + artifactId + '_' + versionDir.getFileName().toString() + ".zip");
                            if(Files.exists(zippedFP)) {
                                IoUtils.recursiveDelete(zippedFP);
                            }
                            ZipUtils.zip(versionDir, zippedFP);
                            final Artifact artifact = new DefaultArtifact(
                                    groupDir.getFileName().toString(),
                                    artifactDir.getFileName().toString(), null,
                                    "zip", versionDir.getFileName().toString(), null, zippedFP.toFile());
                            Path target = Paths.get(project.getBuild().getDirectory()).resolve(project.getBuild().getFinalName() + ".zip");
                            IoUtils.copy(zippedFP, target);
                            installReq.addArtifact(artifact);
                            if (pomFile != null && Files.exists(pomFile.toPath())) {
                                Artifact pomArtifact = new SubArtifact(artifact, "", "pom");
                                pomArtifact = pomArtifact.setFile(pomFile);
                                installReq.addArtifact(pomArtifact);
                            }
                        }
                    }
                }
            }
        }
    }
    return installReq;
}
 
Example 8
Source File: ExternalVersionExtension.java    From maven-external-version with Apache License 2.0 4 votes vote down vote up
private void createNewVersionPom( MavenProject mavenProject, Map<String, String> gavVersionMap )
    throws IOException, XmlPullParserException
{
    Reader fileReader = null;
    Writer fileWriter = null;
    try
    {
        fileReader = new FileReader( mavenProject.getFile() );
        Model model = new MavenXpp3Reader().read( fileReader );
        model.setVersion( mavenProject.getVersion() );


        // TODO: this needs to be restructured when other references are updated (dependencies, dep-management, plugins, etc)
        if ( model.getParent() != null )
        {
            String key = buildGavKey( model.getParent().getGroupId(), model.getParent().getArtifactId(),
                                      model.getParent().getVersion() );
            String newVersionForParent = gavVersionMap.get( key );
            if ( newVersionForParent != null )
            {
                model.getParent().setVersion( newVersionForParent );
            }
        }
        
        Plugin plugin = mavenProject.getPlugin( "org.apache.maven.plugins:maven-external-version-plugin" );
        // now we are going to wedge in the config
        Xpp3Dom pluginConfiguration = (Xpp3Dom) plugin.getConfiguration();
        
        File newPom = createFileFromConfiguration( mavenProject, pluginConfiguration ); 
        logger.debug( ExternalVersionExtension.class.getSimpleName() + ": using new pom file => " + newPom );
        fileWriter = new FileWriter( newPom );
        new MavenXpp3Writer().write( fileWriter, model );

        mavenProject.setFile( newPom );
    }
    finally
    {
        IOUtil.close( fileReader );
        IOUtil.close( fileWriter );
    }


}
 
Example 9
Source File: AbstractVersionModifyingMojo.java    From revapi with Apache License 2.0 4 votes vote down vote up
void updateProjectVersion(MavenProject project, Version version) throws MojoExecutionException {
    try {

        int indentationSize;
        try (BufferedReader rdr = new BufferedReader(new FileReader(project.getFile()))) {
            indentationSize = XmlUtil.estimateIndentationSize(rdr);
        }

        VTDGen gen = new VTDGen();
        gen.enableIgnoredWhiteSpace(true);
        gen.parseFile(project.getFile().getAbsolutePath(), true);

        VTDNav nav = gen.getNav();
        AutoPilot ap = new AutoPilot(nav);
        XMLModifier mod = new XMLModifier(nav);

        ap.selectXPath("/project/version");
        if (ap.evalXPath() != -1) {
            //found the version
            int textPos = nav.getText();
            mod.updateToken(textPos, version.toString());
        } else {
            if (!forceVersionUpdate && !project.getParent().getVersion().equals(version.toString())) {
                throw new MojoExecutionException("Project " + project.getArtifactId() + " inherits the version" +
                        " from the parent project (" + project.getParent().getVersion() + ") but should have a" +
                        " different version according to the configured rules (" + version.toString() + "). If" +
                        " you wish to insert an explicit version instead of inheriting it, set the " +
                        Props.forceVersionUpdate.NAME + " property to true.");
            }

            //place the version after the artifactId
            ap.selectXPath("/project/artifactId");
            if (ap.evalXPath() == -1) {
                throw new MojoExecutionException("Failed to find artifactId element in the pom.xml of project "
                        + project.getArtifact().getId() + " when trying to insert a version tag after it.");
            } else {
                StringBuilder versionLine = new StringBuilder();
                versionLine.append('\n');
                for (int i = 0; i < indentationSize; ++i) {
                    versionLine.append(' ');
                }
                versionLine.append("<version>").append(version.toString()).append("</version>");
                mod.insertAfterElement(versionLine.toString());
            }
        }

        try (OutputStream out = new FileOutputStream(project.getFile())) {
            mod.output(out);
        }
    } catch (IOException | ModifyException | NavException | XPathParseException | XPathEvalException | TranscodeException e) {
        throw new MojoExecutionException("Failed to update the version of project " + project, e);
    }
}
 
Example 10
Source File: ConvertToXmlConfigMojo.java    From revapi with Apache License 2.0 4 votes vote down vote up
private void updateAllConfigurationFiles(MavenProject project, Map<String, ModelNode> extensionSchemas,
                                         int indentationSize) throws Exception {
    VTDGen gen = new VTDGen();
    gen.enableIgnoredWhiteSpace(true);
    gen.parseFile(project.getFile().getAbsolutePath(), true);

    VTDNav nav = gen.getNav();
    XMLModifier mod = new XMLModifier(nav);

    AutoPilot ap = new AutoPilot(nav);

    ThrowingConsumer<String> update = xpath -> {
        ap.resetXPath();
        ap.selectXPath(xpath);

        while (ap.evalXPath() != -1) {
            int textPos = nav.getText();

            String configFile = nav.toString(textPos);

            File newFile = updateConfigurationFile(new File(configFile), extensionSchemas, indentationSize);
            if (newFile == null) {
                continue;
            }

            mod.updateToken(textPos, newFile.getPath());
        }
    };

    update.accept("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']" +
            "/configuration/analysisConfigurationFiles/*[not(self::configurationFile)]");
    update.accept("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']" +
            "/configuration/analysisConfigurationFiles/configurationFile[not(roots)]/path");

    update.accept("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']" +
            "/executions/execution/configuration/analysisConfigurationFiles/*[not(self::configurationFile)]");
    update.accept("//plugin[groupId = 'org.revapi' and artifactId = 'revapi-maven-plugin']" +
            "/executions/execution/configuration/analysisConfigurationFiles/configurationFile[not(roots)]/path");

    try (OutputStream out = new FileOutputStream(project.getFile())) {
        mod.output(out);
    }
}
 
Example 11
Source File: CompilerBuildContext.java    From takari-lifecycle with Eclipse Public License 1.0 4 votes vote down vote up
@Inject
public CompilerBuildContext(BuildContextEnvironment configuration, MavenProject project) {
  super(configuration);
  pom = project.getFile();
}