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:com.github.zhve.ideaplugin.IdeaPluginMojo.java

License:Apache License

protected void doExecute() throws Exception {
    // prepare/*from  w ww. j  a v a2 s.c  o  m*/
    ArtifactHolder artifactHolder = getArtifactHolder();
    VelocityWorker velocityWorker = getVelocityWorker();
    VelocityContext context = new VelocityContext();
    MavenProject project = getProject();

    // fill iml-attributes
    String buildDirectory = project.getBuild().getDirectory();
    String standardBuildDirectory = project.getFile().getParent() + File.separator + "target";
    context.put("buildDirectory",
            buildDirectory.startsWith(standardBuildDirectory) ? standardBuildDirectory : buildDirectory);
    context.put("context", this);
    context.put("gaeHome", gaeHome == null ? null : new File(gaeHome).getCanonicalPath());
    context.put("MD", "$MODULE_DIR$");
    context.put("packagingPom", "pom".equals(project.getPackaging()));
    context.put("packagingWar", "war".equals(project.getPackaging()));
    context.put("project", project);

    // generate iml file
    createFile(context, velocityWorker.getImlTemplate(), "iml");

    // for non execution root just exit
    if (!getProject().isExecutionRoot())
        return;

    // fill ipr-attributes
    context.put("M", getLocalRepositoryBasePath());
    context.put("assembleModulesIntoJars", assembleModulesIntoJars);
    context.put("jdkName", jdkName);
    context.put("jdkLevel", jdkLevel);
    context.put("wildcardResourcePatterns", Util.escapeXmlAttribute(wildcardResourcePatterns));
    List<MavenProject> warProjects = artifactHolder.getProjectsWithPackaging("war");
    // check id uniques
    Set<String> used = new HashSet<String>();
    for (MavenProject item : warProjects)
        if (!used.add(item.getArtifactId()))
            throw new MojoExecutionException(
                    "Two or more war-packagins projects in reactor have the same artifactId, please make sure that <artifactId> is unique for each war-packagins project.");
    Collections.sort(warProjects, ProjectComparator.INSTANCE);
    context.put("warProjects", warProjects);

    IssueManagement issueManagement = getProject().getIssueManagement();
    if (issueManagement != null) {
        String system = issueManagement.getSystem();
        String url = issueManagement.getUrl();
        if ("Redmine".equalsIgnoreCase(system)) {
            context.put("issueNavigationExist", Boolean.TRUE);
            context.put("issueRegexp", "\\d+");
            context.put("linkRegexp", url + "/issues/$0");
        } else if ("JIRA".equalsIgnoreCase(system)) {
            context.put("issueNavigationExist", Boolean.TRUE);
            context.put("issueRegexp", "[A-Z]+\\-\\d+");
            context.put("linkRegexp", url + "/browse/$0");
        } else if ("YouTrack".equalsIgnoreCase(system)) {
            context.put("issueNavigationExist", Boolean.TRUE);
            context.put("issueRegexp", "[A-Z]+\\-\\d+");
            context.put("linkRegexp", url + "/issue/$0");
        } else if ("Google Code".equalsIgnoreCase(system)) {
            context.put("issueNavigationExist", Boolean.TRUE);
            context.put("issueRegexp", "\\d+");
            context.put("linkRegexp", url + "/issues/detail?id=$0");
        } else if ("GitHub".equalsIgnoreCase(system)) {
            context.put("issueNavigationExist", Boolean.TRUE);
            context.put("issueRegexp", "\\d+");
            context.put("linkRegexp", url + "/$0");
        }
    }

    createFile(context, velocityWorker.getIprTemplate(), "ipr");

    // fill iws-attributes
    context.put("compileInBackground", compileInBackground);
    context.put("assertNotNull", assertNotNull);
    context.put("hideEmptyPackages", hideEmptyPackages);
    context.put("autoscrollToSource", autoscrollToSource);
    context.put("autoscrollFromSource", autoscrollFromSource);
    context.put("sortByType", sortByType);
    context.put("optimizeImportsBeforeCommit", optimizeImportsBeforeCommit);
    context.put("reformatCodeBeforeCommit", reformatCodeBeforeCommit);
    context.put("performCodeAnalysisBeforeCommit", performCodeAnalysisBeforeCommit);

    if (!warProjects.isEmpty()) {
        // fill war-attributes
        MavenProject warProject = getDefaultWarProject(warProjects);
        context.put("warProject", warProject);
        warProjects.remove(warProject);
        context.put("otherWarProjects", warProjects);
        context.put("applicationServerTitle",
                StringUtils.isEmpty(applicationServerTitle) ? warProject.getArtifactId()
                        : Util.escapeXmlAttribute(applicationServerTitle));
        context.put("applicationServerName", gaeHome == null ? applicationServerName : "Google AppEngine Dev");
        context.put("applicationServerVersion", applicationServerVersion);
        context.put("openInBrowser", openInBrowser);
        context.put("openInBrowserUrl", Util.escapeXmlAttribute(openInBrowserUrl));
        context.put("vmParameters", vmParameters == null ? "" : Util.escapeXmlAttribute(vmParameters));
        context.put("deploymentContextPath", deploymentContextPath);

        if (gaeHome != null) {
            context.put("applicationServerConfigurationType", "GoogleAppEngineDevServer");
            context.put("applicationServerFullName",
                    applicationServerFullName == null ? "AppEngine Dev" : applicationServerFullName);
        } else if ("Tomcat".equals(applicationServerName)) {
            context.put("applicationServerConfigurationType",
                    "#com.intellij.j2ee.web.tomcat.TomcatRunConfigurationFactory");
            context.put("applicationServerFullName",
                    applicationServerFullName == null ? applicationServerName + " " + applicationServerVersion
                            : applicationServerFullName);
        } else if ("Jetty".equals(applicationServerName)) {
            context.put("applicationServerConfigurationType",
                    "org.codebrewer.idea.jetty.JettyRunConfigurationType");
            context.put("applicationServerFullName",
                    applicationServerFullName == null ? applicationServerName + " " + applicationServerVersion
                            : applicationServerFullName);
        } else
            throw new MojoExecutionException("Unknown applicationServerName: " + applicationServerName
                    + ", possible values: Tomcat, Jetty");
    }

    createFile(context, velocityWorker.getIwsTemplate(), "iws");

    File idea = new File(project.getBasedir(), ".idea");
    if (idea.exists()) {
        getLog().info("");
        getLog().info("Delete Workspace Files:");
        getLog().info("");
        Util.deleteFileOrDirectory(getLog(), idea);
    }
}

From source file:com.github.zhve.ideaplugin.IdeaPluginMojoBase.java

License:Apache License

public List<String> getReactorPaths() {
    List<String> list = new ArrayList<String>();
    list.add(new File(project.getFile().getParentFile(), project.getArtifactId() + ".iml").getAbsolutePath());
    for (Object collectedProject : project.getCollectedProjects()) {
        MavenProject reactorProject = (MavenProject) collectedProject;
        list.add(new File(reactorProject.getFile().getParentFile(), reactorProject.getArtifactId() + ".iml")
                .getAbsolutePath());//www  . j  a va2s. c  o m
    }
    return list;
}

From source file:com.google.gdt.eclipse.maven.e35.configurators.GoogleProjectConfigurator.java

License:Open Source License

@Override
protected void doConfigure(final MavenProject mavenProject, IProject project,
        ProjectConfigurationRequest request, final IProgressMonitor monitor) throws CoreException {

    final IMaven maven = MavenPlugin.getDefault().getMaven();

    boolean configureGaeNatureSuccess = configureNature(project, mavenProject, GaeNature.NATURE_ID, true,
            new NatureCallbackAdapter() {

                @Override//from   w  w  w . jav a  2  s  . c  o m
                public void beforeAddingNature() {
                    try {
                        DefaultMavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
                        executionRequest.setBaseDirectory(mavenProject.getBasedir());
                        executionRequest.setLocalRepository(maven.getLocalRepository());
                        executionRequest.setRemoteRepositories(mavenProject.getRemoteArtifactRepositories());
                        executionRequest
                                .setPluginArtifactRepositories(mavenProject.getPluginArtifactRepositories());
                        executionRequest.setPom(mavenProject.getFile());
                        executionRequest.setGoals(GAE_UNPACK_GOAL);

                        MavenExecutionResult result = maven.execute(executionRequest, monitor);
                        if (result.hasExceptions()) {
                            Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                                    "Error configuring project", result.getExceptions().get(0)));
                        }
                    } catch (CoreException e) {
                        Activator.getDefault().getLog().log(
                                new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error configuring project", e));
                    }
                }
            }, monitor);

    boolean configureGWTNatureSuccess = configureNature(project, mavenProject, GWTNature.NATURE_ID, true,
            new NatureCallbackAdapter() {

                @Override
                public void beforeAddingNature() {

                    // Get the GWT version from the project pom
                    String gwtVersion = null;
                    List<Dependency> dependencies = mavenProject.getDependencies();
                    for (Dependency dependency : dependencies) {
                        if (GWTMavenRuntime.MAVEN_GWT_GROUP_ID.equals(dependency.getGroupId())
                                && (GWTMavenRuntime.MAVEN_GWT_USER_ARTIFACT_ID
                                        .equals(dependency.getArtifactId())
                                        || GWTMavenRuntime.MAVEN_GWT_SERVLET_ARTIFACT_ID
                                                .equals(dependency.getArtifactId()))) {
                            gwtVersion = dependency.getVersion();
                            break;
                        }
                    }

                    // Check that the pom.xml has GWT dependencies
                    if (!StringUtilities.isEmpty(gwtVersion)) {
                        try {
                            /*
                             * Download and install the gwt-dev.jar into the local
                             * repository.
                             */
                            maven.resolve(GWTMavenRuntime.MAVEN_GWT_GROUP_ID,
                                    GWTMavenRuntime.MAVEN_GWT_DEV_JAR_ARTIFACT_ID, gwtVersion, "jar", null,
                                    mavenProject.getRemoteArtifactRepositories(), monitor);
                        } catch (CoreException e) {
                            Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                                    "Error configuring project", e));
                        }
                    }
                }
            }, monitor);

    if (configureGWTNatureSuccess || configureGaeNatureSuccess) {
        try {
            // Add GWT Web Application configuration parameters
            WebAppProjectProperties.setWarSrcDir(project, new Path("src/main/webapp"));
            WebAppProjectProperties.setWarSrcDirIsOutput(project, false);

            String artifactId = mavenProject.getArtifactId();
            String version = mavenProject.getVersion();
            IPath location = (project.getRawLocation() != null ? project.getRawLocation()
                    : project.getLocation());
            if (location != null && artifactId != null && version != null) {
                WebAppProjectProperties.setLastUsedWarOutLocation(project,
                        location.append("target").append(artifactId + "-" + version));
            }
        } catch (BackingStoreException be) {
            Activator.getDefault().getLog()
                    .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error configuring project", be));
        }
    }
}

From source file:com.groupon.maven.plugin.json.DefaultValidatorExecutor.java

License:Apache License

static void configureInputLocator(final MavenProject project,
        final ResourceManager inputLocator) {
    inputLocator.setOutputDirectory(new File(project.getBuild().getDirectory()));

    MavenProject parent = project;
    while (parent != null && parent.getFile() != null) {
        final File dir = parent.getFile().getParentFile();
        inputLocator.addSearchPath(FileResourceLoader.ID, dir.getAbsolutePath());
        parent = parent.getParent();/*from w w w. j ava 2 s.  com*/
    }
    inputLocator.addSearchPath("url", "");
}

From source file:com.oracle.istack.maven.PropertyResolver.java

License:Open Source License

/**
 *
 * @param project maven project/*from ww  w.  j a va 2  s  .  co  m*/
 * @throws FileNotFoundException properties not found
 * @throws IOException IO error
 * @throws XmlPullParserException error parsing xml
 */
public void resolveProperties(MavenProject project)
        throws FileNotFoundException, IOException, XmlPullParserException {
    logger.info("Resolving properties for " + project.getGroupId() + ":" + project.getArtifactId());

    Model model = null;
    FileReader reader;
    try {
        reader = new FileReader(project.getFile());
        model = mavenreader.read(reader);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ImportPropertiesMojo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ImportPropertiesMojo.class.getName()).log(Level.SEVERE, null, ex);
    }
    MavenProject loadedProject = new MavenProject(model);

    DependencyManagement dm = loadedProject.getDependencyManagement();
    if (dm == null) {
        logger.warn("No dependency management section found in: " + loadedProject.getGroupId() + ":"
                + loadedProject.getArtifactId());
        return;
    }

    List<Dependency> depList = dm.getDependencies();

    DependencyResult result;
    for (Dependency d : depList) {
        if ("import".equals(d.getScope())) {
            try {
                String version = d.getVersion();
                logger.info("Imported via import-scope: " + d.getGroupId() + ":" + d.getArtifactId() + ":"
                        + version);
                if (version.contains("$")) {
                    version = properties
                            .getProperty(version.substring(version.indexOf('{') + 1, version.lastIndexOf('}')));
                    logger.info("Imported version resolved to: " + version);
                }
                d.setVersion(version);
                d.setType("pom");
                d.setClassifier("pom");
                result = DependencyResolver.resolve(d, pluginRepos, repoSystem, repoSession);
                Artifact a = result.getArtifactResults().get(0).getArtifact();
                reader = new FileReader(a.getFile());
                Model m = mavenreader.read(reader);
                MavenProject p = new MavenProject(m);
                p.setFile(a.getFile());
                for (Map.Entry<Object, Object> e : p.getProperties().entrySet()) {
                    logger.info("Setting property: " + (String) e.getKey() + ":" + (String) e.getValue());
                    properties.setProperty((String) e.getKey(), (String) e.getValue());
                }

                resolveProperties(p);
            } catch (DependencyResolutionException ex) {
                Logger.getLogger(ImportPropertiesMojo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.photon.maven.plugins.android.AbstractAndroidMojoTestCase.java

License:Apache License

/**
 * Copy the project specified into a temporary testing directory. Create the {@link MavenProject} and
 * {@link ManifestUpdateMojo}, configure it from the <code>plugin-config.xml</code> and return the created Mojo.
 * <p>/*w w w .  ja va2  s.  c o m*/
 * Note: only configuration entries supplied in the plugin-config.xml are presently configured in the mojo returned.
 * That means and 'default-value' settings are not automatically injected by this testing framework (or plexus
 * underneath that is suppling this functionality)
 * 
 * @param resourceProject
 *            the name of the goal to look for in the <code>plugin-config.xml</code> that the configuration will be
 *            pulled from.
 * @param resourceProject
 *            the resourceProject path (in src/test/resources) to find the example/test project.
 * @return the created mojo (unexecuted)
 * @throws Exception
 *             if there was a problem creating the mojo.
 */
protected T createMojo(String resourceProject) throws Exception {
    // Establish test details project example
    String testResourcePath = "src/test/resources/" + resourceProject;
    testResourcePath = FilenameUtils.separatorsToSystem(testResourcePath);
    File exampleDir = new File(getBasedir(), testResourcePath);
    Assert.assertTrue("Path should exist: " + exampleDir, exampleDir.exists());

    // Establish the temporary testing directory.
    String testingPath = "target/tests/" + this.getClass().getSimpleName() + "." + getName();
    testingPath = FilenameUtils.separatorsToSystem(testingPath);
    File testingDir = new File(getBasedir(), testingPath);

    if (testingDir.exists()) {
        FileUtils.cleanDirectory(testingDir);
    } else {
        Assert.assertTrue("Could not create directory: " + testingDir, testingDir.mkdirs());
    }

    // Copy project example into temporary testing directory
    // to avoid messing up the good source copy, as mojo can change
    // the AndroidManifest.xml file.
    FileUtils.copyDirectory(exampleDir, testingDir);

    // Prepare MavenProject
    final MavenProject project = new MojoProjectStub(testingDir);

    // Setup Mojo
    PlexusConfiguration config = extractPluginConfiguration("android-maven-plugin", project.getFile());
    @SuppressWarnings("unchecked")
    final T mojo = (T) lookupMojo(getPluginGoalName(), project.getFile());

    // Inject project itself
    setVariableValueToObject(mojo, "project", project);

    // Configure the rest of the pieces via the PluginParameterExpressionEvaluator
    //  - used for ${plugin.*}
    MojoDescriptor mojoDesc = new MojoDescriptor();
    // - used for error messages in PluginParameterExpressionEvaluator
    mojoDesc.setGoal(getPluginGoalName());
    MojoExecution mojoExec = new MojoExecution(mojoDesc);
    // - Only needed if we start to use expressions like ${settings.*}, ${localRepository}, ${reactorProjects}
    // MavenSession context = null; // Messy to declare, would rather avoid using it.
    // - Used for ${basedir} relative paths
    PathTranslator pathTranslator = new DefaultPathTranslator();
    // - Declared to prevent NPE from logging events in maven core
    Logger logger = new ConsoleLogger(Logger.LEVEL_DEBUG, mojo.getClass().getName());

    MavenSession context = createMock(MavenSession.class);

    expect(context.getExecutionProperties()).andReturn(project.getProperties());
    expect(context.getCurrentProject()).andReturn(project);
    replay(context);

    // Declare evalator that maven itself uses.
    ExpressionEvaluator evaluator = new PluginParameterExpressionEvaluator(context, mojoExec, pathTranslator,
            logger, project, project.getProperties());
    // Lookup plexus configuration component
    ComponentConfigurator configurator = (ComponentConfigurator) lookup(ComponentConfigurator.ROLE, "basic");
    // Configure mojo using above
    ConfigurationListener listener = new DebugConfigurationListener(logger);
    configurator.configureComponent(mojo, config, evaluator, getContainer().getContainerRealm(), listener);

    return mojo;
}

From source file:com.photon.maven.plugins.android.AbstractAndroidMojoTestCase.java

License:Apache License

/**
 * Get the project directory used for this mojo.
 * //ww w .  j ava 2 s  . co m
 * @param mojo the mojo to query.
 * @return the project directory.
 * @throws IllegalAccessException if unable to get the project directory.
 */
public File getProjectDir(AbstractAndroidMojo mojo) throws IllegalAccessException {
    MavenProject project = (MavenProject) getVariableValueFromObject(mojo, "project");
    return project.getFile().getParentFile();
}

From source file:com.redhat.rcm.version.config.DefaultSessionConfigurator.java

License:Open Source License

private File[] loadBOMs(final List<String> boms, final VersionManagerSession session) {
    if (!session.hasDependencyMap()) {
        File[] bomFiles = null;//  w  w  w . j av a  2  s  .  c o m
        try {
            bomFiles = getFiles(boms, session.getDownloads());
        } catch (final VManException e) {
            session.addError(e);
        }

        List<MavenProject> projects = null;
        if (bomFiles != null) {
            try {
                projects = projectLoader.buildReactorProjectInstances(session, false, bomFiles);
            } catch (final ProjectToolsException e) {
                session.addError(new VManException("Error building BOM: %s", e, e.getMessage()));
            }
        }

        if (projects != null) {
            for (final MavenProject project : projects) {
                final File bom = project.getFile();

                logger.info("Adding BOM to session: " + bom + "; " + project);
                try {
                    session.addBOM(bom, project);
                } catch (final VManException e) {
                    session.addError(e);
                }
            }
        }

        return bomFiles;
    }

    return null;
}

From source file:com.stratio.mojo.scala.crossbuild.ChangeVersionMojoHelper.java

License:Apache License

public static void changeProjects(final List<MavenProject> projects, final String scalaBinaryVersionProperty,
        final String scalaVersionProperty, final String scalaBinaryVersion, final String scalaVersion,
        final Log log) throws MojoExecutionException {
    final RewritePom rewritePom = new RewritePom();
    for (final MavenProject subproject : projects) {
        log.debug("Rewriting " + subproject.getFile());
        try {//  w ww.  ja  v  a 2s .com
            rewritePom.rewrite(subproject, scalaBinaryVersionProperty, scalaVersionProperty, scalaBinaryVersion,
                    scalaVersion);
        } catch (final IOException | XMLStreamException ex) {
            restoreProjects(projects);
            throw new MojoExecutionException("Failed to rewrite POM", ex);
        }
    }
}

From source file:com.stratio.mojo.scala.crossbuild.RewritePom.java

License:Apache License

public void rewrite(final MavenProject pom, final String scalaBinaryVersionProperty,
        final String scalaVersionProperty, final String newBinaryVersion, final String newVersion)
        throws IOException, XMLStreamException {
    final List<RewriteRule> rewriteRules = Arrays.<RewriteRule>asList(
            new ArtifactIdRewriteRule(newBinaryVersion),
            new PropertyRewriteRule(scalaBinaryVersionProperty, newBinaryVersion),
            new PropertyRewriteRule(scalaVersionProperty, newVersion));
    final FileRewriter rewriter = new FileRewriter(rewriteRules);
    rewriter.rewrite(pom.getFile());
}