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

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

Introduction

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

Prototype

public String getId() 

Source Link

Usage

From source file:net.java.jpatch.maven.common.AbstractPatchMojo.java

License:Apache License

/**
 * Check the SCM status of the project./*from   w  w  w . ja  v a 2 s  . com*/
 *
 * @param project the MAVEN project.
 * @param begin the SCM ID.
 * @param end the SCM ID.
 *
 * @return
 *
 * @throws MojoExecutionException if the method fails.
 */
private boolean checkSCM(MavenProject project, String revision, File diffDirectory)
        throws MojoExecutionException {

    getLog().info("Check SCM for the project " + project.getId());

    boolean result = false;
    boolean ignoreUnknown = true;

    DiffScmResult scmResult = null;
    try {
        ScmRepository repository = scmManager.makeScmRepository(project.getScm().getConnection());
        scmResult = scmManager.diff(repository, new ScmFileSet(project.getBasedir()), new ScmRevision(revision),
                null);
    } catch (Exception e) {
        getLog().error("Error check SCM status for project " + project.getId());
        throw new MojoExecutionException("Couldn't configure SCM repository: " + e.getLocalizedMessage(), e);
    }

    if (scmResult != null && scmResult.getChangedFiles() != null) {
        List<ScmFile> changedFiles = scmResult.getChangedFiles();
        for (ScmFile changedScmFile : changedFiles) {
            ScmFileStatus status = changedScmFile.getStatus();
            if (!status.isStatus()) {
                getLog().debug("Not a diff: " + status);
                continue;
            }
            if (ignoreUnknown && ScmFileStatus.UNKNOWN.equals(status)) {
                getLog().debug("Ignoring unknown");
                continue;
            }

            getLog().info(changedScmFile.getStatus().toString() + " " + changedScmFile.getPath());
            result = true;
        }

        if (result) {
            File diffFile = new File(diffDirectory, project.getArtifactId() + project.getVersion() + ".diff");
            try {
                getLog().info("Create new diff file: " + diffFile.getAbsolutePath());
                diffFile.createNewFile();
                FileUtils.fileWrite(diffFile.getAbsolutePath(), scmResult.getPatch());
            } catch (IOException ex) {
                Logger.getLogger(AbstractPatchMojo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    getLog().info("");
    return result;
}

From source file:net.java.jpatch.maven.ReleaseInfoMojo.java

License:Apache License

/**
 * Show information about the release package.
 * /*from  w  w  w  .  ja  v a 2  s  .co  m*/
 * @throws MojoExecutionException if the method fails.
 * @throws MojoFailureException if the method fails.
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    // Setup the release artifact and open release properties file
    Properties releaseProperties = setupReleaseArtifact();

    // Creates temporary keys set.
    Set<Object> keys = new HashSet<Object>(releaseProperties.keySet());

    // Write information to the console
    getLog().info("Create:\t" + releaseProperties.getProperty(RELEASE_PROPERTY_DATE));
    keys.remove(RELEASE_PROPERTY_DATE);

    getLog().info("User:\t" + releaseProperties.getProperty(RELEASE_PROPERTY_USER_NAME));
    keys.remove(RELEASE_PROPERTY_USER_NAME);

    getLog().info("Java:\t" + releaseProperties.getProperty(RELEASE_PROPERTY_JAVA_VERSION));
    keys.remove(RELEASE_PROPERTY_JAVA_VERSION);

    getLog().info("Os:\t" + releaseProperties.getProperty(RELEASE_PROPERTY_OS_NAME));
    keys.remove(RELEASE_PROPERTY_OS_NAME);

    getLog().info("Projects");

    // Load projects
    List<MavenProject> mavenProjects = loadMavenProjects();

    // Filter the projects
    List<MavenProject> filterProjects = filterMavenProjects(mavenProjects, getPackages());

    // Show the list of projects
    for (MavenProject project : filterProjects) {
        keys.remove(project.getId());
        String revision = releaseProperties.getProperty(project.getId(), null);
        if (revision == null) {
            getLog().warn("Missing revision number for the project " + project.getId());
        } else {
            getLog().info(project.getId() + " r:" + revision);
        }
    }

    // Show list of missing keys.
    if (!keys.isEmpty()) {
        getLog().warn("To many keys in the release properties");
        for (Object key : keys) {
            getLog().warn(
                    "key:" + key + ",value:" + releaseProperties.getProperty(key.toString(), "").toString());
        }
    }
}

From source file:net.java.jpatch.maven.ReleaseMojo.java

License:Apache License

/**
 * Creates the release package.//from   www .j  a v  a 2 s .  com
 * 
 * @throws MojoExecutionException if the method fails.
 * @throws MojoFailureException if the method fails.
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    // Search for existing release
    Artifact releaseArtifact = resolveReleaseArtifact();
    File releaseFile = releaseArtifact.getFile();

    // Check existing release
    if (releaseFile != null && releaseFile.exists()) {
        getLog().info(releaseFile.getAbsolutePath());
        getLog().error("Release file already exist! For new release execute first jpatch:release-clean.");
        throw new MojoFailureException("Release package already exist!");
    }

    // Create release directory
    File directory = createTargetDirectory(releaseArtifact.getVersion());

    // Create release properties file.
    Properties releaseProperties = new Properties();

    // Load projects
    List<MavenProject> mavenProjects = loadMavenProjects();

    // Filter the projects
    List<MavenProject> filterProjects = filterMavenProjects(mavenProjects, getPackages());

    // Unpack the libraries in the output directory
    for (MavenProject project : filterProjects) {

        String revision = scmRevision(project);
        releaseProperties.setProperty(project.getId(), revision);

        Artifact artifact = project.getArtifact();
        resolveArtifactFromLocalRepository(artifact);
        unpackArtifactFile(directory, artifact.getFile());
    }

    // Setup the advanced properties to the release property
    SimpleDateFormat sdf = new SimpleDateFormat();
    releaseProperties.put(RELEASE_PROPERTY_DATE, sdf.format(new Date()));
    releaseProperties.put(RELEASE_PROPERTY_USER_NAME, SystemUtils.USER_NAME);
    releaseProperties.put(RELEASE_PROPERTY_JAVA_VERSION, SystemUtils.JAVA_VERSION);
    releaseProperties.put(RELEASE_PROPERTY_OS_NAME, SystemUtils.OS_NAME);

    // Save release properties file
    try {
        File propFile = new File(mavenProject.getBuild().getDirectory(),
                mavenProject.getBuild().getFinalName() + ".properties");
        releaseProperties.store(new FileOutputStream(propFile), null);
    } catch (IOException e) {
        throw new MojoExecutionException("Error creating the release properties file!", e);
    }

    // Create package file
    String fileName = mavenProject.getBuild().getFinalName();
    File packFile = new File(mavenProject.getBuild().getDirectory(), fileName + ".zip");
    packDirectory(directory, packFile);

    // Attached the package to the project
    releaseArtifact.setFile(packFile);
    mavenProject.addAttachedArtifact(releaseArtifact);

    // Create build file (project.jpatch)
    createBuildFile();
}

From source file:net.java.jpatch.maven.ReleaseMojo.java

License:Apache License

/**
 * Gets the SCM status from the repository.
 * /*from ww w.  j  a va  2  s .c o m*/
 * @param project the MAVEN project.
 * 
 * @return the SCM status.
 * 
 * @throws MojoExecutionException if the method fails.
 * 
 * TODO: rewrite this method. Exception handling.
 */
private String scmRevision(MavenProject project) throws MojoExecutionException {
    String result = null;
    try {
        ScmRepository repository = scmManager.makeScmRepository(project.getScm().getConnection());
        ChangeLogScmResult scmResult = scmManager.changeLog(repository, new ScmFileSet(project.getBasedir()),
                null, null, null);
        if (scmResult != null) {
            ChangeLogSet log = scmResult.getChangeLog();
            if (log != null) {
                if (log.getChangeSets() != null) {
                    List<ChangeSet> changes = log.getChangeSets();
                    if (!changes.isEmpty()) {
                        ChangeSet change = changes.get(0);
                        if (!change.getFiles().isEmpty()) {
                            List<ChangeFile> files = change.getFiles();
                            ChangeFile file = files.get(0);
                            result = file.getRevision();
                        } else {
                            throw new MojoExecutionException("No revision found! Project: " + project.getId());
                        }
                    } else {
                        throw new MojoExecutionException(
                                "Missing changes in the repository! Project: " + project.getId());
                    }
                }
            } else {
                throw new MojoExecutionException("Missing the SCM log! Project: " + project.getId());
            }
        } else {
            throw new MojoExecutionException("Missing the SCM result! Project: " + project.getId());
        }
    } catch (Exception e) {
        getLog().error("Error check SCM status for project " + project.getId());
        throw new MojoExecutionException("Couldn't configure SCM repository: " + e.getLocalizedMessage(), e);
    }
    return result;
}

From source file:org.apache.sling.maven.slingstart.ModelPreprocessor.java

License:Apache License

/**
 * Read all model files from the directory in alphabetical order.
 * Only files ending with .txt or .model are read.
 *
 * @param project The current maven project
 * @param modelDirectory The directory to scan for models
 * @param logger The logger/*ww  w .j  a v a  2s  . c  o m*/
 */
protected Model readLocalModel(final MavenProject project, final String inlinedModel, final File modelDirectory,
        final String pattern, final Logger logger) throws MavenExecutionException, IOException {
    final Pattern p = Pattern.compile(pattern);
    final List<String> candidates = new ArrayList<String>();
    if (modelDirectory != null && modelDirectory.exists()) {
        for (final File f : modelDirectory.listFiles()) {
            if (f.isFile() && !f.getName().startsWith(".")) {
                if (p.matcher(f.getName()).matches()) {
                    candidates.add(f.getName());
                }
            }
        }
        Collections.sort(candidates);
    }
    if (candidates.size() == 0 && (inlinedModel == null || inlinedModel.trim().length() == 0)) {
        throw new MavenExecutionException(
                "No model files found in " + modelDirectory + ", and no model inlined in POM.", (File) null);
    }
    final Model result = new Model();
    if (inlinedModel != null) {
        logger.debug("Reading inlined model from project " + project.getId());
        try {
            final Reader reader = new StringReader(inlinedModel);
            try {
                final Model current = ModelReader.read(reader, "pom");
                final Map<Traceable, String> errors = ModelUtility.validate(current);
                if (errors != null) {
                    throw new MavenExecutionException("Invalid inlined model : " + errors, (File) null);
                }
                ModelUtility.merge(result, current, false);
            } finally {
                IOUtils.closeQuietly(reader);
            }
        } catch (final IOException io) {
            throw new MavenExecutionException("Unable to read inlined model", io);
        }
    }
    for (final String name : candidates) {
        logger.debug("Reading model " + name + " in project " + project.getId());
        try {
            final File f = new File(modelDirectory, name);
            final FileReader reader = new FileReader(f);
            try {
                final Model current = ModelReader.read(reader, f.getAbsolutePath());
                final Map<Traceable, String> errors = ModelUtility.validate(current);
                if (errors != null) {
                    throw new MavenExecutionException("Invalid model at " + name + " : " + errors, (File) null);
                }
                ModelUtility.merge(result, current, false);
            } finally {
                IOUtils.closeQuietly(reader);
            }
        } catch (final IOException io) {
            throw new MavenExecutionException("Unable to read model at " + name, io);
        }
    }

    final Map<Traceable, String> errors = ModelUtility.validate(result);
    if (errors != null) {
        throw new MavenExecutionException("Invalid assembled model : " + errors, (File) null);
    }

    return postProcessReadModel(result);
}

From source file:org.apache.sling.maven.slingstart.ProjectHelper.java

License:Apache License

/**
 * Get the effective model from the project
 * @param project The maven projet/*from w w  w.  j  a  v  a 2  s. com*/
 * @return The effective model
 * @throws MojoExecutionException If reading fails
 */
public static Model getEffectiveModel(final MavenProject project, ResolverOptions resolverOptions)
        throws MojoExecutionException {
    Model result = (Model) project.getContextValue(EFFECTIVE_MODEL_CACHE);
    if (result == null) {
        try {
            final StringReader r = new StringReader((String) project.getContextValue(EFFECTIVE_MODEL_TXT));
            result = ModelReader.read(r, project.getId());
            result = ModelUtility.getEffectiveModel(result, resolverOptions);
            project.setContextValue(EFFECTIVE_MODEL_CACHE, result);
        } catch (final IOException ioe) {
            throw new MojoExecutionException(ioe.getMessage(), ioe);
        }
    }
    return result;
}

From source file:org.apache.sling.maven.slingstart.ProjectHelper.java

License:Apache License

/**
 * Get the raw model from the project//from  w  w  w  .  ja  v a2s .  c  o  m
 * @param project The maven projet
 * @return The raw local model
 * @throws MojoExecutionException If reading fails
 */
public static Model getRawModel(final MavenProject project) throws MojoExecutionException {
    Model result = (Model) project.getContextValue(RAW_MODEL_CACHE);
    if (result == null) {
        try {
            final StringReader r = new StringReader((String) project.getContextValue(RAW_MODEL_TXT));
            result = ModelReader.read(r, project.getId());
            project.setContextValue(RAW_MODEL_CACHE, result);
        } catch (final IOException ioe) {
            throw new MojoExecutionException(ioe.getMessage(), ioe);
        }
    }
    return result;
}

From source file:org.apache.tomcat.maven.common.run.DefaultClassLoaderEntriesCalculator.java

License:Apache License

protected boolean isInProjectReferences(Artifact artifact, MavenProject project) {
    if (project.getProjectReferences() == null || project.getProjectReferences().isEmpty()) {
        return false;
    }//from   w  ww .  j  a  va 2  s  . c om
    @SuppressWarnings("unchecked")
    Collection<MavenProject> mavenProjects = project.getProjectReferences().values();
    for (MavenProject mavenProject : mavenProjects) {
        if (StringUtils.equals(mavenProject.getId(), artifact.getId())) {
            return true;
        }
    }
    return false;
}

From source file:org.apache.tuscany.maven.plugin.eclipse.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Resolve project dependencies. Manual resolution is needed in order to avoid resolution of multiproject artifacts
 * (if projects will be linked each other an installed jar is not needed) and to avoid a failure when a jar is
 * missing.//from  w  w w . j a v a2s .c o m
 *
 * @throws MojoExecutionException if dependencies can't be resolved
 * @return resolved IDE dependencies, with attached jars for non-reactor dependencies
 */
protected IdeDependency[] doDependencyResolution() throws MojoExecutionException {
    if (ideDeps == null) {
        if (resolveDependencies) {
            MavenProject project = getProject();
            Set<String> imported = Collections.emptySet();
            try {
                imported = BundleUtil.getImportedPackages(project.getBasedir());
            } catch (IOException e1) {
                throw new MojoExecutionException(e1.getMessage(), e1);
            }
            ArtifactRepository localRepo = getLocalRepository();

            List deps = getProject().getDependencies();

            // Collect the list of resolved IdeDependencies.
            List dependencies = new ArrayList();

            if (deps != null) {
                Map managedVersions = createManagedVersionMap(getArtifactFactory(), project.getId(),
                        project.getDependencyManagement());

                ArtifactResolutionResult artifactResolutionResult = null;

                try {

                    List listeners = new ArrayList();

                    if (logger.isDebugEnabled()) {
                        listeners.add(new DebugResolutionListener(logger));
                    }

                    listeners.add(new WarningResolutionListener(logger));

                    artifactResolutionResult = artifactCollector.collect(getProjectArtifacts(),
                            project.getArtifact(), managedVersions, localRepo,
                            project.getRemoteArtifactRepositories(), getArtifactMetadataSource(), null,
                            listeners);
                } catch (ArtifactResolutionException e) {
                    getLog().debug(e.getMessage(), e);
                    getLog().error(
                            Messages.getString("AbstractIdeSupportMojo.artifactresolution", new Object[] { //$NON-NLS-1$
                                    e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() }));

                    // if we are here artifactResolutionResult is null, create a project without dependencies but
                    // don't fail
                    // (this could be a reactor projects, we don't want to fail everything)
                    // Causes MECLIPSE-185. Not sure if it should be handled this way??
                    return new IdeDependency[0];
                }

                // keep track of added reactor projects in order to avoid duplicates
                Set emittedReactorProjectId = new HashSet();

                for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i
                        .hasNext();) {

                    ResolutionNode node = (ResolutionNode) i.next();
                    int dependencyDepth = node.getDepth();
                    Artifact art = node.getArtifact();
                    // don't resolve jars for reactor projects
                    if (hasToResolveJar(art)) {
                        try {
                            artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository);
                        } catch (ArtifactNotFoundException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactdownload", //$NON-NLS-1$
                                    new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        } catch (ArtifactResolutionException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactresolution", //$NON-NLS-1$
                                    new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        }
                    }

                    boolean includeArtifact = true;
                    if (getExcludes() != null) {
                        String artifactFullId = art.getGroupId() + ":" + art.getArtifactId();
                        if (getExcludes().contains(artifactFullId)) {
                            getLog().info("excluded: " + artifactFullId);
                            includeArtifact = false;
                        }
                    }

                    if (includeArtifact && (!(getUseProjectReferences() && isAvailableAsAReactorProject(art))
                            || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId()))) {

                        // the following doesn't work: art.getArtifactHandler().getPackaging() always returns "jar"
                        // also
                        // if the packaging specified in pom.xml is different.

                        // osgi-bundle packaging is provided by the felix osgi plugin
                        // eclipse-plugin packaging is provided by this eclipse plugin
                        // String packaging = art.getArtifactHandler().getPackaging();
                        // boolean isOsgiBundle = "osgi-bundle".equals( packaging ) || "eclipse-plugin".equals(
                        // packaging );

                        // we need to check the manifest, if "Bundle-SymbolicName" is there the artifact can be
                        // considered
                        // an osgi bundle
                        if ("pom".equals(art.getType())) {
                            continue;
                        }
                        File artifactFile = art.getFile();
                        MavenProject reactorProject = getReactorProject(art);
                        if (reactorProject != null) {
                            artifactFile = reactorProject.getBasedir();
                        }
                        boolean isOsgiBundle = false;
                        String osgiSymbolicName = null;
                        try {
                            osgiSymbolicName = BundleUtil.getBundleSymbolicName(artifactFile);
                        } catch (IOException e) {
                            getLog().error("Unable to read jar manifest from " + artifactFile, e);
                        }
                        isOsgiBundle = osgiSymbolicName != null;

                        IdeDependency dep = new IdeDependency(art.getGroupId(), art.getArtifactId(),
                                art.getVersion(), art.getClassifier(), useProjectReference(art),
                                Artifact.SCOPE_TEST.equals(art.getScope()),
                                Artifact.SCOPE_SYSTEM.equals(art.getScope()),
                                Artifact.SCOPE_PROVIDED.equals(art.getScope()),
                                art.getArtifactHandler().isAddedToClasspath(), art.getFile(), art.getType(),
                                isOsgiBundle, osgiSymbolicName, dependencyDepth, getProjectNameForArifact(art));
                        // no duplicate entries allowed. System paths can cause this problem.
                        if (!dependencies.contains(dep)) {
                            // [rfeng] Do not add compile/provided dependencies
                            if (!(pde && (Artifact.SCOPE_COMPILE.equals(art.getScope())
                                    || Artifact.SCOPE_PROVIDED.equals(art.getScope())))) {
                                dependencies.add(dep);
                            } else {
                                // Check this compile dependency is an OSGi package supplier
                                if (!imported.isEmpty()) {
                                    Set<String> exported = Collections.emptySet();
                                    try {
                                        exported = BundleUtil.getExportedPackages(artifactFile);
                                    } catch (IOException e) {
                                        getLog().error("Unable to read jar manifest from " + art.getFile(), e);
                                    }
                                    boolean matched = false;
                                    for (String p : imported) {
                                        if (exported.contains(p)) {
                                            matched = true;
                                            break;
                                        }
                                    }
                                    if (!matched) {
                                        dependencies.add(dep);
                                    } else {
                                        getLog().debug(
                                                "Compile dependency is skipped as it is added through OSGi dependency: "
                                                        + art);
                                    }
                                } else {
                                    dependencies.add(dep);
                                }
                            }
                        }
                    }

                }

                // @todo a final report with the list of
                // missingArtifacts?

            }

            ideDeps = (IdeDependency[]) dependencies.toArray(new IdeDependency[dependencies.size()]);
        } else {
            ideDeps = new IdeDependency[0];
        }
    }

    return ideDeps;
}

From source file:org.codehaus.gmaven.plugin.CompileState.java

License:Apache License

private String projectKey(final MavenProject project) {
    assert project != null;

    if (project.getBasedir() == null || !project.getBasedir().isDirectory()) {
        throw new IllegalStateException(
                "Project " + project.getId() + " does not define a base directory: " + project.getBasedir());
    }/*w  ww  . j av  a 2  s.co  m*/

    try {
        return project.getBasedir().getCanonicalPath();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}