Example usage for org.apache.maven.project MavenProject getFile

List of usage examples for org.apache.maven.project MavenProject getFile

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject getFile.

Prototype

public File getFile() 

Source Link

Usage

From source file:aQute.bnd.maven.plugin.BndMavenPlugin.java

License:Open Source License

private File loadProjectProperties(Builder builder, MavenProject project) throws Exception {
    // Load parent project properties first
    MavenProject parentProject = project.getParent();
    if (parentProject != null) {
        loadProjectProperties(builder, parentProject);
    }// ww w  . jav a 2 s.  co m

    // Merge in current project properties
    Xpp3Dom configuration = project.getGoalConfiguration("biz.aQute.bnd", "bnd-maven-plugin",
            mojoExecution.getExecutionId(), mojoExecution.getGoal());
    File baseDir = project.getBasedir();
    if (baseDir != null) { // file system based pom
        File pomFile = project.getFile();
        builder.updateModified(pomFile.lastModified(), "POM: " + pomFile);
        // check for bnd file
        String bndFileName = Project.BNDFILE;
        if (configuration != null) {
            Xpp3Dom bndfileElement = configuration.getChild("bndfile");
            if (bndfileElement != null) {
                bndFileName = bndfileElement.getValue();
            }
        }
        File bndFile = IO.getFile(baseDir, bndFileName);
        if (bndFile.isFile()) {
            logger.debug("loading bnd properties from file: {}", bndFile);
            // we use setProperties to handle -include
            builder.setProperties(bndFile.getParentFile(), builder.loadProperties(bndFile));
            return bndFile;
        }
        // no bnd file found, so we fall through
    }
    // check for bnd-in-pom configuration
    if (configuration != null) {
        Xpp3Dom bndElement = configuration.getChild("bnd");
        if (bndElement != null) {
            logger.debug("loading bnd properties from bnd element in pom: {}", project);
            UTF8Properties properties = new UTF8Properties();
            properties.load(bndElement.getValue(), project.getFile(), builder);
            if (baseDir != null) {
                String here = baseDir.toURI().getPath();
                here = Matcher.quoteReplacement(here.substring(0, here.length() - 1));
                properties = properties.replaceAll("\\$\\{\\.\\}", here);
            }
            // we use setProperties to handle -include
            builder.setProperties(baseDir, properties);
        }
    }
    return project.getFile();
}

From source file:ch.rotscher.maven.plugins.InstallWithVersionOverrideMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    try {//from   w w w. j  a v a  2 s  . c om

        String versionOverride = System.getProperty("version.override");
        if (versionOverride != null) {
            MavenProject project = getMavenProject();
            if (project != null) {
                getLog().info(
                        "version.override: rewrite the version in the original pom.xom in target/pom.xml");

                //it's very important to set the absolute file name as some classes are using File.equals for comparing
                //to file instances
                File targetDir = new File(project.getBasedir(), "target");
                if (!targetDir.exists()) {
                    targetDir.mkdir();
                }
                File newPomFile = new File(targetDir, "pom.xml");
                newPomFile.createNewFile();
                replaceVersion(project.getFile(), newPomFile, versionOverride);
                project.setFile(newPomFile);
            } else {
                getLog().warn(
                        "could not access the project in InstallMojo: install with version.override did not work!");
            }
        }

    } catch (IOException e) {
        getLog().warn(e);
    } catch (JDOMException e) {
        getLog().warn(e);
    }

    super.execute();
}

From source file:ch.sourcepond.maven.release.pom.UpdateProcessor.java

License:Apache License

@Override
public ChangeSet updatePoms(final Reactor reactor, final boolean incrementSnapshotVersionAfterRelease)
        throws POMUpdateException {
    final DefaultChangeSet changeSet = changeSetFactory.newChangeSet();
    final List<String> errors = new LinkedList<String>();

    for (final ReleasableModule module : reactor) {
        final Version version = module.getVersion();

        // TODO: If a module will not be released, is further processing
        // necessary or should we continue the loop here?
        if (module.getVersion().hasChanged()) {
            log.info(format("Going to release %s %s", module.getArtifactId(), version.getReleaseVersion()));
        }//from  w w w  . j  a v a2s  .  c  om

        final MavenProject project = module.getProject();
        final Model releaseModel = project.getOriginalModel().clone();
        Context context = contextFactory.newContext(reactor, project, releaseModel, false);
        process(context, errors);
        // Mark project to be written at a later stage; if an exception
        // occurs, we don't need to revert anything.
        changeSet.markRelease(project.getFile(), releaseModel, context.needsOwnVersion());

        if (incrementSnapshotVersionAfterRelease) {
            final Model snapshotModel = project.getOriginalModel().clone();
            context = contextFactory.newContext(reactor, project, snapshotModel, true);
            process(context, errors);
            changeSet.markSnapshotVersionIncrement(project.getFile(), snapshotModel, context.needsOwnVersion());
        }
    }

    if (!errors.isEmpty()) {
        final POMUpdateException exception = new POMUpdateException(DEPENDENCY_ERROR_SUMMARY);
        exception.add(DEPENDENCY_ERROR_INTRO);
        for (final String dependencyError : errors) {
            exception.add(" * %s", dependencyError);
        }
        throw exception;
    }

    // At this point it's guaranteed that no dependency errors occurred.
    return changeSet.writeChanges();
}

From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.EclipsePlugin.java

License:Apache License

public final EclipseSourceDir[] buildDirectoryList(MavenProject project, File basedir,
        File buildOutputDirectory) throws MojoExecutionException {
    File projectBaseDir = project.getFile().getParentFile();

    String mainOutput = IdeUtils.toRelativeAndFixSeparator(projectBaseDir, buildOutputDirectory, false);

    // If using the standard output location, don't mix the test output into it.
    String testOutput = null;//from  w ww  .ja  v  a  2 s .  co  m
    boolean useStandardOutputDir = buildOutputDirectory
            .equals(new File(project.getBuild().getOutputDirectory()));
    if (useStandardOutputDir) {
        getLog().debug("testOutput toRelativeAndFixSeparator " + projectBaseDir + " , "
                + project.getBuild().getTestOutputDirectory());
        testOutput = IdeUtils.toRelativeAndFixSeparator(projectBaseDir,
                new File(project.getBuild().getTestOutputDirectory()), false);
        getLog().debug("testOutput after toRelative : " + testOutput);
    }

    Set mainDirectories = new LinkedHashSet();

    extractSourceDirs(mainDirectories, project.getCompileSourceRoots(), basedir, projectBaseDir, false, null);

    extractResourceDirs(mainDirectories, project.getBuild().getResources(), basedir, projectBaseDir, false,
            mainOutput);

    Set testDirectories = new LinkedHashSet();

    extractSourceDirs(testDirectories, project.getTestCompileSourceRoots(), basedir, projectBaseDir, true,
            testOutput);

    extractResourceDirs(testDirectories, project.getBuild().getTestResources(), basedir, projectBaseDir, true,
            testOutput);

    // avoid duplicated entries
    Set directories = new LinkedHashSet();

    // NOTE: Since MNG-3118, test classes come before main classes
    boolean testBeforeMain = isMavenVersion("[2.0.8,)");

    // let users override this if needed, they need to simulate more than the test phase in eclipse
    if (testSourcesLast) {
        testBeforeMain = false;
    }

    if (testBeforeMain) {
        directories.addAll(testDirectories);
        directories.removeAll(mainDirectories);
        directories.addAll(mainDirectories);
    } else {
        directories.addAll(mainDirectories);
        directories.addAll(testDirectories);
    }
    if (ajdt) {
        extractAspectDirs(directories, project, basedir, projectBaseDir, testOutput);
    }
    return (EclipseSourceDir[]) directories.toArray(new EclipseSourceDir[directories.size()]);
}

From source file:com.atlassian.maven.plugin.clover.internal.AbstractCloverMojo.java

License:Apache License

public static File getResourceAsFile(final MavenProject project, final ResourceManager resourceManager,
        final String resourceLocation, final Log logger, final ClassLoader classloader)
        throws MojoExecutionException {

    logger.debug("Getting resource: '" + resourceLocation + "'");

    resourceManager.addSearchPath("url", "");
    resourceManager.addSearchPath(FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath());

    final ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
    try {/*from ww  w . jav  a 2s  . c o m*/
        Thread.currentThread().setContextClassLoader(classloader);
        try {
            logger.debug("Attempting to load resource from [" + resourceLocation + "] ...");
            final File outputFile = File.createTempFile("mvn", "resource");
            outputFile.deleteOnExit();
            return resourceManager.getResourceAsFile(resourceLocation, outputFile.getPath());
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to load resource as file [" + resourceLocation + "]", e);
        }
    } finally {
        Thread.currentThread().setContextClassLoader(origLoader);
    }

}

From source file:com.bugvm.maven.plugin.AbstractBugVMMojo.java

License:Apache License

protected Config.Builder configure(Config.Builder builder) throws MojoExecutionException {
    builder.logger(getBugVMLogger());// ww  w.j  a v a 2s . co m

    // load config base file if it exists (and properties)

    if (os != null) {
        builder.os(OS.valueOf(os));
    }

    if (propertiesFile != null) {
        if (!propertiesFile.exists()) {
            throw new MojoExecutionException(
                    "Invalid 'propertiesFile' specified for BugVM compile: " + propertiesFile);
        }
        try {
            getLog().debug(
                    "Including properties file in BugVM compiler config: " + propertiesFile.getAbsolutePath());
            builder.addProperties(propertiesFile);
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "Failed to add properties file to BugVM config: " + propertiesFile);
        }
    } else {
        try {
            builder.readProjectProperties(project.getBasedir(), false);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to read BugVM project properties file(s) in "
                    + project.getBasedir().getAbsolutePath(), e);
        }
    }

    if (configFile != null) {
        if (!configFile.exists()) {
            throw new MojoExecutionException("Invalid 'configFile' specified for BugVM compile: " + configFile);
        }
        try {
            getLog().debug("Loading config file for BugVM compiler: " + configFile.getAbsolutePath());
            builder.read(configFile);
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to read BugVM config file: " + configFile);
        }
    } else {
        try {
            builder.readProjectConfig(project.getBasedir(), false);
        } catch (Exception e) {
            throw new MojoExecutionException(
                    "Failed to read project BugVM config file in " + project.getBasedir().getAbsolutePath(), e);
        }
    }

    // Read embedded BugVM <config> if there is one
    Plugin plugin = project.getPlugin("com.bugvm:bugvm-maven-plugin");
    MavenProject p = project;
    while (p != null && plugin == null) {
        plugin = p.getPluginManagement().getPluginsAsMap().get("com.bugvm:bugvm-maven-plugin");
        if (plugin == null)
            p = p.getParent();
    }
    if (plugin != null) {
        getLog().debug("Reading BugVM plugin configuration from " + p.getFile().getAbsolutePath());
        Xpp3Dom configDom = (Xpp3Dom) plugin.getConfiguration();
        if (configDom != null && configDom.getChild("config") != null) {
            StringWriter sw = new StringWriter();
            XMLWriter xmlWriter = new PrettyPrintXMLWriter(sw, "UTF-8", null);
            Xpp3DomWriter.write(xmlWriter, configDom.getChild("config"));
            try {
                builder.read(new StringReader(sw.toString()), project.getBasedir());
            } catch (Exception e) {
                throw new MojoExecutionException("Failed to read BugVM config embedded in POM", e);
            }
        }
    }

    File tmpDir = new File(project.getBuild().getDirectory(), "bugvm.tmp");
    try {
        FileUtils.deleteDirectory(tmpDir);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to clean output dir " + tmpDir, e);
    }
    tmpDir.mkdirs();

    Home home = null;
    try {
        home = Home.find();
    } catch (Throwable t) {
    }
    if (home == null || !home.isDev()) {
        home = new Config.Home(unpackBugVMDist());
    }
    builder.home(home).tmpDir(tmpDir).skipInstall(true).installDir(installDir);
    if (home.isDev()) {
        builder.useDebugLibs(Boolean.getBoolean("bugvm.useDebugLibs"));
        builder.dumpIntermediates(true);
    }

    if (debug != null && !debug.equals("false")) {
        builder.debug(true);
        if (debugPort != -1) {
            builder.addPluginArgument("debug:jdwpport=" + debugPort);
        }
        if ("clientmode".equals(debug)) {
            builder.addPluginArgument("debug:clientmode=true");
        }
    }

    if (skipSigning) {
        builder.iosSkipSigning(true);
    } else {
        if (signIdentity != null) {
            getLog().debug("Using explicit signing identity: " + signIdentity);
            builder.iosSignIdentity(SigningIdentity.find(SigningIdentity.list(), signIdentity));
        }

        if (provisioningProfile != null) {
            getLog().debug("Using explicit provisioning profile: " + provisioningProfile);
            builder.iosProvisioningProfile(
                    ProvisioningProfile.find(ProvisioningProfile.list(), provisioningProfile));
        }

        // if (keychainPassword != null) {
        //     builder.keychainPassword(keychainPassword);
        // } else if (keychainPasswordFile != null) {
        //     builder.keychainPasswordFile(keychainPasswordFile);
        // }
    }

    if (cacheDir != null) {
        builder.cacheDir(cacheDir);
    }

    builder.clearClasspathEntries();

    // configure the runtime classpath

    try {
        for (Object object : project.getRuntimeClasspathElements()) {
            String path = (String) object;
            if (getLog().isDebugEnabled()) {
                getLog().debug("Including classpath element for BugVM app: " + path);
            }
            builder.addClasspathEntry(new File(path));
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error resolving application classpath for BugVM build", e);
    }

    return builder;
}

From source file:com.ebay.osgi.maven.compiler.osgi.BundleResolver.java

License:Apache License

public BundleDescription getBundleDescription(MavenProject project) {
    String location = project.getFile().getParentFile().getAbsolutePath();
    return state.getBundleByLocation(location);
}

From source file:com.exentes.maven.versions.UseReleasesMojo.java

License:Apache License

private Collection<String> processProject() throws MojoFailureException {
    List<String> errors = Lists.newArrayList();

    getLog().info("Processing all projects snapshots...");
    SetMultimap<Artifact, MavenProject> allSnapshotProjectArtifacts = VersionMojoUtils
            .allSnapshotProjectArtifacts(session);
    Map<String, Dependency> allDependenciesMap = allDependenciesMap(session);
    Map<Object, MavenProject> origins = origins(session);
    Set<MavenProject> projectsToUpdate = Sets.newHashSet();

    for (Map.Entry<Artifact, Collection<MavenProject>> artifactWithProjects : allSnapshotProjectArtifacts
            .asMap().entrySet()) {//w w w .ja  v a  2  s  . c  o  m
        Artifact snapshotArtifact = artifactWithProjects.getKey();
        Collection<MavenProject> projects = artifactWithProjects.getValue();

        try {
            ArtifactResult artifactResult = resolveReleasedArtifact(snapshotArtifact);
            for (MavenProject project : projects) {
                Dependency dependencyToUpdate = allDependenciesMap
                        .get(projectArtifactKey(project, snapshotArtifact));

                if (isPropertyPlaceholder(dependencyToUpdate.getVersion())) {
                    MavenProject projectToUpdate = origins.get(dependencyToUpdate);
                    String propertyName = getPropertyName(dependencyToUpdate.getVersion());
                    Properties projectProperties = projectToUpdate.getOriginalModel().getProperties();
                    if (projectProperties != null && projectProperties.containsKey(propertyName)) {
                        String newVersion = null;
                        String versionPropertyValue = projectProperties.getProperty(propertyName);
                        VersionRange versionRange = VersionRange.createFromVersionSpec(versionPropertyValue);
                        if (versionRange.getRecommendedVersion() == null) {
                            int restrictionIndex = 0;
                            for (Restriction restriction : versionRange.getRestrictions()) {
                                if (restriction.isUpperBoundInclusive()) {
                                    if (snapshotArtifact.getVersion()
                                            .equals(restriction.getUpperBound().toString())) {
                                        DefaultArtifactVersion updatedVersion = new DefaultArtifactVersion(
                                                artifactResult.getArtifact().getVersion());
                                        Restriction updatedRestriction = new Restriction(
                                                restriction.getUpperBound().equals(restriction.getLowerBound())
                                                        ? updatedVersion
                                                        : restriction.getLowerBound(),
                                                restriction.isLowerBoundInclusive(), updatedVersion,
                                                restriction.isUpperBoundInclusive());
                                        versionRange.getRestrictions().set(restrictionIndex,
                                                updatedRestriction);
                                        newVersion = versionRange.toString();
                                        break;
                                    }
                                }
                                restrictionIndex++;
                            }
                        } else {
                            newVersion = artifactResult.getArtifact().getVersion();
                        }
                        if (newVersion != null) {
                            projectProperties.setProperty(propertyName, newVersion);
                            projectsToUpdate.add(projectToUpdate);
                            getLog().info("Version property {" + propertyName + "} in the project ["
                                    + projectToUpdate.getId() + "] set to the value: "
                                    + artifactResult.getArtifact().getVersion());
                            getLog().info("Snapshot dependency [" + snapshotArtifact + "] is replaced with ["
                                    + artifactResult.getArtifact() + "] in the project: ["
                                    + projectToUpdate.getId() + "]");
                        } else {
                            errors.add("Dependency version value '" + versionPropertyValue
                                    + "' defined as a value of property '" + propertyName + "' not supported");
                        }
                    } else {
                        errors.add("Property [" + propertyName + "] not found in the project ["
                                + projectsToUpdate + "] properties. The artifact version cannot be resolved");
                    }
                } else if (snapshotArtifact.getVersion().equals(dependencyToUpdate.getVersion())) {
                    MavenProject projectToUpdate = origins.get(dependencyToUpdate);
                    projectsToUpdate.add(projectToUpdate);
                    dependencyToUpdate.setVersion(artifactResult.getArtifact().getVersion());
                    getLog().info("Snapshot dependency [" + snapshotArtifact + "] is replaced with ["
                            + artifactResult.getArtifact() + "] in the project: [" + projectToUpdate.getId()
                            + "]");
                } else if (dependencyToUpdate.getVersion() == null) {
                    errors.add("Unknown version for the dependency [" + dependencyToUpdate + "]");
                } else {
                    // check if this is version range
                    try {
                        VersionRange versionRange = VersionRange
                                .createFromVersionSpec(dependencyToUpdate.getVersion());
                        if (versionRange.getRecommendedVersion() == null) {
                            // this this a version range. now all inclusive upper bounds should be inspected and the one which match resolved snapshot version must be upgraded
                            int restrictionIndex = 0;
                            for (Restriction restriction : versionRange.getRestrictions()) {
                                if (restriction.isUpperBoundInclusive()) {
                                    if (isPropertyPlaceholder(restriction.getUpperBound().toString())) {
                                        // try to update a property which is used as an upper version boundary
                                        String propertyName = getPropertyName(
                                                restriction.getUpperBound().toString());
                                        getLog().info("property name: " + propertyName);
                                        MavenProject projectToUpdate = origins.get(dependencyToUpdate);
                                        Properties projectProperties = projectToUpdate.getOriginalModel()
                                                .getProperties();
                                        if (projectProperties != null
                                                && projectProperties.containsKey(propertyName)
                                                && projectProperties.getProperty(propertyName)
                                                        .equals(snapshotArtifact.getVersion())) {
                                            projectProperties.setProperty(propertyName,
                                                    artifactResult.getArtifact().getVersion());
                                            projectsToUpdate.add(projectToUpdate);
                                            getLog().info(
                                                    "Version property {" + propertyName + "} in the project ["
                                                            + projectToUpdate.getId() + "] set to the value: "
                                                            + artifactResult.getArtifact().getVersion());
                                            getLog().info("Snapshot dependency [" + snapshotArtifact
                                                    + "] is replaced with [" + artifactResult.getArtifact()
                                                    + "] in the project: [" + projectToUpdate.getId() + "]");
                                            break;
                                        }
                                    } else {
                                        if (snapshotArtifact.getVersion()
                                                .equals(restriction.getUpperBound().toString())) {
                                            DefaultArtifactVersion updatedVersion = new DefaultArtifactVersion(
                                                    artifactResult.getArtifact().getVersion());
                                            Restriction updatedRestriction = new Restriction(
                                                    restriction.getUpperBound().equals(
                                                            restriction.getLowerBound()) ? updatedVersion
                                                                    : restriction.getLowerBound(),
                                                    restriction.isLowerBoundInclusive(), updatedVersion,
                                                    restriction.isUpperBoundInclusive());
                                            versionRange.getRestrictions().set(restrictionIndex,
                                                    updatedRestriction);
                                            MavenProject projectToUpdate = origins.get(dependencyToUpdate);
                                            projectsToUpdate.add(projectToUpdate);
                                            dependencyToUpdate.setVersion(versionRange.toString());
                                            getLog().info("Snapshot dependency [" + snapshotArtifact
                                                    + "] is replaced with [" + dependencyToUpdate
                                                    + "] in the project: [" + projectToUpdate.getId() + "]");
                                            break;
                                        }
                                    }
                                }
                                restrictionIndex++;
                            }
                        } else {
                            errors.add("Dependency version value [" + dependencyToUpdate.getVersion()
                                    + "] not supported");
                        }
                    } catch (InvalidVersionSpecificationException e) {
                        errors.add("Invalid version specified: " + dependencyToUpdate.getVersion()
                                + ". Exception when parsing version: " + e.getMessage());
                    }
                }
            }
        } catch (ArtifactResolutionException e) {
            getLog().info(e);
            errors.add("Failed to resolve a RELEASE version for [" + snapshotArtifact + "]. Exception: "
                    + e.getMessage());
        } catch (InvalidVersionSpecificationException e) {
            errors.add("Invalid version specified: " + snapshotArtifact.getVersion()
                    + ". Exception when parsing version: " + e.getMessage());
        }
    }

    if (!dryRun) {
        for (MavenProject project : projectsToUpdate) {
            try {
                modelWriter.write(project.getFile(), null, project.getOriginalModel());
            } catch (IOException e) {
                throw new MojoFailureException("Error writing POM", e);
            }
        }
    }
    return errors;
}

From source file:com.github.ferstl.maven.pomenforcers.AbstractPedanticEnforcer.java

License:Apache License

@Override
public final void execute(EnforcerRuleHelper helper) throws EnforcerRuleException {
    MavenProject project = EnforcerRuleUtils.getMavenProject(helper);
    Document pom = XmlUtils.parseXml(project.getFile());
    PomSerializer pomSerializer = new PomSerializer(pom);
    ProjectModel model = pomSerializer.read();

    initialize(helper, pom, model);//from w  ww.j  ava2 s  .  c o m

    ErrorReport report = new ErrorReport(getDescription());
    doEnforce(report);

    if (report.hasErrors()) {
        throw new EnforcerRuleException(report.toString());
    }
}

From source file:com.github.jeluard.maven.ParentEnforcerRule.java

License:Apache License

protected final File extractRootFolder(final MavenProject project) {
    return new File(project.getFile().getParentFile().getPath());
}