Sonar mojo 1.0-beta-2 Released by Mojo team – Configure now

sonar-mojo-10

The Mojo team is pleased to announce the release of Sonar Maven Plugin, version 1.0-beta-2. It makes configuration easier when using a repository manager like Archivaor Nexus. Indeed no additional settings are required anymore ! Let’s remind that the version 1.0-beta-1 needs to declare a mirror in maven settings.

This improvement requires Sonar 2.2+. It is automatically disabled when using sonar 2.1 or less. Upgrading to this version should be automatic if the shortcut “mvn sonar:sonar” is used.

Tagged : / / / / / / / / / / / / / / /

Maven2 Step by Step Guide – Complete Introduction

maven2-step-by-step

Setting up the application frame

The Maven2 documentation is silent about how to set up web application skeletons. The standard archetypes allow you to create a simple standalone, a simple web application (no Java code), and a multi-module project. Presumably, the recommended approach to creating a standard web application (JSP and HTML code for the view, and Java code for the Model and Controller layers) is to create a multi-module project containing a single simple web application and one or more standalone applications for the Model and Controller. However, it is possible to make Maven2 work with a standard web application structure by adding some directories to the skeleton created by the standalone Maven archetype.

The Maven2 Getting started Guide has some commands for creating skeletons from standard Maven archetypes. To create the skeleton for an application my-app in the com.mycompany.app namespace using a standalone archetype, run this command:

1
$ mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=my-app

To make a standard web application skeleton from this, add the following directories. The webapps directories is the root of the web applications context, and contains the WEB-INF directory. The resources subdirectory corresponds to the WEB-INF/classes directory for a web application or the conf/ or etc/ directory for a standalone, where all the properties files go. The test/resources/ directory is useful for storing test specific properties files.

1
2
3
4
my-app/src/main/webapps/
my-app/src/main/webapps/WEB-INF/
my-app/src/main/resources/
my-app/src/test/resources/

Finally, to make a web application out of the standard standalone application, change the value of project.packaging from jar to war in the pom.xml file.

Standard Maven2 Goals

Maven2 provides some standard goals which are similar to Ant targets found in most project’s build.xml files. This helps people familiar with Ant to make a quick transition to using Maven2. They are as follows:

1
2
3
4
5
6
mvn clean - cleans out all Maven2 generated files.
mvn compile - compiles the Java sources
mvn test-compile - compiles the Java JUnit test classes.
mvn test - runs all JUnit tests in the project.
mvn package - builds the JAR or WAR file for the project.
mvn install - installs the JAR or WAR file in the local Maven repository.

Most of these goals are configured in the super-POM, but if you want to build your application using Java 1.5 (who doesn’t these days), you will need some additional configuration in your pom.xml, in the project.build.plugins element in your pom.xml.

1
2
3
4
5
6
7
8
9
      <!-- Java 1.5 compiler plugin -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>

Generating IDE configuration files

Most people work with some kind of IDE, and the IDE must be told where to look for JAR files, Java code, test code, etc. Since this information is already specified in the pom.xml files, Maven2 can generate the IDE artefacts for a large number of popular IDEs in use, such as Eclipse, IDEA and Emacs JDEE. To generate the Eclipse artefacts for your project, run the following command:

1
$ mvn eclipse:eclipse

You also need to tell Eclipse where to find the your local Maven2 repository (under ~/.m2/repository by default). You can do this by setting a global environment variable M2_REPO in the IDE.

Running Jetty in place (webapps)

A nice touch is the Maven2 Jetty Plugin. This starts up a Jetty installation in place in your web application. This is a huge time-saver, since web application development is often an iterative cycle of changing code, deploying to application server, checking a web page and back. Having Jetty running on your web application source enables you to see your changes instantly (or after compiling with changes in Java code). To set it up, you will need to add the following configuration in project.build.plugins in your pom.xml file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty6-plugin</artifactId>
        <configuration>
          <scanIntervalSeconds>10</scanIntervalSeconds>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-j2ee_1.4_spec</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
          </dependency>
        </dependencies>
      </plugin>

Then start up Jetty with the following command. You should be able to see your web application on your browser at http://localhost:8080/my-app.

1
$ mvn jetty6:run

Documentation: The project website

I think of documentation as a place to tell the world all about the cool things my project does. However, too many projects skimp on documentation, because of the effort in setting up the infrastructure in place to generate documentation. Maven2 has built in support for generating a project website with all the documentation for your project. Data entered into the pom.xml drives a lot of the reports, such as Mailing List, Issue Management, Source Repository, etc. Maven2 needs to be told which reports to generate in the project.reporting.plugins section of the pom.xml. Details about which pom.xml entries drive which report elements can be found in Resources[2].

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <reportSets>
          <reportSet>
            <reports>
              <report>dependencies</report>
              <report>project-team</report>
              <report>mailing-list</report>
              <report>cim</report>
              <report>issue-tracking</report>
              <!-- <report>license</report> -->
              <report>scm</report>
            </reports>
          </reportSet>
        </reportSets>
      </plugin>

You can also create project documentation content, such as User Guides, etc, in a variety of formats, such as DocBook and APT (Almost Plain Text). APT is a wiki-like plain text format which I find very convenient. For FAQ entries, Maven2 supports the FML format.

To set up the project site, create the following directories.

1
2
3
4
5
my-app/src/site/apt/
my-app/src/site/fml/
my-app/src/site/resources/
my-app/src/site/resources/images/
my-app/src/site/site.xml

The apt subdirectory should contain the documentation in APT format. The fml subdirectory contains various FAQ source files. The resources subdirectory should contain files and documents that do not need any pre-processing. The files in the apt and fml subdirectory will be pre-processed by the APT and FML processor and be copied to the project site root directory as .html files. The files in the resources subdirectory (including the images/ subdirectory) will be copied to the project site docroot as is. The site.xml specifies the template for your site, ie what the left and right banners should contain, etc. The site.xml file will reference these HTML files.

To generate the project web site, run the following command. The website will be generated under my-app/target/site where you can view it with a browser using the file:// protocol.

1
$ mvn site

Javadocs

The Javadocs plugin needs to be configured explicitly in the project pom.xml in the project.reporting.plugins section.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <configuration>
          <links>
            <link>http://java.sun.com/j2se/1.5.0/docs/api/</link>
            <link>http://plexus.codehaus.org/ref/1.0-alpha-9/apidocs</link>
            <link>http://jakarta.apache.org/commons/dbcp/apidocs/</link>
            ... other third party libs used by your project ...
          </links>
        </configuration>
      </plugin>

If the Javadocs plugin has been configured, then mvn site will automatically generate the Javadocs. Otherwise, they can be generated separately using the command:

1
$ mvn javadoc:javadoc

Java Cross Reference (JXR)

Another cool plugin is the Code Cross Reference that is created using the JXR plugin. The project code is made displayable with line numbers and syntax highlighting, with links to related code. Almost like having an IDE running on the browser in read-only mode. Though not required for all projects, this is very useful to allow people to review your code without having to download it. To configure it, configure the plugin in the project.reporting.plugins section.

1
2
3
4
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jxr-plugin</artifactId>
      </plugin>

Like the Javadocs goal, this will be run as part of mvn site as well, but can be run separately using the command:

1
mvn jxr:jxr

Code Style (Checkstyle)

I chose Checkstyle because I am familiar with it, but I think Maven2 supports other code style checkers too. I use the default Maven code style, since this is likely to become the most popular code style as more and more people embrace Maven2, but this setting can be overriden to use Sun’s code style or some other style preferred by your corporation. To configure it (with default Maven code style), we need the following configuration in project.reporting.plugins in the pom.xml file.

1
2
3
4
5
6
7
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
        <configuration>
          <configLocation>config/maven_checks.xml</configLocation>
        </configuration>
      </plugin>

As before, once configured, the report is run as part of the mvn site command, but can be run separately using the command:

1
$ mvn checkstyle:checkstyle

Unit Test Coverage (Cobertura)

Clover is the most popular tool for checking on Unit test coverage, and Maven2 provides a plugin for that. However, Clover is commercial software and costs money. A free, open-source alternative is Cobertura. Maven2 provides a Cobertura plugin as well. To configure this plugin, add the following XML to project.reporting.plugins section in the pom.xml.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
        <!--
        <executions>
          <execution>
            <id>clean</id>
            <phase>clean</phase>
            <goals>
              <goal>clean</goal>
            </goals>
          </execution>
        </executions>
        -->
      </plugin>

The plugin can be run manually using the command:

1
$ mvn cobertura:cobertura

The plugin leaves a cobertura.ser file in the project root directory, which can be removed using mvn clean. There was a suggestion to automate this by creating an executions subelement under the plugin declaration, but I could not get it to work – the parser complained about invalid tags, so I commented it out (in the above XML snippet). If anyone knows what I did wrong, please let me know.

Deploying files to other locations

I dont know much about this, except that it involves using the Maven2 Wagon Plugin. The plugin supports a wide variety of transport formats. I will post more information about this as I find it. If anyone has some information about using Wagon, would appreciate your posting it here or pointing to links with the information.

So thats basically all I have for now. Hopefully, this article will help kickstart Maven2 adoption in your new projects. Personally, I have used Ant for over 6 years now, and I was justifiably sceptical about switching new development to Maven2. However, I have had good success with Maven2 so far, and I am quite impressed with its range of capabilities in terms of integration with other tools and the services it provides to the developer.

Resources

  • The Maven 2 POM demystified – I have restructured my template pom.xml according to this article, and it helps a lot in understanding the POM.
  • Get the most out of Maven2 site generation – Much useful information about what elements to populate to produce clear Maven2 project reports.
  • The Maven2 Schema – Its hard to figure out what element goes where without examples. The XSD is very detailed and provides good information.
  • Better Builds with Maven – if you haven’t already downloaded this free e-book, you should. This is the only book I know of which talks about Maven2, so if you are working with Maven2, you should definitely download and read it.
  • Maven : A Developer’s Notebook – covers details of the FML format used for generating FAQ entries.
Tagged : / / / / / / / / / /

Clover and Maven working with Distributed Applications

clover-and-maven-working-with-distributed-applications

1.       Configure maven clover plugin.

2.       Build the all components with clover enabled.

3.       Deploy the clover enabled build to test server.

4.       Run the tests.

5.       Create & Review the Code Coverage Report.

Configure Maven Clover Plugin

Configure the maven plugin in pom.xml .If you are having multi module projects; you can configure the plugin in parent-pom instead of modifying each module’s pom xml.


Build all components with clover enabled.

Run the following command.

 

  “mvn -U clover2:setup package clover2:aggregate

 

                If you got something like this

[INFO] Loaded from: C:\Documents and Settings\Administrator\.m2\repository\com\cenqua\clover\clover\2.6.3\clover-2.6.3.jar

[INFO] Clover: Commercial License registered to ABC Corporation.

[INFO] Creating new database at ‘C:\p4_depot\trunk\4A\target\clover\clover.db’.

[INFO] Processing files at 1.5 source level.

[INFO] Clover all over. Instrumented 5 files (1 package).

[INFO] Elapsed time = 0.532 secs. (9.398 files/sec, 812.03 srclines/sec)

Congratulation, you get clover work with your source!!

 

Deploy the clover enabled build to test server.

Deploy the Clover enabled build to the server. The same process as normal

Copy the Clover registry file to the appropriate directory on each of the test servers

 

The registry file is the DB file create during compile, defined by initstring parametersclover‐setup task, this needs to occur after the Clover build is complete, and before you run your tests

 

Background: the Clover initstring

 

FileName: xxx.db

At build time, Clover constructs a registry of your source code, and writes it to a file at the location specified in the Clover initstring. When Clover‐ instrumented code is executed (e.g. by running a suite of unit tests), Clover looks in the same location for this registry file to initialise itself. Clover then records coverage data and writes coverage recording files next to the registry file during execution

Notes: gives the folder contains the registry file full control permissions

 

Recommended Permissions

Clover requires access to the Java system properties for runtime configurations, as well as read write access to areas of the file system to read the Clover coverage database and to write coverage information. Clover also uses a shutdown hook to ensure that it flushes any as yet unflushed coverage information to disk when Java exits. To support these requirements, the following security

permissions are recommended:

 

grant codeBase “file:/path/to/clover.jar” {

permission java.util.PropertyPermission “*”, “read”;

permission java.io.FilePermission “<>”, “read, write”;

permission java.lang.RuntimePermission “shutdownHooks”;

}

 

Grant Permissions to clover.jar

Edit the java.policy file of the java runtime on the test server

%JAVA_HOME%/jre/lib/security

 

Copy clover.jar and license file to the java runtime class path of the test servers

%JAVA_HOME%/jre/lib/ext

 

 

Run the test suite

Run the test suite as normal. Either automation test case or manual test case.

 

Create Code Coverage Report

Copy the coverage recording files to build machine.

 

Once test execution is complete, you will need to copy the coverage recording files from each remote machine to the initstring path on the build machine in order to generate coverage reports.

 

Background: CoverageRecording Files

 

Filename:xxx.dbHHHHHHH_TTTTTTTTTT or clover.dbHHHHHHH_TTTTTTTTTT.1 (where HHHHHHH and TTTTTTTTTT are both hex strings)

CoverageRecording files contain actual coverage data. When running instrumented code, Clover creates one or more Coverage Recorders. Each Coverage Recorder will write one CoverageRecording file. The number of Coverage Recorders created at runtime depends the nature of the application you are Clovering. In general a new Coverage Recorder will be created for each new ClassLoader instance that loads a Clovered class file. The first hex number in the filename (HHHHHHH) is a unique number based on the recording context. The second hex number (TTTTTTTTTT) is the timestamp (ms since epoch) of the creation of the Clover Recorder. CoverageRecording files are named this way to try to minimise the chance of a name clash. While it is theoretically possible that a name clash could occur, in practice the chances are very small.

CoverageRecording files are written during the execution of Clover‐instrumented code. CoverageRecording files are read during report generation or coverage browsing.

 

Run the generating report goal to create the report.

                                “mvn clover2:clover”

               

Tagged : / / / / / / / / / / / / / /

Maven 3.0-beta-1 Release – What’s new in Maven 3.0? – Quick guide

maven-30-beta-1

The Apache Maven team would like to announce the release of Maven 3.0-beta-1.

Maven 3.0-beta-1 is available for download from the ‘preview’ section.

Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central place.

Maven 3 aims to ensure backward compatibility with Maven 2, improve usability, increase performance, allow safe embedding, and pave the way to implement many highly demanded features.

The core release is independent of the plugins available. Further releases of plugins will be made separately. See the Plugin List for more information.

We hope you enjoy using Maven! If you have any questions, please consult:

 

For More Info…

http://maven.apache.org/docs/3.0-beta-1/release-notes.html

 

Tagged : / / / / / / / / / / / / / / /

Maven Interview Questions and Answers – Maven Job Interview Kit

maven-interview-questions-answers

Maven Interview Questions and Answers

Contributed by Rajesh Kumar with the help of Google Search and www.scmGalaxy.com
Is there a way to use the current date in the POM?
Take a look at the buildnumber plugin. It can be used to generate a build date each time I do a build, as follows:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>maven-buildnumber-plugin</artifactId>
<version>0.9.4</version>
<configuration>
<format>{0,date,yyyy-MM-dd HH:mm:ss}</format>
<items>
<item>timestamp</item>
</items>
<doCheck>false</doCheck>
<doUpdate>false</doUpdate>
</configuration>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>create</goal>
</goals>
</execution>
</executions>
</plugin>

pom.xml or settings.xml? What is the best practice configuration usage for these files?
The best practice guideline between settings.xml and pom.xml is that configurations in settings.xml must be specific to the current user and that pom.xml configurations are specific to the project.
For example, <repositories> in pom.xml would tell all users of the project to use the <repositories> specified in the pom.xml. However, some users may prefer to use a mirror instead, so they’ll put <mirrors> in their settings.xml so they can choose a faster repository server.
so there you go:
settings.xml -> user scope
pom.xml -> project scope

How do I indicate array types in a MOJO configuration?

<tags>
    <tag>value1</tag>
    <tag>value2</tag>
  </tags>

How should I point a path for maven 2 to use a certain version of JDK when I have different versions of JDK installed on my PC and my JAVA_HOME already set?
If you don’t want to change your system JAVA_HOME, set it in maven script instead.
How do I setup the classpath of my antrun plugin to use the classpath from maven?
The maven classpaths are available as ant references when running your ant script. The ant reference names and some examples can be found here: maven-antrun-plugin
Is it possible to use HashMap as configurable parameter in a plugin? How do I configure that in pom.xml?
Yes. Its possible to use a HashMap field as a parameter in your plugin. To use it, your pom configuration should look like this:

<myMap>
      <yourkey>yourvalue</yourkey>
      .....
   </myMap>

How do I filter which classes should be put inside the packaged jar?
All compiled classes are always put into the packaged jar. However, you can configure the compiler plugin to exclude compiling some of the java sources using the compiler parameter excludes as follows:

<project>
   ...
   <build>
     ...
     <plugins>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <configuration>
           <excludes>
             <exclude>**/NotNeeded*.java</exclude>
           </excludes>
         </configuration>
       </plugin>
     </plugins>
     ...
   </build>
  </project>

How can I change the default location of the generated jar when I command “mvn package”?
By default, the location of the generated jar is in ${project.build.directory} or in your target directory.
We can change this by configuring the outputDirectory of maven-jar-plugin.

<plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-jar-plugin</artifactId>
              <configuration>
                  <outputDirectory>${project.build.directory}/<!-- directory --></outputDirectory>
              </configuration>
          </plugin>

How does maven 2 implement reproducibility?

  • Add the exact versions of plugins into your pluginDepenencies (make use of the release plugin)
  • Make use of ibiblio for your libraries. This should always be the case for jars. (The group is working on stabilising metadata and techniques for locking it down even if it changes. An internal repository mirror that doesn’t fetch updates (only new) is recommended for true reproducibility.)

Why there are no dependency properties in Maven 2?
They were removed because they aren’t reliable in a transitive environment. It implies that the dependency knows something about the
environment of the dependee, which is back to front. In most cases, granted, the value for war bundle will be the same for a particular
dependency – but that relies on the dependency specifying it.
In the end, we give control to the actual POM doing the building, trying to use sensible defaults that minimise what needs to be
specified, and allowing the use of artifact filters in the configuration of plugins.

What does aggregator mean in mojo?
When a Mojo has a @aggregator expression, it means that It can only build the parent project of your multi-module-project, the one who has the packaging of pom. It can also give you values for the expression ${reactorProjects} where reactorProjects are the MavenProject references to the parent pom modules.
Where is the plugin-registry.xml?
From the settings.xml, you may enable it by setting <usePluginRegistry/> to true
and the file will be in ~/.m2/plugin-registry.xml
How do I create a command line parameter (i.e., -Dname=value ) in my mojo?
In your mojo, put “expression=${<exp>}” in your parameter field

/**
   * @parameter expression="${expression.name}"
   */
  private String exp;

You may now able to pass parameter values to the command line.
“mvn -Dexpression.name=value install”
How do I convert my <reports> from Maven 1 to Maven 2?
In m1, we declare reports in the pom like this:

<project>
    ...
    <reports>
      <report>maven-checkstyle-plugin</report>
      <report>maven-pmd-plugin</report>
    </reports>
  </project>

In m2, the <reports> tag is replaced with <reporting>

<project>
    ...
    <reporting>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-checkstyle-plugin</artifactId>
          <configuration>
             <!-- put your config here -->
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-pmd-plugin</artifactId>
          <configuration>
             <!-- put your config here -->
          </configuration>
        </plugin>
      </plugins>
    <reporting>
  </project>

What does the “You cannot have two plugin executions with the same (or missing) elements” message mean?
It means that you have executed a plugin multiple times with the same <id>. Provide each <execution> with a unique <id> then it would be ok.
How do I add my generated sources to the compile path of Maven, when using modello?
Modello generate the sources in the generate-sources phase and automatically adds the source directory for compilation in maven. So you don’t have to copy the generated sources. You have to declare the modello-plugin in the build of your plugin for source generation (in that way the sources are generated each time).
What is Maven’s order of inheritance?

  1. parent pom
  2. project pom
  3. settings
  4. CLI parameters

where the last overrides the previous.
How do I execute the assembly plugin with different configurations?
Add this to your pom,

<build>
    ...
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
      <id>1</id>
            <phase>install</phase>
        <goals>
             <goal>assembly</goal>
       </goals>
          <configuration>
               <descriptor>src/main/descriptors/bin.xml</descriptor>
               <finalName>${project.build.finalName}-bin</finalName>
       </configuration>
          </execution>

<execution>
<id>2</id>
<phase>install</phase>
<goals>
<goal>assembly</goal>
</goals>
<configuration>
<descriptor>src/main/descriptors/src.xml</descriptor>
<finalName>${project.build.finalName}-src</finalName>
</configuration>
</execution>
</executions>
</plugin>
</plugins>

</build>

and run mvn install, this will execute the assembly plugin twice with different config.
How do I configure the equivalent of maven.war.src of war plugin in Maven 2.0?

<build>
    ...
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
           <warSourceDirectory><!-- put the path of the directory --></warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
    ...
  </build>

How do I add main class in a generated jar’s manifest?
Configure the maven-jar-plugin and add your main class.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
     <mainClass>com.mycompany.app.App</mainClass>
        </manifest>
      </archive>
    </configuration>
  </plugin>

What does the FATAL ERROR with the message “Class org.apache.commons.logging.impl.Jdk14Logger does not implement Log” when using the maven-checkstyle-plugin mean?
Checkstyle uses commons-logging, which has classloader problems when initialized within a Maven plugin’s container. This results in the above message – if you run with ‘-e’, you’ll see something like the following:

Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: Class org.apache.commons.logging.impl.Jdk14Logger does not implement Log

buried deep in the stacktrace.
The only workaround we currently have for this problem is to include another commons-logging Log implementation in the plugin itself. So, you can solve the problem by adding the following to your plugin declaration in your POM:

<project>
    ...
    <build>
      ...
      <plugins>
        ...
        <plugin>
          <artifactId>maven-checkstyle-plugin</artifactId>
          <dependencies>
            <dependency>
              <groupId>log4j</groupId>
              <artifactId>log4j</artifactId>
              <version>1.2.12</version>
            </dependency>
          </dependencies>
        </plugin>
      </plugins>
    </build>
    ...
    <reporting>
      ...
      <plugins>
        <!-- your checkstyle report is registered here, according to Maven documentation -->
      </plugins>
    </reporting>
  </project>

While this may seem a counter-intuitive way of configuring a report, it’s important to remember that Maven plugins can have a mix of reports and normal mojos. When a POM has to configure extra dependencies for a plugin, it should do so in the normal plugins section.
We will probably try to fix this problem before the next release of the checkstyle plugin.
UPDATE: This problem has been fixed in the SVN trunk version of the checkstyle plugin, which should be released very soon.
Plugins and Lifecycle, Sites & Reporting, Errors
How do I determine the stale resources in a Mojo to avoid reprocessing them?
This can be done using the following piece of code:

// Imports needed
  import org.codehaus.plexus.compiler.util.scan.InclusionScanException;
  import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner;
  import org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping;

// At some point of your code
StaleSourceScanner scanner = new StaleSourceScanner( 0, Collections.singleton( “**/*.xml” ), Collections.EMPTY_SET );
scanner.addSourceMapping( new SuffixMapping( “.xml”, “.html” ) );
Set<File> staleFiles = (Set<File>) scanner.getIncludedSources( this.sourceDirectory, this.targetDirectory );

The second parameter to the StaleSourceScanner is the set of includes, while the third parameter is the set of excludes. You must add a source mapping to the scanner (second line). In this case we’re telling the scanner what is the extension of the result file (.html) for each source file extension (.xml). Finally we get the stale files as a Set<File> calling the getIncludedSources method, passing as parameters the source and target directories (of type File). The Maven API doesn’t support generics, but you may cast it that way if you’re using them.
In order to use this API you must include the following dependency in your pom:

<dependencies>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-compiler-api</artifactId>
      <version>1.5.1</version>
    </dependency>
  </dependencies>

Is there a property file for plug-in configuration in Maven 2.0?
No. Maven 2.x no longer supports plug-in configuration via properties files. Instead, in Maven 2.0 you can configure plug-ins directly from command line using the -D arguement, or from the plug-in’s POM using the <configuration> element.
How do I determine which POM contains missing transitive dependency?
run “mvn -X”
How do I integrate static (x) html into my Maven site?
You can integrate your static pages in this several steps,

  • Put your static pages in the resources directory, ${basedir}/src/site/resources.
  • Create your site.xml and put it in ${basedir}/src/site. An example below:
<project name="Maven War Plugin">
    <bannerLeft>
      <name>Maven War Plugin</name>
      <src>http://maven.apache.org/images/apache-maven-project.png</src>
      <href>http://maven.apache.org/</href>
    </bannerLeft>
    <bannerRight>
      <src>http://maven.apache.org/images/maven-small.gif</src>
    </bannerRight>
    <body>
      <links>
        <item name="Maven 2" xhref="http://maven.apache.org/maven2/"/>
      </links>

<menu name=”Overview”>
<item name=”Introduction” xhref=”introduction.html”/>
<item name=”How to Use” xhref=”howto.html”/>
</menu>
${reports}
</body>
</project>

Link the static pages by modifying the <menu> section, create items and map it with the filename of the static pages.

<menu name="Overview">
    <item name="Introduction" xhref="introduction.html"/>
    <item name="How to Use" xhref="howto.html"/>
    <item name="<put-name-here>" xhref="<filename-of-the-static-page>"/>
  </menu>

How do I run an ant task twice, against two different phases?
You can specify multiple execution elements under the executions tag, giving each a different id and binding them at different phases.

<plugin>
         <artifactId>maven-antrun-plugin</artifactId>
         <executions>
           <execution>
              * <id>one</id>*
             <phase>generate-sources</phase>
             <configuration>
               <tasks>
                 <echo message="generate-sources!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"/>
               </tasks>
             </configuration>
             <goals>
               <goal>run</goal>
             </goals>
           </execution>

<execution>
*<id>two</id>*
<phase>package</phase>
<configuration>
<tasks>
* <echo message=”package!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!”/>*

</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>

Can a profile inherit the configuration of a “sibling” profile?
No. Profiles merge when their ID’s match – so you can inherit them from a parent POM (but you can’t inherit profiles from the same POM).
Inheritence and Interpolation, Plugins and Lifecycle, POM
How do I invoke the “maven dist” function from Maven 1.0, in Maven 2.0?
mvn assembly:assembly
See the Assembly Plugin documentation for more details.
General, Plugins and Lifecycle
How do I specify which output folders the Eclipse plugin puts into the .classpath file?

<build>
  ...
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-eclipse-plugin</artifactId>
          <configuration>
            <outputDirectory>target-eclipse</outputDirectory>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  ...
  </build>

What is a Mojo?
A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more related mojos.
How to produce execution debug output or error messages?
You could call Maven with -X parameter or -e parameter. For more information, run:

mvn --help

Maven compiles my test classes but doesn’t run them?
Tests are run by the surefire plugin. The surefire plugin can be configured to run certain test classes and you may have unintentionally done so by specifying a value to ${test}. Check your settings.xml and pom.xml for a property named “test” which would like this:

  ...
    <properties>
      <property>
        <name>test</name>
        <value>some-value</value>
      </property>
   </properties>
    ...

Or

  ...
    <properties>
      <test>some-value</test>
   </properties>
    ...

How do I include tools.jar in my dependencies?
The following code includes tools.jar on Sun JDKs (it is already included in the runtime for Mac OS X and some free JDKs).

...
    <profiles>
      <profile>
        <id>default-tools.jar</id>
        <activation>
          <property>
            <name>java.vendor</name>
            <value>Sun Microsystems Inc.</value>
         </property>
       </activation>
        <dependencies>
          <dependency>
            <groupId>com.sun</groupId>
            <artifactId>tools</artifactId>
            <version>1.4.2</version>
            <scope>system</scope>
            <systemPath>${java.home}/../lib/tools.jar</systemPath>
         </dependency>
       </dependencies>
     </profile>
   </profiles>
    ...

I have a jar that I want to put into my local repository. How can I copy it in?
If you understand the layout of the maven repository, you can copy the jar directly into where it is meant to go. Maven will find this file next time it is run.
If you are not confident about the layout of the maven repository, then you can adapt the following command to load in your jar file, all on one line.

mvn install:install-file
    -Dfile=<path-to-file>
    -DgroupId=<group-id>
    -DartifactId=<artifact-id>
    -Dversion=<version>
    -Dpackaging=<packaging>
    -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
<group-id>      the group that the file should be registered under
<artifact-id>   the artifact name for the file
<version>       the version of the file
<packaging>     the packaging of the file e.g. jar

This should load in the file into the maven repository, renaming it as needed.
How do I set up Maven so it will compile with a target and source JVM of my choice?
You must configure the source and target parameters in your pom. For example, to set the source and target JVM to 1.5, you should have in your pom :

...
    <build>
    ...
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.0.2</version>
          <configuration>
            <source>1.5</source>
            <target>1.5</target>
         </configuration>
       </plugin>
     </plugins>
    ...
   </build>
    ...

How can I use Ant tasks in Maven 2?

There are currently 2 alternatives:

Maven 2.0 Eclipse Plug-in

Plugins are great in simplifying the life of programmers; it actually reduces the repetitive tasks involved in the programming. In this article our experts will show you the steps required to download and install the Maven Plugin with your eclipse IDE.
Why Maven with Eclipse
Eclipse is an industry leader in IDE market, it is used very extensively in developing projects all around the world. Similarly, Maven is a high-level, intelligent project management, build and deployment tool provided by Apache’s software foundation group. Maven deals with application development lifecycle management.

Maven–Eclipse Integration makes the development, testing, packaging and deployment process easy and fast. Maven Integration for Eclipse provides a tight integration for Maven into the IDE and avails the following features:
· It helps to launch Maven builds from within Eclipse
· It avails the dependency management for Eclipse build path based on Maven’s pom.xml
· It resolves Maven dependencies from the Eclipse workspace withoutinstalling to local Maven repository
· It avails an automatic downloading of the required dependencies from the remote Maven repositories
· It provides wizards for creating new Maven projects, pom.xml or to enable Maven support on plain Java project
· It helps to search quickly for dependencies in Maven remote repositories
· It quickly fixes in the Java editor for looking up required dependencies/jars by the class or package name.
What do you Need?
1. Get the Eclipse Development Environment :
In this tutorial we are using the eclipse-SDK-3.3-win32, which can be downloaded fromhttp://www.eclipse.org/downloads/
2. Get Maven-eclipse-plugin-plugin :
It is available at http://mevenide.codehaus.org/maven-eclipse-plugin-plugin/

Download and Install Eclipse
First download and install the eclipse plugin on your development machine then proceed with the installation process of the eclipse-maven plugin.

A Maven 2.0 Repository: An Introduction

Maven repository Types:

  • Public remote external repository: This public external repository exists at ibiblio.org and maven synchronizes with this repository.
  • Private remote internal repository: We set up this repository and make changes in the maven’s pom.xml or settings.xml file to use this repository.
  • Local repository: This repository is maintained by the developer and stays on the developer’s machine. It is synchronous to the maven repository defined in the settings.xml file that exists in the .m2 directory at its standard location i.e. C:\Documents and Settings\Administrator. If no private internal repository is setup and not listed in the pom.xml or in the setting.xml then the local repository exists on the developer’s machine is synchronized with the public maven repository at ibiblio.org.

Advantages of having an internal private repository :

  • Reduces conflicts among likelihood versions.
  • To build first time it requires less manual intervention.
  • Rather than having several separate independent libraries it provides a single central reference repository for all the dependent software libraries.
  • It quickly builds the project while using an internal repository as maven artifacts are retrieved from the intranet server rather than retrieving from the server on internet.

Use cases for maven repository:

  • It creates two sub-repository inside the internal repository.
  • Downloads ibiblio-cache from ibiblio for artifacts and make it available publically. This synchronizes with external repository from ibiblio.
  • internal-maven-repository: used for internal artifacts of an organization. It contains unique artifacts for the organization and is not synchronized with any repository.
  • Alternatively, another sub-repository that is not at ibiblio can be created for artifacts. This does not synchronize with any external repository.
  • Browse the remote repository by using a web browser.
  • Search the artifacts in the repository.
  • Download code from version control and make changes in settings.xml to point to the internal repository and build without any manual intervention.
  • Install new version of the artifacts.
  • Import artifacts into the repository in bulk.
  • Export artifacts from the repository in bulk.
  • Setup the task to backup the repository automatically.

Criteria for choosing a maven repository implementation: In ideal condition a maven repository implementation should be:

  • Free and open source
  • Provide admin tools
  • Easy to setup and use
  • Provide backup facility
  • Able to create, edit and delete sub repositories.
  • Anonymous read only access and also access control facility.
  • Deployable in any standard web server such as Tomcat or Apache.
  • Issue tracker, forums and other independent source of information.
  • Active community developers make the product enhanced and bugs fixed.
  • Bulk import/export facility to move groups of artifacts into the repository and out of the repository.
  • Provide a repository browser: should be a web browser instead of the desktop application.

Shifting from Apache Ant to Maven

Maven is entirely a different creature from Ant. Ant is simply a toolbox whereas Maven is about the application of patterns in order to achieve an infrastructure which displays the characteristics of visibility, reusability, maintainability, and comprehensibility. It is wrong to consider Maven as a build tool and just a replacement for Ant.
Ant Vs Maven
There is nothing that Maven does that Ant cannot do. Ant gives the ultimate power and flexibility in build and deployment to the developer. But Maven adds a layer of abstraction above Ant (and uses Jelly). Maven can be used to build any Java application. Today JEE build and deployment has become much standardized. Every enterprise has some variations, but in general it is all the same: deploying EARs, WARs, and EJB-JARs. Maven captures this intelligence and lets you achieve the build and deployment in about 5-6 lines of Maven script compared to dozens of lines in an Ant build script.
Ant lets you do any variations you want, but requires a lot of scripting. Maven on the other hand mandates certain directories and file names, but it provides plugins to make life easier. The restriction imposed by Maven is that only one artifact is generated per project (A project in Maven terminology is a folder with a project.xml file in it). A Maven project can have sub projects. Each sub project can build its own artifact. The topmost project can aggregate the artifacts into a larger one. This is synonymous to jars and wars put together to form an EAR. Maven also provides inheritance in projects.
Maven : Stealing the show
Maven simplifies build enormously by imposing certain fixed file names and acceptable restrictions like one artifact per project. Artifacts are treated as files on your computer by the build script. Maven hides the fact that everything is a file and forces you to think and script to create a deployable artifact such as an EAR. Artifact has a dependency on a particular version of a third party library residing in a shared remote (or local) enterprise repository, and then publish your library into the repository as well for others to use. Hence there are no more classpath issues. No more mismatch in libraries. It also gives the power to embed even the Ant scripts within Maven scripts if absolutely essential.

Maven 2.0: Features

Maven is a high-level, intelligent project management, build and deployment tool provided by Apache’s software foundation group. Maven deals with application development lifecycle management. Maven was originally developed to manage and to minimize the complexities of building the Jakarta Turbine project. But its powerful capabilities have made it a core entity of the Apache Software Foundation projects. Actually, for a long time there was a need to standardized project development lifecycle management system and Maven has emerged as a perfect option that meets the needs. Maven has become the de- facto build system in many open source initiatives and it is rapidly being adopted by many software development organizations.
Maven was borne of the very practical desire to make several projects at Apache work in a consistence manner. So that developers could freely move between these projects, knowing clearly how they all worked by understanding how one of them worked.

If a developer spent time understanding how one project built it was intended that they would not have to go through this process again when they moved on to the next project. The same idea extends to testing, generating documentation, generating metrics and reports, testing and deploying. All projects share enough of the same characteristics, an understanding of which Maven tries to harness in its general approach to project management.
On a very high level all projects need to be built, tested, packaged, documented and deployed. There occurs infinite variation in each of the above mentioned steps, but these variation still occur within the confines of a well defined path and it is this path that Maven attempts to present to everyone in a clear way. The easiest way to make a path clear is to provide people with a set of patterns that can be shared by anyone involved in a project.

The key benefit of this approach is that developers can follow one consistent build lifecycle management process without having to reinvent such processes again. Ultimately this makes developers more productive, agile, disciplined, and focused on the work at hand rather than spending time and effort doing grunt work understanding, developing, and configuring yet another non-standard build system.
Maven: Features

  1. Portable: Maven is portable in nature because it includes:
    • Building configuration using maven are portable to another machine, developer and architecture without any effort
    • Non trivial: Maven is non trivial because all file references need to be relative, environment must be completely controlled and independent from any specific file system.
  2. Technology: Maven is a simple core concept that is activated through IoC container (Plexus). Everything is done in maven through plugins and every plugin works in isolation (ClassLoader). Plugings are downloaded from a plugin-repository on demand.

Maven’s Objectives:
The primary goal of maven is to allow the developers to comprehend the complete state of a project in the shortest time by using easy build process, uniform building system, quality project management information (such as change Log, cross-reference, mailing lists, dependencies, unit test reports, test coverage reports and many more), guidelines for best practices and transparent migration to new features. To achieve to this goal Maven attempts to deal with several areas like:

  • It makes the build process easy
  • Provides a uniform building system
  • Provides quality related project information
  • Provides guidelines related to development to meet the best goal.
  • Allows transparent migration to new features.

Introduction to Maven 2.0

Maven2 is an Open Source build tool that made the revolution in the area of building projects. Like the build systems as “make” and “ant” it is not a language to combine the build components but it is a build lifecycle framework. A development team does not require much time to automate the project’s build infrastructure since maven uses a standard directory layout and a default build lifecycle. Different development teams, under a common roof can set-up the way to work as standards in a very short time. This results in the automated build infrastructure in more stable state. On the other hand, since most of the setups are simple and reusable immediately in all the projects using maven therefore many important reports, checks, build and test animation are added to all the projects. Which was not possible without maven because of the heavy cost of every project setup.

Maven 2.0 was first released on 19 October 2005 and it is not backward compatible with the plugins and the projects of maven1. In December 2005, a lot of plugins were added to maven but not all plugins that exists for maven1 are ported yet. Maven 2 is expected to stabilize quickly with most of the Open Source technologies. People are introduced to use maven as the core build system for Java development in one project and a multi-project environment. After a little knowledge about the maven, developers are able to setup a new project with maven and also become aware of the default maven project structure. Developers are easily enabled to configure maven and its plugins for a project. Developers enable common settings for maven and its plugins over multiple projects, how to generate, distribute and deploy products and reports with maven so that they can use repositories to set up a company repository. Developers can also know about the most important plugins about how to install, configure and use them, just to look for other plugins to evaluate them so that they can be integrated in their work environment.

Maven is the standard way to build projects and it also provides various other characters like clearing the definition of the project, ways to share jars across projects. It also provides the easy way to publish project information (OOS).
Originally maven was designed to simplify the building processes in the Jakarta Turbine project. Several projects were there containing their own slightly different Ant build files and JARs were checked into CVS. An apache group’s tool that can build the projects, publish project information, defines what the project consists of and that can share JARs across several projects. The result of all these requirement was the maven tool that builds and manages the java-based-project.

Why maven is a great build tool? how does it differ from other Build tools?
Tell me more about Profiles and Nodes in Maven?
Tell me more about local repositories?
How did you configured local repositories in different environment (Development, Testing , Production etc)?
What is Transcend Dependencies in maven 2?
Did you write plugins in maven? if so what are they?
Why a matrix report is required during a new release?  How does this benefit QA Team?
What are pre-scripts and post-scripts in maven? Illustrate with an example?
What are the checklists for artifacts ? and what are the checklists for source code artifact?
Tell me the experience about Static Analysis Code?

Reference:
http://www.javabeat.net

Tagged : / / / / / / / / / / / / / / / / /

Reporting Plugins in Maven | Maven Plugins That Provide Reports

reporting-plugins-in-maven

Reporting plugins
Plugins which generate reports, are configured as reports in the POM and run under the site generation
lifecycle.

This plugin consists of several reports that you can run selectively, individually or even run all of them. Please see below for instructions on how to configure your pom.xml to do this.

Run All Reports
To include all Project Info Reports in your project, you must configure your pom.xml. Use “mvn site:site” to generate the configured reports.

project


org.apache.maven.plugins
maven-project-info-reports-plugin

Run Selective Reports


org.apache.maven.plugins
maven-project-info-reports-plugin

dependencies
project-team
mailing-list
cim
issue-tracking
license
scm

Reporting plugins are configured in the POM as in this example:

org.apache.maven.plugins
maven-project-info-reports-plugin

Configuration in the reporting section also applies if plugin goals are invoked individually. The converse is not true– if you configure the plugin inside , that configuration will NOT apply to .

Configuring multiple reports for one plugin using . Each must have a unique . For more information on UMLGraph, see the UMLGraph site and this page.

org.apache.maven.plugins
maven-javadoc-plugin

uml

gr.spinellis.umlgraph.doclet.UmlGraph

gr.spinellis
UmlGraph
4.4

-views
target/uml
private

javadoc

html

private

javadoc

Plugins Type Version Release Date Description Source Repository Issue Tracking
changelog R 2.1 2007-07-25 Generate a
list of recent
changes from
your SCM.
SVN JIRA
changes B+R 2.1 2008-11-24 Generate a
report from
issue tracking
or a change
document.
SVN JIRA
checkstyle B+R 2.3 2009-07-14 Generate a
checkstyle
report.
SVN JIRA
clover B+R 2.4 2007-04-23 Generate
a Clover
report. NOTE:
Moved to
Atlassian.com
SVN JIRA
doap B 1.0 2008-08-01 Generate a
Description
of a Project
(DOAP) file
from a POM.
SVN JIRA
docck B 1.0 2008-11-16 Documentation
checker
plugin.
SVN JIRA
javadoc B+R 2.6 2009-07-29 Generate
Javadoc for
the project.
SVN JIRA
Jxr R 2.1 2007-04-05 Generate a
source cross
reference.
SVN JIRA
pmd B+R 2.4 2008-01-08 Generate a
PMD report.
SVN JIRA
projectinforeports R 2.1.2 2009-07-23 Generate
standard
project
reports.
SVN JIRA
surefirereport R 2.4.3 2008-05-14 Generate a
report based
on the results
of unit tests.
SVN JIRA

Known Plugins That Provide Reports

 

Tagged : / / / / / / / / / / / /

Properties in Maven – List of Maven Properties

properties-in-maven

Intro
It is a collection of things found in the offcial maven documentation and postings to the maven user mailing list.
Build in properties

  • ${basedir} represents the directory containing pom.xml
  • ${version} equivalent to ${project.version} or ${pom.version}

Pom/Project properties
All elements in the pom.xml, can be referenced with the project. prefix or using pom. as prefix. This list is just an example of some commonly used elements.

  • ${project.build.directory} results in the path to your “target” dir, this is the same as ${pom.project.build.directory}
  • ${project.build.outputDirectory} results in the path to your “target/classes” dir
  • ${project.name} or ${pom.name} refers to the name of the project.
  • ${project.version} or ${pom.version} refers to the version of the project.
  • ${project.build.finalName} refers to the final name of the file created when the built project is packaged

Local user settings
Similarly, values in the user’s settings.xml can be referenced using property names with settings. prefix.

  • ${settings.localRepository} refers to the path of the user’s local repository.
  • ${maven.repo.local} also works for backward compatibility with maven1 ??

Environment variables
Environment variables can be referenced using the env prefix

  • ${env.M2_HOME} returns the Maven2 installation path.
  • ${java.home} specifies the path to the current JRE_HOME environment use with relative paths to get for example:
    ${java.home}../bin/java.exe

Java system properties
All Java System Properties defined by the JVM.
Custom properties in the POM
User defined properties in the pom.xml.

hello

  • ${my.filter.value} will result in hello if you inserted the above XML fragment in your pom.xml

Parent Project variables
How can parent project variables be accessed?
You can use the prefix: ${project.parent}.
A good way to determine possible variables is to have a look directly at the API. I’m currently using Maven 2.2.1, and to access the Parent you can use ${project.parent}. This will return an org.apache.maven.project.MavenProject instance.
To access the parent version: ${parent.version}.
Reflection Properties
The pattern ${someX.someY.someZ} can simply sometimes mean getSomeX().getSomeY().getSomeZ(). Thus, properties such as ${project.build.directory} is translated to getProject().getBuild().getDirectory().
List of Maven Properties

project (from [1])
o project.distributionManagementArtifactRepository
o project.artifact
o project.parent
o project.file
o project.artifacts
o project.parentArtifact
o project.pluginArtifacts
o project.remoteArtifactRepositories
o project.pluginArtifactRepositories
o project.attachedArtifact
* settings (from [2])
o settings.offilne
o settings.interactive
* rootless (from [3])
o localRepository
o reactorProjects
* java properties (from [4])
o java.version
o java.vendor
o java.vendor.url
o java.home
o java.vm.specification.version
o java.vm.specification.vendor
o java.vm.specification.name
o java.vm.version
o java.vm.vendor
o java.vm.name
o java.specification.version
o java.specification.vendor
o java.specification.name
o java.class.version
o java.class.path
o java.library.path
o java.io.tmpdir
o java.compiler
o java.ext.dirs
o os.name
o os.arch
o os.version
o file.separator
o path.separator
o line.separator
o user.name
o user.home
o user.dir

 

Tagged : / / / / / / / / / / / / /

Profiles in Maven – How to Build Maven Profile ?

profiles-in-maven

Reference: Apache Maven,Current version User Guide

Profiles in Maven

 Use of profile:

Maven 2.0 goes to great lengths to ensure that builds are portable. Among other things, this means allowing build configuration inside the POM, avoiding all filesystem references (in inhertiance,
dependencies, and other places), and leaning much more heavily on the local repository to store the metadata needed to make this possible.

However, sometimes portability is not entirely possible. Under certain conditions, plugins may need to be configured with local filesystem paths. Under other circumstances, a slightly different
dependency set will be required, and the project’s artifact name may need to be adjusted slightly. And at still other times, you may even need to include a whole plugin in the build lifecycle depending on the detected build environment.

To address these circumstances, Maven 2.0 introduces the concept of a build profile. Profiles are specified using a subset of the elements available in the POM itself (plus one extra section), and are
triggered in any of a variety of ways. They modify the POM at build time, and are meant to be used in complementary sets to give equivalent-but-different parameters for a set of target environments
(providing, for example, the path of the appserver root in the development, testing, and production environments). As such, profiles can easily lead to differing build results from different members of your team. However, used properly, profiles can be used while still preserving project portability. This will also minimize the use of -f option of maven which allows user to create another POM with different parameters or configuration to build which makes it more maintainable since it is running with one POM only.

What are the different types of profile? Where is each defined?

• Per Project: Defined in the POM itself (pom.xml).
• Per User: Defined in the Maven-settings (%USER_HOME%/.m2/settings.xml).
• Global: Defined in the global maven-settings (%M2_HOME%/conf/settings.xml).
• Profile descriptor: a descriptor located in project basedir (profiles.xml)

How can a profile be triggered? How does this vary according to the type of profile being used?

  • A profile can be triggered/activated in several ways:
  • Explicitly
  • Through Maven settings
  • Based on environment variables
  • OS settings
  • Present or missing files

Profiles can be explicitly specified using the -P CLI option.

This option takes an argument that is a comma-delimited list of profile-ids to use. When this option is specified, no profiles other than those specified in the option argument will be activated.

mvn groupId:artifactId:goal -P profile-1,profile-2

Profiles can be activated in the Maven settings, via the section.

This section takes a list of elements, each containing a profile-id inside.

profile-1

Profiles listed in the tag would be activated by default everytime a project use it.

Profiles can be automatically triggered based on the detected state of the build environment.

These triggers are specified via an section in the profile itself. Currently, this detection is
limited to prefix-matching of the JDK version, the presence of a system property or the value of a
system property. Here are some examples.
The follwing configuration will trigger the profile when the JDK’s version starts with “1.4” (eg.
“1.4.0_08”, “1.4.2_07”, “1.4”):

1.4


The following honours versions 1.3, 1.4 and 1.5.

[1.3,1.6)


Note: an upper bound such as ,1.5] is likely not to include most releases of 1.5, since they will have an additional “patch” release such as _05 that is not taken into consideration in the above range.

This next one will activate based on OS settings.

See the Maven Enforcer Plugin for more details about OS values.

Windows XP
Windows
x86
5.1.2600


This will activate the profile when the system property “debug” is specified with any value:

debug


This example will trigger the profile when the system property “environment” is specified with the
value “test”:

environment
test


Note: Environment variable FOO would be set like env.FOO.

Present or missing files

To activate this you would type this on the command line: mvn groupId:artifactId:goal -Denvironment=test

This example will trigger the profile when the generated file target/generated-sources/axistools/wsdl2java/org/apache/maven is missing.

target/generated-sources/axistools/wsdl2java/org/apache/maven


Note: The tags and could be interpolated with some patterns like ${user.home}. Profiles can also be active by default using a configuration like the following:

profile-1

true


This profile will automatically be active for all builds unless another profile in the same pom is activated using one of the previously described methods. All profiles that are active by default are automatically deactivated when a profile in the pom is activated on the command line or through its activation config. 20.1.2.2

Deactivating a profile

Starting with Maven 2.0.10, one or more profiles can be deactivated using the command line by prefixing their identifier with either the character ‘!’ or ‘-‘ as shown below:

mvn groupId:artifactId:goal -P !profile-1,!profile-2

This can be used to deactivate profiles marked as activeByDefault or profiles that would otherwise be activated through their activation config.

Next ….? Coming Soon

Tagged : / / / / / / / / / / / /

issue Management in Maven

issuemanagement-in-maven

issueManagement

Information about the issue tracking (or bug tracking) system used to manage this project.

Element Description
system The name of the issue management system, e.g. Bugzilla
url URL for the issue management system used by the project.

Example:

Tagged : / / / / / / / / /

Introduction of Maven – Complete Guide

maven-introduction

Contents
What is Maven?
Philosophy of Maven
Benefits of Maven
High Level Features and Benefits of Maven
Download Maven
Installation Instructions
Windows 2000/XP
Unix-based Operating Systems (Linux, Solaris and Mac OS X)
Optional configuration
Settings
Settings Reference
First Maven project?

What is Maven?

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information.
At first glance Maven can appear to be many things, but in a nutshell Maven is an attempt to apply patterns to a project’s build infrastructure in order to promote comprehension and productivity by providing a clear path in the use of best practices. Maven is essentially a project management and comprehension tool and as such provides a way to help with managing:

  • Builds
  • Documentation
  • Reporting
  • Dependencies
  • SCMs
  • Releases
  • Distribution

Philosophy of Maven

Maven is generally considered by many to be a build tool. Many people who come to Maven initially are familiar with Ant so it’s a natural association but Maven is not just a build tool, and not just a replacement for Ant. Maven is an entirely different creature from Ant. Ant is simply a toolbox whereas Maven is about the application of patterns in order to achieve an infrastructure which displays the characteristics of visibility, reusability, maintainability, and comprehensibility.
Maven was borne of the very practical desire to make several projects at Apache work in the same way. So that developers could freely move between these projects, knowing clearly how they all worked by understanding how one of them worked. If a developer spent time understanding how one project built it was intended that they would not have to go through this process again when they moved on to the next project. The same idea extends to testing, generating documentation, generating metrics and reports, testing and deploying.

Benefits of Maven

  • Standardized project layout and project structure generator.
  • Standardized dependency-management mechanism.
  • Multiple project support.
  • Instant downloads of new plugins and features as the developer needs them.
  • Website generation for up-to-date project information.
  • Integration with source control: CVS and Subversion.
  • Reusability
  • scalability (lower level of additional info/code to add a new step to the build process)
  • Build lifecycle management
  • Large existing repository
  • Eclipse aware
  • Well documented (hopefully soon)
  • One directory layout,
  • A single way to define dependencies,
  • Setting up a project is really fast,
  • 99% of my needs are available out of the box,
  • build best practices enforcement (shared build meme)
  • automated build of application, from source code to pre-production platform => fast time to market with reduced risks
  • Works well with distributed teams 😉 Location doesn’t matter.
  • All artifacts are versioned and store in a repository
  • Build process is standardized for all projects
  • A lot of goals are available so it isn’t necessary to develop some specific build process part contrary to ANT we can reuse existing ANT tasks in build process with ant run plug-in
  • it provide quality project information with generated site
  • Easy to learn and use
  • Makes the build process much easier at the project level (i.e. don’t have to create very much for each project for Maven to build it correctly, and those things you do create are more declarative than functional)
  • Automatic project web sites with consistent information about each project
  • Recommended standards and best practices for project layout and definition
  • Promotes modular design of code. by making it simple to manage mulitple projects it allows the design to be laid out into multiple logical parts, weaving these parts together through the use of dependency tracking in pom files.
  • Enforces modular design of code
  • Quick project setup, no complicated build.xml files, just a POM and go

 

High Level Features and Benefits of Maven

  • Encourages best practices
  • Provides a uniform build system and consistent usage across all projects
  • Provides dependency management including automatic updating, dependency closures (also known as transitive dependencies)
  • Provides reuse of build logic
  • Defines project standard directory layout
  • Helps to reduce the duplication of dependent software libraries (jars) required to build an application
  • Stores all the software libraries or artifacts in a remote stores called a Maven repositories

Download Maven

Maven is distributed in several formats for your convenience. Maven 2.2.1 is distributed under the Apache License, version 2.0.
Download link: http://maven.apache.org/download.html

Installation Instructions

System Requirements
JDK 1.5 or above (this is to execute Maven – it still allows you to build against 1.3 and prior JDK’s)
Memory No minimum requirement
Disk No minimum requirement. Approximately 100MB will be used for your local repository, however this will vary depending on usage and can be removed and redownloaded at any time.
Operating System No minimum requirement. On Windows, Windows NT and above or Cygwin is required for the startup scripts. Tested on Windows XP, Fedora Core and Mac OS X.
Maven is a Java tool, so you must have Java installed in order to proceed. More precisely, you need a Java Development Kit (JDK), the Java Runtime Environment (JRE) is not sufficient.
Additional optional installation steps are listed after the platform specific instructions.

Windows 2000/XP

  • Unzip the distribution archive, i.e. apache-maven-2.2.1-bin.zip to the directory you wish to install Maven 2.2.1. These instructions assume you chose C:\Program Files\Apache Software Foundation. The subdirectory apache-maven-2.2.1 will be created from the archive.
  • Add the M2_HOME environment variable by opening up the system properties (WinKey + Pause), selecting the “Advanced” tab, and the “Environment Variables” button, then adding the M2_HOME variable in the user variables with the value C:\Program Files\Apache Software Foundation\apache-maven-2.2.1. Be sure to omit any quotation marks around the path even if it contains spaces. Note: For Maven < 2.0.9, also be sure that the M2_HOME doesn’t have a ‘\’ as last character.
  • In the same dialog, add the M2 environment variable in the user variables with the value %M2_HOME%\bin.
  • Optional: In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.
  • In the same dialog, update/create the Path environment variable in the user variables and prepend the value %M2% to add Maven available in the command line.
  • In the same dialog, make sure that JAVA_HOME exists in your user variables or in the system variables and it is set to the location of your JDK, e.g. C:\Program Files\Java\jdk1.5.0_02 and that %JAVA_HOME%\bin is in your Path environment variable.
  • Open a new command prompt (Winkey + R then type cmd) and run mvn –version to verify that it is correctly installed.

Unix-based Operating Systems (Linux, Solaris and Mac OS X)

  • Extract the distribution archive, i.e. apache-maven-2.2.1-bin.tar.gz to the directory you wish to install Maven 2.2.1. These instructions assume you chose /usr/local/apache-maven. The subdirectory apache-maven-2.2.1 will be created from the archive.
  • In a command terminal, add the M2_HOME environment variable, e.g. export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1.
  • Add the M2 environment variable, e.g. export M2=$M2_HOME/bin.
  • Optional: Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS=”-Xms256m -Xmx512m”. This environment variable can be used to supply extra options to Maven.
  • Add M2 environment variable to your path, e.g. export PATH=$M2:$PATH.
  • Make sure that JAVA_HOME is set to the location of your JDK, e.g. export JAVA_HOME=/usr/java/jdk1.5.0_02 and that $JAVA_HOME/bin is in your PATH environment variable.
  • Run mvn –version to verify that it is correctly installed.

 

Optional configuration

Maven will work for most tasks with the above configuration, however if you have any environmental specific configuration outside of individual projects then you will need to configure settings. The following sections refer to what is available.

Settings

Maven has settings file located in the Maven installation and/or user home directory that configure environmental specifics such as:

  • HTTP proxy server
  • repository manager location
  • server authentication and passwords
  • other configuration properties

Settings Reference

The settings element in the settings.xml file contains elements used to define values which configure Maven execution in various ways, like the pom.xml, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:

    • The Maven install: $M2_HOME/conf/settings.xml
    • A user’s install: ${user.home}/.m2/settings.xml

Here is an overview of the top elements under settings:

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd”>

 

localRepository: This value is the path of this build system’s local repository. The default value is ${user.home}/.m2/repository. This element is especially useful for a main build server allowing all logged-in users to build from a common local repository.

interactiveMode: true if Maven should attempt to interact with the user for input, false if not. Defaults to true.

usePluginRegistry: true if Maven should use the ${user.home}/.m2/plugin-registry.xml file to manage plugin versions, defaults to false. Note that for the current version of Maven 2.0, the plugin-registry.xml file should not be depended upon. Consider it dormant for now.

offline: true if this build system should operate in offline mode, defaults to false. This element is useful for build servers which cannot connect to a remote repository, either because of network setup or security reasons.

pluginGroups: This element contains a list of pluginGroup elements, each contains a groupId. The list is searched when a plugin is used and the groupId is not provided in the command line. This list automatically contains org.apache.maven.plugins and org.codehaus.mojo. For example, given the above settings the Maven command line may execute org.mortbay.jetty:jetty-maven-plugin:run with the truncated command:

Servers
The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

Mirrors
epositories are declared inside a project, which means that if you have your own custom repositories, those sharing your project easily get the right settings out of the box. However, you may want to use an alternative mirror for a particular repository without changing the project files.

Some reasons to use a mirror are:

There is a synchronized mirror on the internet that is geographically closer and faster
You want to replace a particular repository with your own internal repository which you have greater control over
You want to run maven-proxy to provide a local cache to a mirror and need to use its URL instead

Proxies: This is basically used for proxies’ setup

Profiles
The profile element in the settings.xml is a truncated version of the pom.xml profile element. It consists of the activation, repositories, pluginRepositories and properties elements. The profile elements only include these four elements because they concerns themselves with the build system as a whole (which is the role of the settings.xml file), not about individual project object model settings.

If a profile is active from settings, its values will override any equivalently ID’d profiles in a POM or profiles.xml file.

First Maven project?

To create our first Maven project we are going to use Maven’s archetype mechanism. An archetype is defined as an original pattern or model from which all other things of the same kind are made. In Maven, an archetype is a template of a project which is combined with some user input to produce a working Maven project that has been tailored to the user’s requirements.

On to creating your first project! In order to create the simplest of Maven projects, execute the following from the command line:

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.mycompany.app -DartifactId=my-app

Once you have executed this command, you will notice a few things have happened. First, you will notice that a directory named my-app has been created for the new project, and this directory contains a file named pom.xml that should look like this:

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd”>
4.0.0
com.mycompany.app
my-app
jar 1.0-SNAPSHOT
Maven Quick Start Archetype
http://maven.apache.org

junit
junit
3.8.1
test

pom.xml contains the Project Object Model (POM) for this project. The POM is the basic unit of work in Maven. This is important to remember because Maven is inherently project-centric in that everything revolves around the notion of a project. In short, the POM contains every important piece of information about your project and is essentially one-stop-shopping for finding anything related to your project.

This is a very simple POM but still displays the key elements every POM contains, so let’s walk through each of them to familiarize you with the POM essentials:

project: This is the top-level element in all Maven pom.xml files.
modelVersion: This element indicates what version of the object model this POM is using. The version of the model itself changes very infrequently but it is mandatory in order to ensure stability of use if and when the Maven developers deem it necessary to change the model.

groupId: This element indicates the unique identifier of the organization or group that created the project. The groupId is one of the key identifiers of a project and is typically based on the fully qualified domain name of your organization. For example org.apache.maven.plugins is the designated groupId for all Maven plug-ins.

artifactId: This element indicates the unique base name of the primary artifact being generated by this project. The primary artifact for a project is typically a JAR file. Secondary artifacts like source bundles also use the artifactId as part of their final name. A typical artifact produced by Maven would have the form -. (for example, myapp-1.0.jar).

packaging: This element indicates the package type to be used by this artifact (e.g. JAR, WAR, EAR, etc.). This not only means if the artifact produced is JAR, WAR, or EAR but can also indicate a specific lifecycle to use as part of the build process. (The lifecycle is a topic we will deal with further on in the guide. For now, just keep in mind that the indicated packaging of a project can play a part in customizing the build lifecycle.) The default value for the packaging element is JAR so you do not have to specify this for most projects.

version: This element indicates the version of the artifact generated by the project. Maven goes a long way to help you with version management and you will often see the SNAPSHOT designator in a version, which indicates that a project is in a state of development. We will discuss the use of snapshots and how they work further on in this guide.

name: This element indicates the display name used for the project. This is often used in Maven’s generated documentation.

url: This element indicates where the project’s site can be found. This is often used in Maven’s generated documentation.

description: This element provides a basic description of your project. This is often used in Maven’s generated documentation.

 

Tagged : / / / / / / / / / / / / / /