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:org.eclipse.m2e.wtp.ProjectUtils.java

License:Open Source License

/**
 * @return the <project>/<buildOutputDir>/m2e-wtp/ folder
 *//*from  w  w  w  .j a  v a2s  . c o  m*/
public static IPath getM2eclipseWtpFolder(MavenProject mavenProject, IProject project) {
    String buildOutputDir = mavenProject.getBuild().getDirectory();
    String relativeBuildOutputDir = getRelativePath(project, buildOutputDir);
    return new Path(relativeBuildOutputDir).append(MavenWtpConstants.M2E_WTP_FOLDER);
}

From source file:org.eclipse.m2e.wtp.WebProjectConfiguratorDelegate.java

License:Open Source License

public void configureClasspath(IProject project, MavenProject mavenProject, IClasspathDescriptor classpath,
        IProgressMonitor monitor) throws CoreException {

    //Improve skinny war support by generating the manifest classpath
    //similar to mvn eclipse:eclipse 
    //http://maven.apache.org/plugins/maven-war-plugin/examples/skinny-wars.html
    WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
    IPackagingConfiguration opts = new PackagingConfiguration(config.getPackagingIncludes(),
            config.getPackagingExcludes());
    /*/*from   w  ww .  j a  v a  2 s . c  o  m*/
     * Need to take care of three separate cases
     * 
     * 1. remove any project dependencies (they are represented as J2EE module dependencies)
     * 2. add non-dependency attribute for entries originated by artifacts with
     *    runtime, system, test scopes or optional dependencies (not sure about the last one)
     * 3. make sure all dependency JAR files have unique file names, i.e. artifactId/version collisions
     */

    Set<String> dups = new LinkedHashSet<String>();
    Set<String> names = new HashSet<String>();

    IVirtualComponent component = ComponentCore.createComponent(project);
    if (component != null) {
        for (IVirtualReference vr : component.getReferences()) {
            if (!vr.getReferencedComponent().isBinary()) {
                names.add(vr.getArchiveName());
            }
        }
    }

    FileNameMapping fileNameMapping = config.getFileNameMapping();
    String targetDir = mavenProject.getBuild().getDirectory();

    // first pass removes projects, adds non-dependency attribute and collects colliding filenames
    Iterator<IClasspathEntryDescriptor> iter = classpath.getEntryDescriptors().iterator();
    while (iter.hasNext()) {
        IClasspathEntryDescriptor descriptor = iter.next();
        String scope = descriptor.getScope();
        Artifact artifact = ArtifactHelper.getArtifact(mavenProject.getArtifacts(),
                descriptor.getArtifactKey());

        ArtifactHelper.fixArtifactHandler(artifact.getArtifactHandler());

        String deployedName = fileNameMapping.mapFileName(artifact);

        boolean isDeployed = (Artifact.SCOPE_COMPILE.equals(scope) || Artifact.SCOPE_RUNTIME.equals(scope))
                && !descriptor.isOptionalDependency() && opts.isPackaged("WEB-INF/lib/" + deployedName)
                && !isWorkspaceProject(artifact);

        // add non-dependency attribute if this classpathentry is not meant to be deployed
        // or if it's a workspace project (projects already have a reference created in configure())
        if (!isDeployed) {
            descriptor.setClasspathAttribute(NONDEPENDENCY_ATTRIBUTE.getName(),
                    NONDEPENDENCY_ATTRIBUTE.getValue());
            //Bug #382078 : no need to rename non-deployed artifacts.
            continue;
        }

        //If custom fileName is used, check if the underlying file already exists
        // if it doesn't, copy and rename the artifact under the build dir
        String fileName = descriptor.getPath().lastSegment();
        if (!deployedName.equals(fileName)) {
            IPath newPath = descriptor.getPath().removeLastSegments(1).append(deployedName);
            if (!new File(newPath.toOSString()).exists()) {
                newPath = renameArtifact(targetDir, descriptor.getPath(), deployedName);
            }
            if (newPath != null) {
                descriptor.setPath(newPath);
            }
        }

        if (!names.add(deployedName)) {
            dups.add(deployedName);
        }
    }

    // second pass disambiguates colliding entry file names
    iter = classpath.getEntryDescriptors().iterator();
    while (iter.hasNext()) {
        IClasspathEntryDescriptor descriptor = iter.next();
        if (descriptor.getClasspathAttributes().containsKey(NONDEPENDENCY_ATTRIBUTE.getName())) {
            //No need to rename if not deployed
            continue;
        }
        if (dups.contains(descriptor.getPath().lastSegment())) {
            String newName = descriptor.getGroupId() + "-" + descriptor.getPath().lastSegment();
            IPath newPath = renameArtifact(targetDir, descriptor.getPath(), newName);
            if (newPath != null) {
                descriptor.setPath(newPath);
            }
        }
    }
}

From source file:org.eclipse.m2e.wtp.WTPProjectsUtil.java

License:Open Source License

public static void removeTestFolderLinks(IProject project, MavenProject mavenProject, IProgressMonitor monitor,
        String folder) throws CoreException {
    IVirtualComponent component = ComponentCore.createComponent(project);
    if (component == null) {
        return;/*from  w w w. j a v a 2s.c o m*/
    }
    IVirtualFolder jsrc = component.getRootFolder().getFolder(folder);
    for (IPath location : MavenProjectUtils.getSourceLocations(project,
            mavenProject.getTestCompileSourceRoots())) {
        if (location == null)
            continue;
        jsrc.removeLink(location, 0, monitor);
    }
    for (IPath location : MavenProjectUtils.getResourceLocations(project, mavenProject.getTestResources())) {
        if (location == null)
            continue;
        jsrc.removeLink(location, 0, monitor);
    }

    //MECLIPSEWTP-217 : exclude other test source folders, added by build-helper for instance
    if (project.hasNature(JavaCore.NATURE_ID)) {
        IJavaProject javaProject = JavaCore.create(project);
        if (javaProject == null) {
            return;
        }
        IPath testOutputDirPath = MavenProjectUtils.getProjectRelativePath(project,
                mavenProject.getBuild().getTestOutputDirectory());
        if (testOutputDirPath == null) {
            return;
        }
        IPath testPath = project.getFullPath().append(testOutputDirPath);
        IClasspathEntry[] cpes = javaProject.getRawClasspath();
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        for (IClasspathEntry cpe : cpes) {
            if (cpe != null && cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath outputLocation = cpe.getOutputLocation();
                if (testPath.equals(outputLocation)) {
                    IPath sourcePath = root.getFolder(cpe.getPath()).getProjectRelativePath();
                    if (sourcePath != null) {
                        jsrc.removeLink(sourcePath, 0, monitor);
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.tycho.extras.sourcefeature.SourceFeatureMojo.java

License:Open Source License

static File getSourcesFeatureDir(MavenProject project) {
    File dir = new File(project.getBuild().getDirectory(), SOURCES_FEATURE_CLASSIFIER);
    dir.mkdirs();/*from  ww  w .j  a  va2 s  . c o m*/
    new File(dir, "p2.inf").delete();
    return dir;
}

From source file:org.eclipse.tycho.extras.sourcefeature.SourceFeatureMojo.java

License:Open Source License

private Feature getSourceFeature(MavenProject project, TargetPlatform targetPlatform)
        throws IOException, MojoExecutionException {
    P2ResolverFactory factory = equinox.getService(P2ResolverFactory.class);
    P2Resolver p2 = factory/*w ww .  java  2s . co  m*/
            .createResolver(new MavenLoggerAdapter(logger, DebugUtils.isDebugEnabled(session, project)));

    Feature feature = Feature.read(new File(project.getBuild().getDirectory(), "feature.xml"));

    Document document = new Document();
    document.setRootNode(new Element("feature"));
    document.setXmlDeclaration(new XMLDeclaration("1.0", "UTF-8"));
    Feature sourceFeature = new Feature(document);
    sourceFeature.setId(feature.getId() + ".source");
    sourceFeature.setVersion(feature.getVersion());

    // make sure versions of sources and binary features match
    FeatureRef binaryRef = new FeatureRef(new Element("includes"));
    binaryRef.setId(feature.getId());
    binaryRef.setVersion(feature.getVersion());
    sourceFeature.addFeatureRef(binaryRef);

    List<PluginRef> missingSourcePlugins = new ArrayList<PluginRef>();
    List<FeatureRef> missingSourceFeatures = new ArrayList<FeatureRef>();

    // include available source bundles
    for (PluginRef pluginRef : feature.getPlugins()) {

        if (excludedPlugins.contains(pluginRef.getId())) {
            continue;
        }

        // version is expected to be fully expanded at this point
        P2ResolutionResult result = p2.resolveInstallableUnit(targetPlatform, pluginRef.getId() + ".source",
                pluginRef.getVersion());
        if (result.getArtifacts().size() == 1) {
            Entry sourceBundle = result.getArtifacts().iterator().next();

            PluginRef sourceRef = new PluginRef("plugin");
            sourceRef.setId(sourceBundle.getId());
            sourceRef.setVersion(sourceBundle.getVersion());
            sourceRef.setDownloadSide(0);
            sourceRef.setInstallSize(0);
            if (pluginRef.getOs() != null) {
                sourceRef.setOs(pluginRef.getOs());
            }
            if (pluginRef.getWs() != null) {
                sourceRef.setWs(pluginRef.getWs());
            }
            if (pluginRef.getArch() != null) {
                sourceRef.setArch(pluginRef.getArch());
            }
            sourceRef.setUnpack(false);

            sourceFeature.addPlugin(sourceRef);
        } else {
            missingSourcePlugins.add(pluginRef);
        }
    }

    // include available source features
    for (FeatureRef featureRef : feature.getIncludedFeatures()) {

        if (excludedFeatures.contains(featureRef.getId())) {
            continue;
        }

        String sourceId = featureRef.getId() + ".source";

        P2ResolutionResult result = p2.resolveInstallableUnit(targetPlatform, sourceId + ".feature.group",
                featureRef.getVersion());
        if (result.getArtifacts().size() == 1) {
            Entry entry = result.getArtifacts().iterator().next();

            FeatureRef sourceRef = new FeatureRef(new Element("includes"));
            sourceRef.setId(sourceId);
            sourceRef.setVersion(entry.getVersion());
            sourceFeature.addFeatureRef(sourceRef);
        } else {
            missingSourceFeatures.add(featureRef);
        }
    }

    if (!missingSourceFeatures.isEmpty() || !missingSourcePlugins.isEmpty()) {
        StringBuilder sb = new StringBuilder();

        sb.append("Could not generate source feature for project " + project.toString()).append("\n");

        if (!missingSourcePlugins.isEmpty()) {
            sb.append("    Missing sources for plugins " + missingSourcePlugins.toString()).append("\n");
        }

        if (!missingSourceFeatures.isEmpty()) {
            sb.append("    Missing sources for features " + missingSourceFeatures.toString()).append("\n");
        }

        throw new MojoExecutionException(sb.toString());
    }

    return sourceFeature;
}

From source file:org.eclipse.tycho.osgi.adapters.MavenReactorProjectCoordinates.java

License:Open Source License

public MavenReactorProjectCoordinates(MavenProject project) {
    this.project = project;
    this.targetFolder = new BuildOutputDirectory(project.getBuild().getDirectory());
}

From source file:org.eclipse.tycho.osgi.adapters.MavenReactorProjectIdentities.java

License:Open Source License

public MavenReactorProjectIdentities(MavenProject project) {
    this.project = project;
    this.targetFolder = new BuildOutputDirectory(project.getBuild().getDirectory());
}

From source file:org.eclipse.tycho.p2.facade.RepositoryReferenceTool.java

License:Open Source License

/**
 * Returns the list of visible p2 repositories for the build of the current module. The list
 * includes the p2 repositories of the referenced reactor modules, the target platform, and
 * optionally the current module itself. The repositories are sorted in a reasonable order of
 * precedence, so if there should be duplicate installable units or artifacts, the hope is that
 * it is deterministic from which repository the unit or artifact is taken. The order is:
 * <ol>/* w w  w. j av  a 2s.co  m*/
 * <li>The publisher results of the current module (only if the flag
 * {@link #REPOSITORIES_INCLUDE_CURRENT_MODULE} is set),
 * <li>The results of the referenced reactor modules,
 * <li>The non-reactor content of the module's target platform.
 * </ol>
 * 
 * @param module
 *            The current Maven project
 * @param session
 *            The current Maven session
 * @param flags
 *            Options flags; supported flags are {@link #REPOSITORIES_INCLUDE_CURRENT_MODULE}
 * @return a {@link RepositoryReferences} instance with the repositories.
 * @throws MojoExecutionException
 *             in case of internal errors
 * @throws MojoFailureException
 *             in case required artifacts are missing
 */
public RepositoryReferences getVisibleRepositories(MavenProject module, MavenSession session, int flags)
        throws MojoExecutionException, MojoFailureException {
    RepositoryReferences repositories = new RepositoryReferences();

    if ((flags & REPOSITORIES_INCLUDE_CURRENT_MODULE) != 0) {
        File publisherResults = new File(module.getBuild().getDirectory(), PUBLISHER_REPOSITORY_PATH);
        repositories.addMetadataRepository(publisherResults);
        repositories.addArtifactRepository(publisherResults);
    }

    repositories
            .addArtifactRepository(RepositoryBlackboardKey.forResolutionContextArtifacts(module.getBasedir()));

    // metadata and artifacts of target platform
    addTargetPlatformRepository(repositories, session, module);
    repositories.addArtifactRepository(new File(session.getLocalRepository().getBasedir()));
    return repositories;
}

From source file:org.eclipse.tycho.p2.facade.RepositoryReferenceTool.java

License:Open Source License

/**
 * Restores the p2 metadata view on the module's build target platform that was calculated
 * during the initial dependency resolution (see
 * org.eclipse.tycho.p2.resolver.P2ResolverImpl.toResolutionResult(...)).
 *///from ww w  .  j  a  va2 s .c o m
private void addTargetPlatformRepository(RepositoryReferences sources, MavenSession session,
        MavenProject project) throws MojoExecutionException, MojoFailureException {
    try {
        File repositoryLocation = new File(project.getBuild().getDirectory(), "targetPlatformRepository");
        repositoryLocation.mkdirs();
        FileOutputStream stream = new FileOutputStream(new File(repositoryLocation, "content.xml"));
        try {
            MetadataSerializable serializer = osgiServices.getService(MetadataSerializable.class);

            TargetPlatform targetPlatform = TychoProjectUtils.getTargetPlatform(project);

            TargetPlatformResolver resolver = targetPlatformResolverLocator.lookupPlatformResolver(project);

            TargetPlatformConfiguration configuration = TychoProjectUtils
                    .getTargetPlatformConfiguration(project);

            DependencyResolverConfiguration resolverConfiguration = configuration
                    .getDependencyResolverConfiguration();

            DependencyArtifacts dependencyArtifacts = resolver.resolveDependencies(session, project,
                    targetPlatform, DefaultReactorProject.adapt(session), resolverConfiguration);

            // this contains dependency-only metadata for 'this' project
            Set<Object> targetPlatformInstallableUnits = new HashSet<Object>(
                    dependencyArtifacts.getInstallableUnits());

            for (ArtifactDescriptor artifact : dependencyArtifacts.getArtifacts()) {
                ReactorProject otherProject = artifact.getMavenProject();
                if (otherProject == null) {
                    continue; // can't really happen
                }
                if (ArtifactKey.TYPE_ECLIPSE_PLUGIN.equals(otherProject.getPackaging())
                        || ArtifactKey.TYPE_ECLIPSE_TEST_PLUGIN.equals(otherProject.getPackaging())
                        || ArtifactKey.TYPE_ECLIPSE_FEATURE.equals(otherProject.getPackaging())) {
                    File artifactXml = otherProject.getArtifact(RepositoryLayoutHelper.CLASSIFIER_P2_ARTIFACTS);
                    if (artifactXml == null || !artifactXml.isFile()) {
                        throw new MojoFailureException(
                                "Missing required file \"" + RepositoryLayoutHelper.FILE_NAME_LOCAL_ARTIFACTS
                                        + "\" in target folder of module " + otherProject.getId());
                    }
                    sources.addArtifactRepository(artifactXml.getParentFile());
                }
            }

            serializer.serialize(stream, targetPlatformInstallableUnits);
        } finally {
            stream.close();
        }
        sources.addMetadataRepository(repositoryLocation);
    } catch (IOException e) {
        throw new MojoExecutionException("I/O exception while writing the build target platform to disk", e);
    }
}

From source file:org.eclipse.tycho.plugins.p2.BaselineValidator.java

License:Open Source License

public Map<String, IP2Artifact> validateAndReplace(MavenProject project,
        Map<String, IP2Artifact> reactorMetadata, List<Repository> baselineRepositories,
        BaselineMode baselineMode, BaselineReplace baselineReplace) throws IOException, MojoExecutionException {

    Map<String, IP2Artifact> result = reactorMetadata;

    if (baselineMode != disable && baselineRepositories != null && !baselineRepositories.isEmpty()) {
        List<MavenRepositoryLocation> _repositories = new ArrayList<MavenRepositoryLocation>();
        for (Repository repository : baselineRepositories) {
            if (repository.getUrl() != null) {
                _repositories.add(new MavenRepositoryLocation(repository.getId(), repository.getUrl()));
            }//from   ww w  .  j  a  v a  2  s. c  om
        }

        File baselineBasedir = new File(project.getBuild().getDirectory(), "baseline");

        BaselineService baselineService = getService(BaselineService.class);

        Map<String, IP2Artifact> baselineMetadata = baselineService.getProjectBaseline(_repositories,
                reactorMetadata, baselineBasedir);

        if (baselineMetadata != null) {
            CompoundArtifactDelta delta = getDelta(baselineService, baselineMetadata, reactorMetadata);
            if (delta != null) {
                if (System.getProperties().containsKey("tycho.debug.artifactcomparator")) {
                    File logdir = new File(project.getBuild().getDirectory(), "artifactcomparison");
                    log.info("Artifact comparison detailed log directory " + logdir.getAbsolutePath());
                    for (Map.Entry<String, ArtifactDelta> classifier : delta.getMembers().entrySet()) {
                        if (classifier.getValue() instanceof CompoundArtifactDelta) {
                            ((CompoundArtifactDelta) classifier.getValue())
                                    .writeDetails(new File(logdir, classifier.getKey()));
                        }
                    }
                }
                if (baselineMode == fail || (baselineMode == failCommon && !isMissingOnlyDelta(delta))) {
                    throw new MojoExecutionException(delta.getDetailedMessage());
                } else {
                    String message = log.isDebugEnabled() ? delta.getDetailedMessage() : delta.getMessage();
                    log.warn(project.toString() + ": " + message);
                }
            }

            if (baselineReplace != none) {
                result = new LinkedHashMap<String, IP2Artifact>();

                // replace reactor artifacts with baseline
                ArrayList<String> replaced = new ArrayList<String>();
                for (Map.Entry<String, IP2Artifact> artifact : baselineMetadata.entrySet()) {
                    String classifier = artifact.getKey();
                    FileUtils.copyFile(artifact.getValue().getLocation(),
                            reactorMetadata.get(classifier).getLocation());
                    result.put(classifier, artifact.getValue());
                    if (classifier != null) {
                        replaced.add(classifier);
                    }
                }

                // un-attach and delete artifacts present in reactor but not in baseline
                ArrayList<String> removed = new ArrayList<String>();
                ArrayList<String> inconsistent = new ArrayList<String>();
                for (Map.Entry<String, IP2Artifact> entry : reactorMetadata.entrySet()) {
                    String classifier = entry.getKey();
                    IP2Artifact artifact = entry.getValue();
                    if (classifier == null || artifact == null) {
                        continue;
                    }
                    if (baselineReplace == all && !baselineMetadata.containsKey(classifier)) {
                        List<Artifact> attachedArtifacts = project.getAttachedArtifacts();
                        ListIterator<Artifact> iterator = attachedArtifacts.listIterator();
                        while (iterator.hasNext()) {
                            if (classifier.equals(iterator.next().getClassifier())) {
                                iterator.remove();
                                break;
                            }
                        }
                        artifact.getLocation().delete();
                        removed.add(classifier);
                    } else {
                        inconsistent.add(classifier);
                        result.put(classifier, artifact);
                    }
                }

                // Reactor build can have more or less artifacts than baseline 
                // baselineReplace==all guarantees consistency of build artifacts with baseline repository
                // baselineReplace==none build results are self-consistent, but maybe inconsistent with baseline
                // baselineReplace==common build artifacts are inconsistent

                if (log.isInfoEnabled()) {
                    StringBuilder msg = new StringBuilder();
                    msg.append(project.toString());
                    msg.append("\n    The main artifact has been replaced with the baseline version.\n");
                    if (!replaced.isEmpty()) {
                        msg.append(
                                "    The following attached artifacts have been replaced with the baseline version: ");
                        msg.append(replaced.toString());
                        msg.append("\n");
                    }
                    if (!removed.isEmpty()) {
                        msg.append(
                                "    The following attached artifacts are not present in the baseline and have been removed: ");
                        msg.append(removed.toString());
                        msg.append("\n");
                    }
                    log.info(msg.toString());
                }
            }
        } else {
            log.info("No baseline version " + project);
        }
    }
    return result;
}