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:org.codehaus.mojo.build.CreateMojo.java

License:Open Source License

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {/* w ww  .  j  av a 2s . co  m*/
        getLog().info("Skipping execution.");
        return;
    }

    if (providerImplementations != null) {
        for (Entry<String, String> entry : providerImplementations.entrySet()) {
            String providerType = entry.getKey();
            String providerImplementation = entry.getValue();
            getLog().info("Change the default '" + providerType + "' provider implementation to '"
                    + providerImplementation + "'.");
            scmManager.setScmProviderImplementation(providerType, providerImplementation);
        }
    }
    Date now = Calendar.getInstance().getTime();
    if (format != null) {
        if (items == null) {
            throw new MojoExecutionException(
                    " if you set a format, you must provide at least one item, please check documentation ");
        }
        // needs to be an array
        // look for special values
        Object[] itemAry = new Object[items.size()];
        for (int i = 0; i < items.size(); i++) {
            Object item = items.get(i);
            if (item instanceof String) {
                String s = (String) item;
                if (s.equals("timestamp")) {
                    itemAry[i] = now;
                } else if (s.startsWith("scmVersion")) {
                    useScm = true;
                    itemAry[i] = getRevision();
                } else if (s.startsWith("buildNumber")) {
                    // check for properties file
                    File propertiesFile = this.buildNumberPropertiesFileLocation;

                    // create if not exists
                    if (!propertiesFile.exists()) {
                        try {
                            if (!propertiesFile.getParentFile().exists()) {
                                propertiesFile.getParentFile().mkdirs();
                            }
                            propertiesFile.createNewFile();
                        } catch (IOException e) {
                            throw new MojoExecutionException(
                                    "Couldn't create properties file: " + propertiesFile, e);
                        }
                    }

                    Properties properties = new Properties();
                    String buildNumberString = null;
                    FileInputStream inputStream = null;
                    FileOutputStream outputStream = null;
                    try {
                        // get the number for the buildNumber specified
                        inputStream = new FileInputStream(propertiesFile);
                        properties.load(inputStream);
                        buildNumberString = properties.getProperty(s);
                        if (buildNumberString == null) {
                            buildNumberString = "0";
                        }
                        int buildNumber = Integer.valueOf(buildNumberString).intValue();

                        // store the increment
                        properties.setProperty(s, String.valueOf(++buildNumber));
                        outputStream = new FileOutputStream(propertiesFile);
                        properties.store(outputStream, "maven.buildNumber.plugin properties file");

                        // use in the message (format)
                        itemAry[i] = new Integer(buildNumber);
                    } catch (NumberFormatException e) {
                        throw new MojoExecutionException(
                                "Couldn't parse buildNumber in properties file to an Integer: "
                                        + buildNumberString);
                    } catch (IOException e) {
                        throw new MojoExecutionException("Couldn't load properties file: " + propertiesFile, e);
                    } finally {
                        IOUtil.close(inputStream);
                        IOUtil.close(outputStream);
                    }
                } else {
                    itemAry[i] = item;
                }
            } else {
                itemAry[i] = item;
            }
        }

        revision = format(itemAry);
    } else {
        // Check if the plugin has already run.
        revision = project.getProperties().getProperty(this.buildNumberPropertyName);
        if (this.getRevisionOnlyOnce && revision != null) {
            getLog().debug("Revision available from previous execution");
            return;
        }

        if (doCheck) {
            // we fail if there are local mods
            checkForLocalModifications();
        } else {
            getLog().debug("Checking for local modifications: skipped.");
        }
        if (session.getSettings().isOffline()) {
            getLog().info("maven is executed in offline mode, Updating project files from SCM: skipped.");
        } else {
            if (doUpdate) {
                // we update your local repo
                // even after you commit, your revision stays the same until you update, thus this
                // action
                List<ScmFile> changedFiles = update();
                for (ScmFile file : changedFiles) {
                    getLog().debug("Updated: " + file);
                }
                if (changedFiles.size() == 0) {
                    getLog().debug("No files needed updating.");
                }
            } else {
                getLog().debug("Updating project files from SCM: skipped.");
            }
        }
        revision = getRevision();
    }

    if (project != null) {
        String timestamp = String.valueOf(now.getTime());
        if (timestampFormat != null) {
            timestamp = MessageFormat.format(timestampFormat, new Object[] { now });
        }

        getLog().info(MessageFormat.format("Storing buildNumber: {0} at timestamp: {1}",
                new Object[] { revision, timestamp }));
        if (revision != null) {
            project.getProperties().put(buildNumberPropertyName, revision);
        }
        project.getProperties().put(timestampPropertyName, timestamp);

        String scmBranch = getScmBranch();
        getLog().info("Storing buildScmBranch: " + scmBranch);
        project.getProperties().put(scmBranchPropertyName, scmBranch);

        // Add the revision and timestamp properties to each project in the reactor
        if (getRevisionOnlyOnce && reactorProjects != null) {
            Iterator<MavenProject> projIter = reactorProjects.iterator();
            while (projIter.hasNext()) {
                MavenProject nextProj = (MavenProject) projIter.next();
                if (revision != null) {
                    nextProj.getProperties().put(this.buildNumberPropertyName, revision);
                }
                nextProj.getProperties().put(this.timestampPropertyName, timestamp);
                nextProj.getProperties().put(this.scmBranchPropertyName, scmBranch);
            }
        }
    }
}

From source file:org.codehaus.mojo.build.CreateTimestampMojo.java

License:Open Source License

public void execute() {
    if (skip) {//from  w ww.j av  a2s .  c o  m
        getLog().info("Skipping execution.");
        return;
    }

    String timestampString = project.getProperties().getProperty(timestampPropertyName);

    // Check if the plugin has already run in the current build.
    if (timestampString != null) {
        getLog().debug("Using previously created timestamp.");
        return;
    }

    timestampString = Utils.createTimestamp(timestampFormat, timezone);

    getLog().debug("Storing timestamp property: " + timestampPropertyName + " " + timestampString);

    Iterator<MavenProject> projIter = reactorProjects.iterator();
    while (projIter.hasNext()) {
        MavenProject nextProj = (MavenProject) projIter.next();
        nextProj.getProperties().setProperty(this.timestampPropertyName, timestampString);
    }

}

From source file:org.codehaus.mojo.dashboard.report.plugin.DashBoardUtils.java

License:Apache License

/**
 * @param project/*ww w. j a va 2  s.  co  m*/
 * @param value
 * @return
 */
private String getInterpolatorValue(MavenProject project, String value) {

    RegexBasedInterpolator interpolator = new RegexBasedInterpolator();
    interpolator.addValueSource(new ObjectBasedValueSource(project));
    interpolator.addValueSource(new MapBasedValueSource(project.getProperties()));

    String result = interpolator.interpolate(value, "project");

    return result;
}

From source file:org.codehaus.mojo.unix.maven.plugin.MavenProjectWrapper.java

License:Open Source License

public static MavenProjectWrapper mavenProjectWrapper(final MavenProject project, MavenSession session) {
    SortedMap<String, String> properties = new TreeMap<String, String>();

    // This is perhaps not ideal. Maven uses reflection to dynamically extract properties from the project
    // when interpolating each file. This uses a static list that doesn't contain the project.* properties, except
    // the new we hard-code support for.
    //// www.  j  a  v a  2  s  .  c om
    // The user can work around this like this:
    // <properties>
    //   <project.build.directory>${project.build.directory}</project.build.directory>
    // </properties>
    //
    // If this has to change, the properties has to be a F<String, String> and interpolation tokens ("${" and "}")
    // has to be defined. Doable but too painful for now.
    properties.putAll(toMap(session.getSystemProperties()));
    properties.putAll(toMap(session.getUserProperties()));
    properties.putAll(toMap(project.getProperties()));
    properties.put("project.groupId", project.getGroupId());
    properties.put("project.artifactId", project.getArtifactId());
    properties.put("project.version", project.getVersion());

    return new MavenProjectWrapper(project.getGroupId(), project.getArtifactId(), project.getVersion(),
            project.getArtifact(), project.getName(), project.getDescription(), project.getBasedir(),
            new File(project.getBuild().getDirectory()), new LocalDateTime(), project.getArtifacts(),
            project.getLicenses(), new ArtifactMap(project.getArtifacts()), unmodifiableSortedMap(properties));
}

From source file:org.codehaus.mojo.versions.api.DefaultVersionsHelper.java

License:Apache License

/**
 * {@inheritDoc}//from  w ww  .j a  v  a  2  s.c  o  m
 */
public Map<Property, PropertyVersions> getVersionPropertiesMap(MavenProject project,
        Property[] propertyDefinitions, String includeProperties, String excludeProperties,
        boolean autoLinkItems) throws MojoExecutionException {
    Map<String, Property> properties = new HashMap<String, Property>();
    if (propertyDefinitions != null) {
        for (Property propertyDefinition : propertyDefinitions) {
            properties.put(propertyDefinition.getName(), propertyDefinition);
        }
    }
    Map<String, PropertyVersionsBuilder> builders = new HashMap<String, PropertyVersionsBuilder>();
    if (autoLinkItems) {
        final PropertyVersionsBuilder[] propertyVersionsBuilders;
        try {
            propertyVersionsBuilders = PomHelper.getPropertyVersionsBuilders(this, project);
        } catch (ExpressionEvaluationException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }

        for (PropertyVersionsBuilder propertyVersionsBuilder : propertyVersionsBuilders) {
            final String name = propertyVersionsBuilder.getName();
            builders.put(name, propertyVersionsBuilder);
            if (!properties.containsKey(name)) {
                final Property value = new Property(name);
                getLog().debug("Property ${" + name + "}: Adding inferred version range of "
                        + propertyVersionsBuilder.getVersionRange());
                value.setVersion(propertyVersionsBuilder.getVersionRange());
                properties.put(name, value);
            }
        }
    }
    getLog().debug("Searching for properties associated with builders");
    Iterator<Property> i = properties.values().iterator();
    while (i.hasNext()) {
        Property property = i.next();
        if (includeProperties != null && !includeProperties.contains(property.getName())) {
            getLog().debug("Skipping property ${" + property.getName() + "}");
            i.remove();
        } else if (excludeProperties != null && excludeProperties.contains(property.getName())) {
            getLog().debug("Ignoring property ${" + property.getName() + "}");
            i.remove();
        }
    }
    i = properties.values().iterator();
    Map<Property, PropertyVersions> propertyVersions = new LinkedHashMap<Property, PropertyVersions>(
            properties.size());
    while (i.hasNext()) {
        Property property = i.next();
        getLog().debug("Property ${" + property.getName() + "}");
        PropertyVersionsBuilder builder = builders.get(property.getName());
        if (builder == null || !builder.isAssociated()) {
            getLog().debug("Property ${" + property.getName() + "}: Looks like this property is not "
                    + "associated with any dependency...");
            builder = new PropertyVersionsBuilder(null, property.getName(), this);
        }
        if (!property.isAutoLinkDependencies()) {
            getLog().debug("Property ${" + property.getName() + "}: Removing any autoLinkDependencies");
            builder.clearAssociations();
        }
        Dependency[] dependencies = property.getDependencies();
        if (dependencies != null) {
            for (Dependency dependency : dependencies) {
                try {
                    getLog().debug(
                            "Property ${" + property.getName() + "}: Adding association to " + dependency);
                    builder.addAssociation(this.createDependencyArtifact(dependency), false);
                } catch (InvalidVersionSpecificationException e) {
                    throw new MojoExecutionException(e.getMessage(), e);
                }
            }
        }
        try {
            final PropertyVersions versions = builder.newPropertyVersions();
            if (property.isAutoLinkDependencies() && StringUtils.isEmpty(property.getVersion())
                    && !StringUtils.isEmpty(builder.getVersionRange())) {
                getLog().debug("Property ${" + property.getName() + "}: Adding inferred version range of "
                        + builder.getVersionRange());
                property.setVersion(builder.getVersionRange());
            }
            versions.setCurrentVersion(project.getProperties().getProperty(property.getName()));
            propertyVersions.put(property, versions);
        } catch (ArtifactMetadataRetrievalException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
    return propertyVersions;
}

From source file:org.codehaus.mojo.webstart.generator.AbstractGenerator.java

License:Apache License

/**
 * Creates a Velocity context and populates it with replacement values
 * for our pre-defined placeholders.// w w  w.j a  v  a2 s .  co m
 *
 * @return Returns a velocity context with system and maven properties added
 */
protected VelocityContext createAndPopulateContext() {
    VelocityContext context = new VelocityContext();

    context.put("dependencies", getDependenciesText());

    // Note: properties that contain dots will not be properly parsed by Velocity. 
    // Should we replace dots with underscores ?        
    addPropertiesToContext(System.getProperties(), context);

    MavenProject mavenProject = config.getMavenProject();
    String encoding = config.getEncoding();

    addPropertiesToContext(mavenProject.getProperties(), context);
    addPropertiesToContext(extraConfig.getProperties(), context);

    context.put("project", mavenProject.getModel());
    context.put("jnlpCodebase", extraConfig.getJnlpCodeBase());

    // aliases named after the JNLP file structure
    context.put("informationTitle", mavenProject.getModel().getName());
    context.put("informationDescription", mavenProject.getModel().getDescription());
    if (mavenProject.getModel().getOrganization() != null) {
        context.put("informationVendor", mavenProject.getModel().getOrganization().getName());
        context.put("informationHomepage", mavenProject.getModel().getOrganization().getUrl());
    }

    // explicit timestamps in local and and UTC time zones
    Date timestamp = new Date();
    context.put("explicitTimestamp", dateToExplicitTimestamp(timestamp));
    context.put("explicitTimestampUTC", dateToExplicitTimestampUTC(timestamp));

    context.put("outputFile", config.getOutputFile().getName());
    context.put("mainClass", config.getMainClass());

    context.put("encoding", encoding);
    context.put("input.encoding", encoding);
    context.put("output.encoding", encoding);

    // TODO make this more extensible
    context.put("allPermissions", BooleanUtils.toBoolean(extraConfig.getAllPermissions()));
    context.put("offlineAllowed", BooleanUtils.toBoolean(extraConfig.getOfflineAllowed()));
    context.put("jnlpspec", extraConfig.getJnlpSpec());
    context.put("j2seVersion", extraConfig.getJ2seVersion());

    return context;
}

From source file:org.ebayopensource.turmeric.eclipse.maven.core.utils.MavenCoreUtils.java

License:Open Source License

private static MavenProjectInfo getIntfProjectInfoFromProperties(final String projectName,
        final MavenProject mProject) throws Exception {
    if (SOALogger.DEBUG)
        logger.entering(projectName, mProject);

    MavenProjectInfo result = null;//from  ww  w  .j a v  a 2s. c  o m

    // try to load from the project if available
    final IProject project = WorkspaceUtil.getProject(projectName);
    if (project != null && project.isAccessible()) {
        if (SOALogger.DEBUG)
            logger.debug("Project is accessible->", project);
        result = getInterfaceProjectInfo(project);
    } else {
        // the service only exist in the repository
        if (SOALogger.DEBUG)
            logger.debug("Project is NOT accessible, reading from the local repository->", mProject);
        final Properties props = mProject.getProperties();
        // the service name should be same as the interface project name
        final String serviceName = projectName;
        final String implProjectName = props.getProperty(SOAMavenConstants.POM_PROP_KEY_IMPL_PROJECT_NAME);
        Properties metadataProps = null;
        InputStream io = null;
        try {
            final String jarEntryPath = StringUtil.toString(SOAProjectConstants.FOLDER_META_INF,
                    SOAIntfProject.FOLDER_SOA_COMMON_CONFIG, WorkspaceUtil.PATH_SEPERATOR, serviceName,
                    WorkspaceUtil.PATH_SEPERATOR, SOAProjectConstants.PROPS_FILE_SERVICE_METADATA);
            io = getInputStreamFromJar(mProject, jarEntryPath);
            metadataProps = new Properties();
            metadataProps.load(io);
        } finally {
            IOUtils.closeQuietly(io);
        }

        result = createProjectInfoFromMetadataProps(serviceName, metadataProps);

        if (result != null) {
            result.setImplementationProjectName(implProjectName);
            /*
             * if (StringUtils.isNotBlank(implProjectName))
             * result.setImplementationProjectName(implProjectName); else {
             * //TODO the impl project name might not be available for those
             * project created in the old SOA plugin
             * result.setImplementationProjectName(serviceName +
             * SOAProjectConstants.IMPL_PROJECT_SUFFIX); logger.warning(
             * "Could not load the impl project name from the pom.xml of service->"
             * , projectName,
             * ", using the default logic with \"Impl\" as suffix ->",
             * result.getImplementationProjectName()); }
             */
            processDependencies(mProject.getModel(), result);
        }
    }

    if (SOALogger.DEBUG)
        logger.exiting(result);
    return result;
}

From source file:org.ebayopensource.turmeric.eclipse.maven.core.utils.MavenCoreUtils.java

License:Open Source License

/**
 * Gets the project info./*from w ww . jav  a  2  s .  co  m*/
 *
 * @param groupID the group id
 * @param projectName the project name
 * @param version the version
 * @return the project info
 * @throws Exception the exception
 */
public static MavenProjectInfo getProjectInfo(final String groupID, final String projectName,
        final String version) throws Exception {
    final String libVersion = version != null ? version
            : MavenCoreUtils.getLibraryVersion(groupID, projectName,
                    SOAProjectConstants.DEFAULT_SERVICE_VERSION);
    final String fullLibName = MavenCoreUtils.translateLibraryName(groupID, projectName, libVersion);
    final ArtifactMetadata artifact = getLibraryIdentifier(fullLibName);
    if (artifact != null) {
        final MavenProject mProject = MavenCoreUtils.getLibrary(artifact);
        if (getMavenOrgProviderInstance().getProjectGroupId(SupportedProjectType.INTERFACE).equals(groupID)) {
            return MavenCoreUtils.getIntfProjectInfoFromProperties(projectName, mProject);
        } else if (getMavenOrgProviderInstance().getProjectGroupId(SupportedProjectType.IMPL).equals(groupID)) {
            return MavenCoreUtils.getImplProjectInfoFromProperties(projectName, mProject.getProperties(),
                    mProject.getModel());
        } else if (getMavenOrgProviderInstance().getProjectGroupId(SupportedProjectType.CONSUMER)
                .equals(groupID)) {
            return MavenCoreUtils.getConsumerProjectInfoFromProperties(projectName, mProject.getProperties(),
                    mProject.getModel());
        } else if (getMavenOrgProviderInstance().getProjectGroupId(SupportedProjectType.TYPE_LIBRARY)
                .equals(groupID)) {
            // TODO return type library project info
            // return MavenUtil.getTypeLibraryInfo(mProject);
        } else if (SOAMavenConstants.SOA_FRAMEWORK_GROUPID.equals(groupID)) {
            // this could be either the soa framework jars or the client
            // projects
            // return MavenUtil.get(projectName, mProject.getProperties(),
            // mProject.getModel());
        }
    }

    return null;
}

From source file:org.ebayopensource.turmeric.plugins.maven.utils.LegacyProperties.java

License:Open Source License

/**
 * Create a LegacyProperties object for dealing with Legacy Properties.
 * //from ww w .j av a2  s. c om
 * @param log
 *            the log to write to
 * @param project
 *            the maven project to get maven properties from
 * @param legacyPropertiesFile
 *            the (potential) legacy properties file to load from. if this file does not exist, no properties are
 *            loaded, and no exception is thrown.
 * @throws MojoFailureException
 *             if the legacyPropertiesFile exists, but there is a problem reading / parsing / loading the properties
 *             from the file.
 */
public LegacyProperties(Log log, MavenProject project, File legacyPropertiesFile) throws MojoFailureException {
    this.log = log;
    this.legacyPropertiesFile = legacyPropertiesFile;

    projectProps = project.getProperties();
    if (projectProps == null) {
        projectProps = new Properties();
    }

    if (legacyPropertiesFile.exists()) {
        FileReader reader = null;
        try {
            reader = new FileReader(legacyPropertiesFile);
            legacyFileProps = new Properties();
            legacyFileProps.load(reader);
        } catch (IOException e) {
            throw new MojoFailureException("Unable to load properties file: " + legacyPropertiesFile, e);
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }
}

From source file:org.eclipse.m2e.core.internal.embedder.MavenImpl.java

License:Open Source License

public void interpolateModel(MavenProject project, Model model) throws CoreException {
    ModelBuildingRequest request = new DefaultModelBuildingRequest();
    request.setUserProperties(project.getProperties());
    ModelProblemCollector problems = new ModelProblemCollector() {
        public void add(ModelProblem.Severity severity, String message, InputLocation location,
                Exception cause) {
        }/*from  w  w w  . j  av a 2s.  c o m*/
    };
    lookup(ModelInterpolator.class).interpolateModel(model, project.getBasedir(), request, problems);
}