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

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

Introduction

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

Prototype

public Properties getProperties() 

Source Link

Usage

From source file:nl.mpi.tla.version.controller.VersionControlCheck.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException {
    final VcsVersionChecker versionChecker;
    try {/*  ww w  .  j  a v a2s  . c om*/
        switch (VcsType.valueOf(vcsType)) {
        case git:
            versionChecker = new GitVersionChecker(new CommandRunnerImpl());
            break;
        case svn:
            versionChecker = new SvnVersionChecker(new CommandRunnerImpl());
            break;
        default:
            throw new MojoExecutionException("Unknown version control system: " + vcsType);
        }
    } catch (IllegalArgumentException exception) {
        throw new MojoExecutionException("Unknown version control system: " + vcsType + "\nValid options are: "
                + VcsType.git.name() + " or " + VcsType.svn.name());
    }
    if (verbose) {
        logger.info("VersionControlCheck");
        logger.info("project: " + project);
        logger.info("majorVersion: " + majorVersion);
        logger.info("minorVersion: " + minorVersion);
        logger.info("buildType: " + buildType);
        logger.info("outputDirectory: " + outputDirectory);
        logger.info("projectDirectory :" + projectDirectory);
    }
    for (MavenProject reactorProject : mavenProjects) {
        final String artifactId = reactorProject.getArtifactId();
        final String moduleVersion = reactorProject.getVersion();
        final String groupId = reactorProject.getGroupId();
        logger.info("Checking version numbers for " + artifactId);
        if (verbose) {
            logger.info("artifactId: " + artifactId);
            logger.info("moduleVersion: " + moduleVersion);
            logger.info("moduleDir :" + reactorProject.getBasedir());
        }
        //                for (MavenProject dependencyProject : reactorProject.getDependencies()) {
        //                    logger.info("dependencyProject:" + dependencyProject.getArtifactId());
        //                }
        final String expectedVersion;
        final String buildVersionString;
        final File moduleDirectory = reactorProject.getBasedir();
        if (allowSnapshots && moduleVersion.contains("SNAPSHOT")) {
            expectedVersion = majorVersion + "." + minorVersion + "-" + buildType + "-SNAPSHOT";
            buildVersionString = "-1"; //"SNAPSHOT"; it will be nice to have snapshot here but we need to update some of the unit tests first
        } else if ((modulesWithShortVersion != null && modulesWithShortVersion.contains(artifactId))
                || (moduleWithShortVersion != null && moduleWithShortVersion.equals(artifactId))) {
            expectedVersion = majorVersion + "." + minorVersion;
            buildVersionString = "-1";
        } else {
            logger.info("getting build number");
            int buildVersion = versionChecker.getBuildNumber(verbose, moduleDirectory, ".");
            logger.info(artifactId + ".buildVersion: " + Integer.toString(buildVersion));
            expectedVersion = majorVersion + "." + minorVersion + "." + buildVersion + "-" + buildType;
            buildVersionString = Integer.toString(buildVersion);
        }
        if (!expectedVersion.equals(moduleVersion)) {
            logger.error("Expecting version number: " + expectedVersion);
            logger.error("But found: " + moduleVersion);
            logger.error("Artifact: " + artifactId);
            throw new MojoExecutionException("The build numbers to not match for '" + artifactId + "': '"
                    + expectedVersion + "' vs '" + moduleVersion + "'");
        }
        // get the last commit date
        logger.info("getting lastCommitDate");
        final String lastCommitDate = versionChecker.getLastCommitDate(verbose, moduleDirectory, ".");
        logger.info(".lastCommitDate:" + lastCommitDate);
        // construct the compile date
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
        Date date = new Date();
        final String buildDate = dateFormat.format(date);
        // setting the maven properties
        final String versionPropertyName = groupId + "." + artifactId + ".moduleVersion";
        logger.info("Setting property '" + versionPropertyName + "' to '" + expectedVersion + "'");
        reactorProject.getProperties().setProperty(versionPropertyName, expectedVersion);
        reactorProject.getProperties().setProperty(propertiesPrefix + ".majorVersion", majorVersion);
        reactorProject.getProperties().setProperty(propertiesPrefix + ".minorVersion", minorVersion);
        reactorProject.getProperties().setProperty(propertiesPrefix + ".buildVersion", buildVersionString);
        reactorProject.getProperties().setProperty(propertiesPrefix + ".lastCommitDate", lastCommitDate);
        reactorProject.getProperties().setProperty(propertiesPrefix + ".buildDate", buildDate);
    }
}

From source file:npanday.registry.impl.ContextAwareModelInterpolator.java

License:Apache License

public static Interpolator buildInterpolator(final MavenProject project) {
    final StringSearchInterpolator interpolator = new StringSearchInterpolator();
    interpolator.setCacheAnswers(true);// w w w .ja va 2s.c  om

    if (project != null) {
        interpolator.addValueSource(
                new PrefixedPropertiesValueSource(PROJECT_PROPERTIES_PREFIXES, project.getProperties(), true));

        interpolator.addValueSource(new PrefixedObjectValueSource(PROJECT_PREFIXES, project, true));
    }

    /*final Properties settingsProperties = new Properties();
    if ( session != null && session.getSettings() != null )
    {
    settingsProperties.setProperty( "localRepository", session.getSettings().getLocalRepository() );
    settingsProperties.setProperty( "settings.localRepository", configSource.getLocalRepository().getBasedir
    () );
    }
    interpolator.addValueSource( new PropertiesBasedValueSource( settingsProperties ) );
            
    Properties commandLineProperties = System.getProperties();
    if ( session != null )
    {
    commandLineProperties = new Properties();
    if ( session.getExecutionProperties() != null )
    {
        commandLineProperties.putAll( session.getExecutionProperties() );
    }
            
    if ( session.getUserProperties() != null )
    {
        commandLineProperties.putAll( session.getUserProperties() );
    }
    }
    interpolator.addValueSource( new PropertiesBasedValueSource( commandLineProperties ) );
    */

    interpolator.addValueSource(
            new PrefixedPropertiesValueSource(Collections.singletonList("env."), ENVIRONMENT_VARIABLES, true));
    interpolator.addValueSource(new WindowsRegistryValueSource(new WinRegistry()));

    return interpolator;
}

From source file:org.apache.felix.bundleplugin.BundlePlugin.java

License:Apache License

protected Properties getDefaultProperties(MavenProject currentProject) {
    Properties properties = new Properties();

    String bsn;//ww  w.  j  a v  a2  s  . c o  m
    try {
        bsn = getMaven2OsgiConverter().getBundleSymbolicName(currentProject.getArtifact());
    } catch (Exception e) {
        bsn = currentProject.getGroupId() + "." + currentProject.getArtifactId();
    }

    // Setup defaults
    properties.put(MAVEN_SYMBOLICNAME, bsn);
    properties.put(Analyzer.BUNDLE_SYMBOLICNAME, bsn);
    properties.put(Analyzer.IMPORT_PACKAGE, "*");
    properties.put(Analyzer.BUNDLE_VERSION, getMaven2OsgiConverter().getVersion(currentProject.getVersion()));

    // remove the extraneous Include-Resource and Private-Package entries from generated manifest
    properties.put(Analyzer.REMOVE_HEADERS, Analyzer.INCLUDE_RESOURCE + ',' + Analyzer.PRIVATE_PACKAGE);

    header(properties, Analyzer.BUNDLE_DESCRIPTION, currentProject.getDescription());
    StringBuffer licenseText = printLicenses(currentProject.getLicenses());
    if (licenseText != null) {
        header(properties, Analyzer.BUNDLE_LICENSE, licenseText);
    }
    header(properties, Analyzer.BUNDLE_NAME, currentProject.getName());

    if (currentProject.getOrganization() != null) {
        String organizationName = currentProject.getOrganization().getName();
        header(properties, Analyzer.BUNDLE_VENDOR, organizationName);
        properties.put("project.organization.name", organizationName);
        properties.put("pom.organization.name", organizationName);
        if (currentProject.getOrganization().getUrl() != null) {
            String organizationUrl = currentProject.getOrganization().getUrl();
            header(properties, Analyzer.BUNDLE_DOCURL, organizationUrl);
            properties.put("project.organization.url", organizationUrl);
            properties.put("pom.organization.url", organizationUrl);
        }
    }

    properties.putAll(currentProject.getProperties());
    properties.putAll(currentProject.getModel().getProperties());
    properties.putAll(getProperties(currentProject.getModel(), "project.build."));
    properties.putAll(getProperties(currentProject.getModel(), "pom."));
    properties.putAll(getProperties(currentProject.getModel(), "project."));
    properties.put("project.baseDir", baseDir);
    properties.put("project.build.directory", getBuildDirectory());
    properties.put("project.build.outputdirectory", getOutputDirectory());

    properties.put("classifier", classifier == null ? "" : classifier);

    // Add default plugins
    header(properties, Analyzer.PLUGIN, BlueprintPlugin.class.getName() + "," + SpringXMLType.class.getName());

    return properties;
}

From source file:org.apache.myfaces.trinidadbuild.plugin.jdeveloper.JDeveloperMojo.java

License:Apache License

private void replaceProjects(File workspaceDir, Xpp3Dom workspaceDOM) throws XmlPullParserException {
    // /jws:workspace
    // /list[@n="listOfChildren"]
    Xpp3Dom sourceDOM = workspaceDOM.getChild("list");

    // <hash>
    // <value n="nodeClass" v="oracle.jdeveloper.model.JProject"/>
    // <url n="URL" path="[workspace-relative-path-to-project.jpr]"/>
    // </hash>
    Xpp3Dom targetDOM = new Xpp3Dom("list");

    MavenProject collectedProject = (MavenProject) project;
    boolean projHasTests = false;

    // Added in V11
    if (_releaseMajor >= 11) {
        Properties props = collectedProject.getProperties();
        String hasTests = (String) props.get(_PROPERTY_HAS_TESTS);
        projHasTests = "true".equalsIgnoreCase(hasTests);
    }//from  ww w .j  ava2s .  c  o m

    getLog().info("projHasTests is " + Boolean.valueOf(projHasTests).toString());

    File projectFile = getJProjectFile(collectedProject);

    targetDOM.addChild(createProjectReferenceDOM(workspaceDir, projectFile));

    File testProjectFile = getJProjectTestFile(collectedProject);

    /*
     * * In V11, we don't create a <projname>-test.jpr if* a project
     * does not have any tests.
     */
    if (_releaseMajor >= 11) {
        if (projHasTests) {
            targetDOM.addChild(createProjectReferenceDOM(workspaceDir, testProjectFile));
        }
    } else {
        targetDOM.addChild(createProjectReferenceDOM(workspaceDir, testProjectFile));
    }

    // TODO: use a better merge algorithm
    removeChildren(sourceDOM);

    // make sure to pass Boolean.FALSE to allow
    // multiple child elements with the same name
    Xpp3Dom.mergeXpp3Dom(sourceDOM, targetDOM, Boolean.FALSE);
}

From source file:org.apache.sling.ide.eclipse.m2e.internal.ContentPackageProjectConfigurator.java

License:Apache License

@Override
public void configure(ProjectConfigurationRequest configRequest, IProgressMonitor progressMonitor)
        throws CoreException {

    IProject project = configRequest.getProject();
    MavenProject mavenProject = configRequest.getMavenProject();
    boolean active = !"false".equalsIgnoreCase(mavenProject.getProperties().getProperty(M2E_ACTIVE));
    if (!active) {
        trace("M2E project configurer for packing type content-package was disabled with property {0}",
                M2E_ACTIVE);// ww w.j a v a  2s . co m
        return;
    }

    String mavenGav = mavenProject.getGroupId() + ":" + mavenProject.getArtifactId() + ":"
            + mavenProject.getVersion();

    trace("Configuring Maven project {0} with packaging content-package...", mavenGav);

    // core configuration for sling ide plugin

    Resource folder = MavenProjectUtils.guessJcrRootFolder(mavenProject);

    java.nio.file.Path contentSyncPath = mavenProject.getBasedir().toPath()
            .relativize(Paths.get(folder.getDirectory()));

    String jcrRootPath = contentSyncPath.toString();
    ConfigurationHelper.convertToContentPackageProject(project, progressMonitor,
            Path.fromOSString(jcrRootPath));

    new WtpProjectConfigurer(mavenProject, project, jcrRootPath).configure(progressMonitor);

    trace("Done converting .");
}

From source file:org.apache.sling.maven.projectsupport.BundleListUtils.java

License:Apache License

public static Interpolator createInterpolator(MavenProject project, MavenSession mavenSession) {
    StringSearchInterpolator interpolator = new StringSearchInterpolator();

    final Properties props = new Properties();
    props.putAll(project.getProperties());
    props.putAll(mavenSession.getSystemProperties());
    props.putAll(mavenSession.getUserProperties());

    interpolator.addValueSource(new PropertiesBasedValueSource(props));

    // add ${project.foo}
    interpolator.addValueSource(new PrefixedObjectValueSource(Arrays.asList("project", "pom"), project, true));

    // add ${session.foo}
    interpolator.addValueSource(new PrefixedObjectValueSource("session", mavenSession));

    // add ${settings.foo}
    final Settings settings = mavenSession.getSettings();
    if (settings != null) {
        interpolator.addValueSource(new PrefixedObjectValueSource("settings", settings));
    }/*w ww .j  a  va 2  s. com*/

    return interpolator;
}

From source file:org.apifocal.maven.plugins.bom.AbstractBomMojo.java

License:Apache License

protected void importProperties(Dependency artifactMetadata) throws MojoExecutionException {
    try {//from   w  w  w  .j  ava 2 s  .c o  m
        Artifact artifact = repoSystem.createDependencyArtifact(artifactMetadata);
        getLog().info("Importing properties from " + artifact);

        ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(
                session.getProjectBuildingRequest());
        buildingRequest.setProject(null);
        buildingRequest.setResolveDependencies(false);
        MavenProject bomProject = projectBuilder.build(artifact, buildingRequest).getProject();

        bomProject.getProperties()
                .forEach((Object key, Object value) -> project.getProperties().putIfAbsent(key, value));
    } catch (ProjectBuildingException ex) {
        getLog().error("Failed to resolve artifact", ex);
        throw new MojoExecutionException("Could not read artifact " + artifactMetadata.toString(), ex);
    }
}

From source file:org.arakhne.maven.plugins.tagreplacer.AbstractReplaceMojo.java

License:Open Source License

/**
 * Replace the property information tags in the given text.
 * //from   ww w.  j a va2s . c  om
 * @param sourceFile
 *            is the filename in which the replacement is done.
 * @param sourceLine
 *            is the line at which the replacement is done. 
 * @param text
 *            is the text in which the author tags should be replaced
 * @param project
 * @param replacementType
 *            is the type of replacement.
 * @return the result of the replacement.
 * @throws MojoExecutionException
 */
protected synchronized String replaceProp(File sourceFile, int sourceLine, String text, MavenProject project,
        ReplacementType replacementType) throws MojoExecutionException {
    String result = text;
    Pattern p = buildMacroPatternWithGroup(MACRO_PROP);
    Matcher m = p.matcher(text);
    boolean hasResult = m.find();

    Properties props = null;
    if (project != null) {
        props = project.getProperties();
    }

    if (hasResult) {
        StringBuffer sb = new StringBuffer();
        StringBuilder replacement = new StringBuilder();
        String propName;
        do {
            propName = m.group(1);
            if (propName != null) {
                propName = propName.trim();
                if (propName.length() > 0) {
                    replacement.setLength(0);
                    if (props != null) {
                        String value = props.getProperty(propName);
                        if (value != null && !value.isEmpty()) {
                            replacement.append(value);
                        }
                    }
                    if (replacement.length() != 0) {
                        m.appendReplacement(sb, Matcher.quoteReplacement(replacement.toString()));
                    }
                } else {
                    getBuildContext().addMessage(sourceFile, sourceLine, 1,
                            "no property name for Prop tag: " + m.group(0), //$NON-NLS-1$
                            BuildContext.SEVERITY_WARNING, null);
                }
            } else {
                getBuildContext().addMessage(sourceFile, sourceLine, 1,
                        "no property name for Prop tag: " + m.group(0), //$NON-NLS-1$
                        BuildContext.SEVERITY_WARNING, null);
            }
            hasResult = m.find();
        } while (hasResult);

        m.appendTail(sb);

        result = sb.toString();
    }
    return result;
}

From source file:org.artificer.integration.java.artifactbuilder.MavenPomArtifactBuilder.java

License:Apache License

@Override
public ArtifactBuilder buildArtifacts(BaseArtifactType primaryArtifact, ArtifactContent artifactContent)
        throws Exception {
    super.buildArtifacts(primaryArtifact, artifactContent);

    try {/*from w w w .java2 s .  co m*/
        Model model = new MavenXpp3Reader().read(getContentStream());
        MavenProject project = new MavenProject(model);
        ((ExtendedDocument) primaryArtifact).setExtendedType(JavaModel.TYPE_MAVEN_POM_XML);
        for (String key : project.getProperties().stringPropertyNames()) {
            String value = project.getProperties().getProperty(key);
            ArtificerModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_MAVEN_PROPERTY + key, value);
        }
        //set core properties when not specified on the request
        if (primaryArtifact.getDescription() == null)
            primaryArtifact.setDescription(project.getDescription());
        if (primaryArtifact.getName() == null)
            primaryArtifact.setName(project.getName());
        if (primaryArtifact.getVersion() == null)
            primaryArtifact.setVersion(project.getVersion());
        //set the GAV and packaging info
        ArtificerModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_MAVEN_ARTIFACT_ID,
                model.getArtifactId());
        ArtificerModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_MAVEN_GROUP_ID,
                model.getGroupId());
        ArtificerModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_MAVEN_VERSION,
                model.getVersion());
        ArtificerModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_MAVEN_PACKAGING,
                model.getPackaging());
        //set the parent GAV info
        if (model.getParent() != null) {
            ArtificerModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_MAVEN_PARENT_ARTIFACT_ID,
                    model.getParent().getArtifactId());
            ArtificerModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_MAVEN_PARENT_GROUP_ID,
                    model.getParent().getGroupId());
            ArtificerModelUtils.setCustomProperty(primaryArtifact, JavaModel.PROP_MAVEN_PARENT_VERSION,
                    model.getParent().getVersion());
        }

        return this;
    } catch (XmlPullParserException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:org.asciidoctor.maven.site.AsciidoctorDoxiaParser.java

License:Apache License

protected OptionsBuilder processAsciiDocConfig(MavenProject project, Xpp3Dom siteConfig, OptionsBuilder options,
        AttributesBuilder attributes) {/*from w  w  w  .  j av  a  2  s  . c  o  m*/
    if (siteConfig == null) {
        return options.attributes(attributes);
    }

    Xpp3Dom asciidocConfig = siteConfig.getChild("asciidoc");
    if (asciidocConfig == null) {
        return options.attributes(attributes);
    }

    if (project.getProperties() != null) {
        for (Map.Entry<Object, Object> entry : project.getProperties().entrySet()) {
            attributes.attribute(((String) entry.getKey()).replaceAll("\\.", "-"), entry.getValue());
        }
    }

    for (Xpp3Dom asciidocOpt : asciidocConfig.getChildren()) {
        String optName = asciidocOpt.getName();
        if ("attributes".equals(optName)) {
            for (Xpp3Dom asciidocAttr : asciidocOpt.getChildren()) {
                AsciidoctorHelper.addAttribute(asciidocAttr.getName(), asciidocAttr.getValue(), attributes);
            }
        } else if ("requires".equals(optName)) {
            Xpp3Dom[] requires = asciidocOpt.getChildren("require");
            // supports variant:
            // <requires>
            //     <require>time</require>
            // </requires>
            if (requires.length > 0) {
                for (Xpp3Dom require : requires) {
                    requireLibrary(require.getValue());
                }
            } else {
                // supports variant:
                // <requires>time, base64</requires>
                for (String require : asciidocOpt.getValue().split(",")) {
                    requireLibrary(require);
                }
            }
        } else if ("templateDir".equals(optName) || "template_dir".equals(optName)) {
            options.templateDir(resolveProjectDir(project, asciidocOpt.getValue()));
        } else if ("templateDirs".equals(optName) || "template_dirs".equals(optName)) {
            List<File> templateDirs = new ArrayList<File>();
            for (Xpp3Dom dir : asciidocOpt.getChildren("dir")) {
                templateDirs.add(resolveProjectDir(project, dir.getValue()));
            }
            if (!templateDirs.isEmpty()) {
                options.templateDirs(templateDirs.toArray(new File[templateDirs.size()]));
            }
        } else if ("baseDir".equals(optName)) {
            options.baseDir(resolveProjectDir(project, asciidocOpt.getValue()));
        } else {
            options.option(optName.replaceAll("(?<!_)([A-Z])", "_$1").toLowerCase(), asciidocOpt.getValue());
        }
    }
    return options.attributes(attributes);
}