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

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

Introduction

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

Prototype

public Build getBuild() 

Source Link

Usage

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

License:Apache License

protected void doExecute() throws Exception {
    // prepare/*w ww  . j  a  va  2  s .c  om*/
    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.goodformobile.build.mobile.RIMPackageMojo.java

License:Apache License

private File copyIcon(String icon, MavenProject project, File basedir) throws IOException {
    if (icon != null) {
        File file = new File(project.getBuild().getOutputDirectory() + File.separator + icon);
        if (file.exists()) {
            File copiedIconFile = new File(basedir.getAbsoluteFile() + File.separator + icon);
            FileUtils.copyFile(file, copiedIconFile);
            return copiedIconFile;
        }/*from w  w w .  j  a  v a  2 s . c om*/
    }
    return null;
}

From source file:com.google.code.play2.plugin.AbstractPlay2EnhanceMojo.java

License:Apache License

private File defaultAnalysisCacheFile(MavenProject p) {
    File classesDirectory = new File(p.getBuild().getOutputDirectory());
    return new File(Compilers.getCacheDirectory(classesDirectory), "compile");
}

From source file:com.google.code.play2.plugin.MavenPlay2Builder.java

License:Apache License

@Override /* Play2Builder */
public boolean build() throws Play2BuildFailure, Play2BuildError/*Play2BuildException*/
{
    Set<String> changedFilePaths = null;
    Map<String, Long> prevChangedFiles = new HashMap<String, Long>();
    synchronized (changedFilesLock) {
        if (!changedFiles.isEmpty()) {
            changedFilePaths = changedFiles.keySet();
            prevChangedFiles = changedFiles;
            changedFiles = new HashMap<String, Long>();
        }//w  w  w.jav  a  2  s. c om
        //TEST - more code inside synchronized block
    }

    if (!forceReloadNextTime && changedFilePaths == null /*&& afterFirstSuccessfulBuild*/ ) {
        return false;
    }

    List<MavenProject> projectsToBuild = projects;
    // - !afterFirstSuccessfulBuild => first build or no previous successful builds, build all modules
    // - currentSourceMaps.isEmpty() => first build, build all modules
    // - projects.size() == 1 => one-module project, just build it
    // - else => not the first build in multimodule-project, calculate modules subset to build
    if (afterFirstSuccessfulBuild
            /*!currentSourceMaps.isEmpty()*//*currentSourceMap != null*/ && projects.size() > 1) {
        projectsToBuild = calculateProjectsToBuild(changedFilePaths);
    }

    MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(session.getRequest());
    request.setStartTime(new Date());
    request.setExecutionListener(new ExecutionEventLogger());
    request.setGoals(goals);

    MavenExecutionResult result = new DefaultMavenExecutionResult();

    MavenSession newSession = new MavenSession(container, session.getRepositorySession(), request, result);
    newSession.setProjects(projectsToBuild);
    newSession.setCurrentProject(session.getCurrentProject());
    newSession.setParallel(session.isParallel());
    newSession.setProjectDependencyGraph(session.getProjectDependencyGraph());

    lifecycleExecutor.execute(newSession);

    forceReloadNextTime = result.hasExceptions();

    if (!result.hasExceptions() && !additionalGoals.isEmpty()) {
        request = DefaultMavenExecutionRequest.copy(session.getRequest());
        request.setStartTime(new Date());
        request.setExecutionListener(new ExecutionEventLogger());
        request.setGoals(additionalGoals);

        result = new DefaultMavenExecutionResult();

        newSession = new MavenSession(container, session.getRepositorySession(), request, result);
        List<MavenProject> onlyMe = Arrays.asList(new MavenProject[] { session.getCurrentProject() });
        newSession.setProjects(onlyMe);
        newSession.setCurrentProject(session.getCurrentProject());
        newSession.setParallel(session.isParallel());
        newSession.setProjectDependencyGraph(session.getProjectDependencyGraph());

        lifecycleExecutor.execute(newSession);

        forceReloadNextTime = result.hasExceptions();
    }

    if (result.hasExceptions()) {
        synchronized (changedFilesLock) {
            changedFiles.putAll(prevChangedFiles); // restore previously changed paths, required for next rebuild
        }
        Throwable firstException = result.getExceptions().get(0);
        if (firstException.getCause() instanceof MojoFailureException) {
            MojoFailureException mfe = (MojoFailureException) firstException.getCause();
            Throwable mfeCause = mfe.getCause();
            if (mfeCause != null) {
                try {
                    Play2BuildException pbe = null;
                    String causeName = mfeCause.getClass().getName();

                    // sbt-compiler exception
                    if (CompilerException.class.getName().equals(causeName)) {
                        pbe = getSBTCompilerBuildException(mfeCause);
                    } else if (AssetCompilationException.class.getName().equals(causeName)
                            || RoutesCompilationException.class.getName().equals(causeName)
                            || TemplateCompilationException.class.getName().equals(causeName)) {
                        pbe = getPlayBuildException(mfeCause);
                    }

                    if (pbe != null) {
                        throw new Play2BuildFailure(pbe, sourceEncoding);
                    }
                    throw new Play2BuildError("Build failed without reporting any problem!"/*?, ce*/ );
                } catch (Play2BuildFailure e) {
                    throw e;
                } catch (Play2BuildError e) {
                    throw e;
                } catch (Exception e) {
                    throw new Play2BuildError(".... , check Maven console");
                }
            }
        }
        throw new Play2BuildError("The compilation task failed, check Maven console"/*?, firstException*/ );
    }

    // no exceptions
    if (!afterFirstSuccessfulBuild) // this was first successful build
    {
        afterFirstSuccessfulBuild = true;

        if (playWatchService != null) {
            // Monitor all existing, not generated (inside output directory) source and resource roots
            List<File> monitoredDirectories = new ArrayList<File>();
            for (MavenProject p : projects) {
                String targetDirectory = p.getBuild().getDirectory();
                for (String sourceRoot : p.getCompileSourceRoots()) {
                    if (!sourceRoot.startsWith(targetDirectory) && new File(sourceRoot).isDirectory()) {
                        monitoredDirectories.add(new File(sourceRoot));
                    }
                }
                for (Resource resource : p.getResources()) {
                    String resourceRoot = resource.getDirectory();
                    if (!resourceRoot.startsWith(targetDirectory) && new File(resourceRoot).isDirectory()) {
                        monitoredDirectories.add(new File(resourceRoot));
                    }
                }
            }
            //TODO - remove roots nested inside another roots (is it possible?)

            try {
                watcher = playWatchService.watch(monitoredDirectories, this);
            } catch (FileWatchException e) {
                logger.warn("File watcher initialization failed. Running without hot-reload functionality.", e);
            }
        }
    }

    Map<MavenProject, Map<String, File>> sourceMaps = new HashMap<MavenProject, Map<String, File>>(
            currentSourceMaps);
    for (MavenProject p : projectsToBuild) {
        Map<String, File> sourceMap = new HashMap<String, File>();
        File classesDirectory = new File(p.getBuild().getOutputDirectory());
        String classesDirectoryPath = classesDirectory.getAbsolutePath() + File.separator;
        File analysisCacheFile = defaultAnalysisCacheFile(p);
        Analysis analysis = sbtAnalysisProcessor.readFromFile(analysisCacheFile);
        for (File sourceFile : analysis.getSourceFiles()) {
            Set<File> sourceFileProducts = analysis.getProducts(sourceFile);
            for (File product : sourceFileProducts) {
                String absolutePath = product.getAbsolutePath();
                if (absolutePath.contains("$")) {
                    continue; // skip inner and object classes
                }
                String relativePath = absolutePath.substring(classesDirectoryPath.length());
                //                    String name = product.getName();
                String name = relativePath.substring(0, relativePath.length() - ".class".length());
                /*if (name.indexOf( '$' ) > 0)
                {
                name = name.substring( 0, name.indexOf( '$' ) );
                }*/
                name = name.replace(File.separator, ".");
                //System.out.println(sourceFile.getPath() + " -> " + name);
                sourceMap.put(name, sourceFile);
            }
            /*String[] definitionNames = analysis.getDefinitionNames( sourceFile );
            Set<String> uniqueDefinitionNames = new HashSet<String>(definitionNames.length);
            for (String definitionName: definitionNames)
            {
            if ( !uniqueDefinitionNames.contains( definitionName ) )
            {
                result.put( definitionName, sourceFile );
            //                        System.out.println( "definitionName:'" + definitionName + "', source:'"
            //                                        + sourceFile.getAbsolutePath() + "'" );
                uniqueDefinitionNames.add( definitionName );
            }
            }*/
        }
        sourceMaps.put(p, sourceMap);
    }
    this.currentSourceMaps = sourceMaps;

    boolean reloadRequired = false;
    for (MavenProject p : projectsToBuild) {
        long lastModifiedTime = 0L;
        Set<String> outputFilePaths = new HashSet<String>();
        File outputDirectory = new File(p.getBuild().getOutputDirectory());
        if (outputDirectory.exists() && outputDirectory.isDirectory()) {
            DirectoryScanner classPathScanner = new DirectoryScanner();
            classPathScanner.setBasedir(outputDirectory);
            classPathScanner.setExcludes(new String[] { assetsPrefix + "**" });
            classPathScanner.scan();
            String[] files = classPathScanner.getIncludedFiles();
            for (String fileName : files) {
                File f = new File(outputDirectory, fileName);
                outputFilePaths.add(f.getAbsolutePath());
                long lmf = f.lastModified();
                if (lmf > lastModifiedTime) {
                    lastModifiedTime = lmf;
                }
            }
        }
        if (!reloadRequired && (lastModifiedTime > currentClasspathTimestamps.get(p).longValue()
                || !outputFilePaths.equals(currentClasspathFilePaths.get(p)))) {
            reloadRequired = true;
        }
        currentClasspathTimestamps.put(p, Long.valueOf(lastModifiedTime));
        currentClasspathFilePaths.put(p, outputFilePaths);
    }

    return reloadRequired;
}

From source file:com.google.code.sbt.compiler.plugin.AbstractSBTCompileMojo.java

License:Apache License

/**
 * Returns SBT incremental main compilation analysis cache file location for a project.
 * /* w ww  .  j  a  v a 2 s. c o  m*/
 * @param p Maven project
 * @return analysis cache file location
 */
protected File defaultAnalysisCacheFile(MavenProject p) {
    File classesDirectory = new File(p.getBuild().getOutputDirectory());
    return new File(Compilers.getCacheDirectory(classesDirectory), "compile");
}

From source file:com.google.code.sbt.compiler.plugin.AbstractSBTCompileMojo.java

License:Apache License

/**
 * Returns SBT incremental test compilation analysis cache file location for a project.
 * /* ww  w. ja  v  a 2 s.com*/
 * @param p Maven project
 * @return analysis cache file location
 */
protected File defaultTestAnalysisCacheFile(MavenProject p) {
    File testClassesDirectory = new File(p.getBuild().getTestOutputDirectory());
    return new File(Compilers.getCacheDirectory(testClassesDirectory), "test-compile");
}

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;//w  ww  .j ava2s  . co m
    while (parent != null && parent.getFile() != null) {
        final File dir = parent.getFile().getParentFile();
        inputLocator.addSearchPath(FileResourceLoader.ID, dir.getAbsolutePath());
        parent = parent.getParent();
    }
    inputLocator.addSearchPath("url", "");
}

From source file:com.infosupport.ellison.sonarplugin.ELCheckerSensor.java

License:Open Source License

/**
 * Look for the project's artifact./*from w  ww .  ja v a  2s.  c  o  m*/
 * This method has been taken from the Sonar <a href="http://docs.codehaus.org/display/SONAR/Artifact+Size+Plugin">
 * artifact-size-plugin</a>, whose author are Olivier Gaudin and Waleri Enns.
 * License: LGPL v3
 *
 * @param pom
 *     the object representing the project's maven configuration
 * @param fileSystem
 *     the filesystem of the project that is being checked
 *
 * @return a file pointing to the artifact path set in the settings (see
 *         {@link ELCheckerSensor#ELCheckerSensor(org.apache.maven.project.MavenProject,
 *         org.sonar.api.config.Settings, ELApplicationCheckerSonarBatchComponent)}
 *         if that has been set, otherwise the artifact as defined by the maven packaging.
 */
protected File searchArtifactFile(MavenProject pom, ProjectFileSystem fileSystem) {
    File file = null;

    if (StringUtils.isNotEmpty(savedArtifactPath)) {
        file = buildPathFromConfig(fileSystem, savedArtifactPath);
    } else if (pom != null && pom.getBuild() != null) {
        String filename = pom.getBuild().getFinalName() + "." + pom.getPackaging();
        file = buildPathFromPom(fileSystem, filename);
    }
    return file;
}

From source file:com.liferay.ide.maven.core.FacetedMavenBundleProject.java

License:Open Source License

@Override
public IPath getOutputBundle(boolean cleanBuild, IProgressMonitor monitor) throws CoreException {
    IPath outputJar = null;//from  w  w  w.j ava  2 s .  c om

    final MavenProjectBuilder mavenProjectBuilder = new MavenProjectBuilder(this.getProject());

    final List<String> goals = new ArrayList<>();

    if (cleanBuild) {
        goals.add("clean");
    }

    goals.add("package");

    for (String goal : goals) {
        mavenProjectBuilder.runMavenGoal(this.getProject(), goal, monitor);
    }

    // we are going to try to get the output jar even if the package failed.
    final IMavenProjectFacade projectFacade = MavenUtil.getProjectFacade(getProject(), monitor);
    final MavenProject mavenProject = projectFacade.getMavenProject(monitor);

    final String targetName = mavenProject.getBuild().getFinalName() + ".war";

    final IFolder targetFolder = getProject().getFolder("target");

    if (targetFolder.exists()) {
        //targetFolder.refreshLocal( IResource.DEPTH_ONE, monitor );
        final IPath targetFile = targetFolder.getRawLocation().append(targetName);

        if (targetFile.toFile().exists()) {
            outputJar = targetFile;
        }
    }

    if (outputJar == null || !outputJar.toFile().exists()) {
        throw new CoreException(LiferayMavenCore
                .createErrorStatus("Unable to get output bundle for project " + getProject().getName()));
    }

    return outputJar;
}

From source file:com.liferay.ide.maven.core.FacetedMavenProject.java

License:Open Source License

public Collection<IFile> getOutputs(boolean buildIfNeeded, IProgressMonitor monitor) throws CoreException {
    final Collection<IFile> outputs = new HashSet<IFile>();

    if (buildIfNeeded) {
        this.getProject().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);

        new MavenProjectBuilder(this.getProject()).runMavenGoal(getProject(), "package", monitor);

        final IMavenProjectFacade projectFacade = MavenUtil.getProjectFacade(getProject(), monitor);
        final MavenProject mavenProject = projectFacade.getMavenProject(monitor);
        final String targetFolder = mavenProject.getBuild().getDirectory();
        final String targetWar = mavenProject.getBuild().getFinalName() + "." + mavenProject.getPackaging();

        final IFile output = getProject().getFile(new Path(targetFolder).append(targetWar));

        if (output.exists()) {
            outputs.add(output);/*from w  w w. j a  v  a  2  s  . com*/
        }
    }

    return outputs;
}