maven

  • submit to reddit

Apache Maven 2

By Matthew McCullough

34,900 Downloads · Refcard 55 of 151 (see them all)

Download
FREE PDF


The Essential Maven 2 Cheat Sheet

Maven is a comprehensive project information tool whose most common application is building Java code. It is receiving renewed recognition in the emerging development space for its convention over configuration approach to builds. This DZone Refcard showcases how Maven offers unparalleled software lifecycle management, and gives Java developers a wide range of execution commands, tips for debugging Mavenized builds, and a clear introduction to the "Maven vocabulary". This Refcard also covers the MVN command, dependencies, plugins, profiles and more. Download it today!
HTML Preview
Apache Maven 2

Apache Maven 2

By Matthew McCullough

ABOUT APACHE MAVEN

Maven is a comprehensive project information tool, whose most common application is building Java code. Maven is often considered an alternative to Ant, but as you’ll see in this Refcard, it offers unparalleled software lifecycle management, providing a cohesive suite of verification, compilation, testing, packaging, reporting, and deployment plugins.

Maven is receiving renewed recognition in the emerging development space for its convention over configuration approach to builds. This Refcard aims to give JVM platform developers a range of basic to advanced execution commands, tips for debugging Mavenized builds, and a clear introduction to the “Maven vocabulary”.

Interoperability and Extensibility

New Maven users are pleasantly surprised to find that Maven offers easy-to-write custom build-supplementing plugins, reuses any desired aspect of Ant, and can compile native C, C++, and .NET code in addition to its strong support for Java and JVM languages and platforms, such as Scala, JRuby, Groovy and Grails.

Hot Tip

All things Maven can be found at http://maven.apache.org

THE MVN COMMAND

Maven supplies a Unix shell script and MSDOS batch file named mvn and mvn.bat respectively. This command is used to start all Maven builds. Optional parameters are supplied in a space-delimited fashion. An example of cleaning and packaging a project, then running it in a Jetty servlet container, yet skipping the unit tests, reads as follows:


mvn clean package jetty:run –Dmaven.test.skip

PROJECT OBJECT MODEL

The world of Maven revolves around metadata files named pom.xml. A file of this name exists at the root of every Maven project and defines the plugins, paths and settings that supplement the Maven defaults for your project.

Basic pom.xml Syntax

The smallest valid pom.xml, which inherits the default artifact type of “jar”, reads as follows:


<project>
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.ambientideas</groupId>
	<artifactId>barestbones</artifactId>
	<version>1.0-SNAPSHOT</version>
</project>

Super POM

The Super POM is a virtual pom.xml file that ships inside the core Maven JARs, and provides numerous default settings. All projects automatically inherit from the Super POM, much like the Object super class in Java. Its contents can be viewed in one of two ways:

View Super POM via SVN

Open the following SVN viewing URL in your web browser:


http://svn.apache.org/repos/asf/maven/components/branches/maven-2.1.x/pom.xml

View Super POM via effective-pom

Run the following command in a directory that contains the most minimal Maven project pom.xml, listed above.


mvn help:effective-pom

Multi-module Projects

Maven showcases exceptional support for componentization via its concept of multi-module builds. Place sub-projects in sub-folders beneath your top level project and reference each with a module tag. To build all sub projects, just execute your normal mvn command and goals from a prompt in the top-most directory.


<project>
  <!-- ... -->
  <packaging>pom</packaging>
  <modules>
    <module>servlets</module>
    <module>ejbs</module>
    <module>ear</module>
  </modules>
</project>

Artifact Vector

Each Maven project produces an element, such as a JAR, WAR or EAR, uniquely identified by a composite of fields known as groupId, artifactId, packaging, version and scope. This vector of fields uniquely distinguishes a Maven artifact from all others.

Many Maven reports and plugins print the details of a specific artifact in this colon separated fashion:


groupid:artifactid:packaging:version:scope

An example of this output for the core Spring JAR would be:


org.springframework:spring:jar:2.5.6:compile

EXECUTION GROUPS

Maven divides execution into four nested hierarchies. From most-encompassing to most-specific, they are: Lifecycle, Phase, Plugin, and Goal.

Lifecycles, Phases, Plugins and Goals

Maven defines the concept of language-independent project build flows that model the steps that all software goes through during a compilation and deployment process.

Lifecycles

Lifecycles represent a well-recognized flow of steps (Phases) used in software assembly.

Each step in a lifecycle flow is called a phase. Zero or more plugin goals are bound to a phase.

A plugin is a logical grouping and distribution (often a single JAR) of related goals, such as JARing.

A goal, the most granular step in Maven, is a single executable task within a plugin. For example, discrete goals in the jar plugin include packaging the jar (jar:jar), signing the jar (jar:sign), and verifying the signature (jar:sign-verify).

Executing a Phase or Goal

At the command prompt, either a phase or a plugin goal can be requested. Multiple phases or goals can be specified and are separated by spaces.


If you ask Maven to run a specific plugin goal, then only that goal is run. This example runs two plugin goals: compilation of code, then JARing the result, skipping over any intermediate steps. mvn compile:compile jar:jar

Conversely, if you ask Maven to execute a phase, all phases and bound plugin goals up to that point in the lifecycle are also executed. This example requests the deploy lifecycle phase, which will also execute the verification, compilation, testing and packaging phases.


mvn deploy

Online and Offline

During a build, Maven attempts to download any uncached referenced artifacts and proceeds to cache them in the ~/.m2/repository directory on Unix, or in the %USERPROFILE%/.m2/repository directory on Windows.

To prepare for compiling offline, you can instruct Maven to download all referenced artifacts from the Internet via the command:


mvn dependency:go-offline

If all required artifacts and plugins have been cached in your local repository, you can instruct Maven to run in offline mode with a simple flag:


mvn <phase or goal> -o

Built-in Maven Lifecycles

Maven ships with three lifecycles; clean, default, and site. Many of the phases within these three lifecycles are bound to a sensible plugin goal.

Hot Tip

The official lifecycle reference, which extensively lists all the default bindings, can be found at http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

The clean lifecycle is simplistic in nature. It deletes all generated and compiled artifacts in the output directory.

Clean Lifecycle
Lifecycle Phase Purpose
pre-clean
clean Remove all generated and compiled artifacts in preperation for a fresh build.
post-clean
Default Lifecycle
Lifecycle Phase Purpose
validate Cross check that all elements necessary for the build are correct and present.
initialize Set up and bootstrap the build process.
generate-sources Generate dynamic source code
process-sources Filter, sed and copy source code
generate-resources Generate dynamic resources
process-resources Filter, sed and copy resources files.
compile Compile the primary or mixed language source files.
process-classes Augment compiled classes, such as for code-coverage instrumentation.
generate-test-sources Generate dynamic unit test source code.
process-test-sources Filter, sed and copy unit test source code.
generate-test-resources Generate dynamic unit test resources.
process-test-resources Filter, sed and copy unit test resources.
test-compile Compile unit test source files
test Execute unit tests
prepare-package Manipulate generated artifacts immediately prior to packaging. (Maven 2.1 and above)
package Bundle the module or application into a distributable package (commonly, JAR, WAR, or EAR).
pre-integration-test
integration-test Execute tests that require connectivity to external resources or other components
post-integration-test
verify Inspect and cross-check the distribution package (JAR, WAR, EAR) for correctness.
install Place the package in the user’s local Maven repository.
deploy Upload the package to a remote Maven repository

The site lifecycle generates a project information web site, and can deploy the artifacts to a specified web server or local path.

Site Lifecycle
Lifecycle Phase Purpose
pre-site Cross check that all elements necessary for the build are correct and present.
site Generate an HTML web site containing project information and reports.
post-site
site-deploy Upload the generated website to a web server

Default Goal

The default goal codifies the author’s intended usage of the build script. Only one goal or lifecycle can be set as the default. The most common default goal is install.


<project>
   [...]
   <build>
      lt;defaultGoal>install</defaultGoal>
   </build>
   [...]
</project>

HELP

Help for a Plugin

Lists all the possible goals for a given plugin and any associated documentation.


help:describe -Dplugin=<pluginname>

Help for POMs

To view the composite pom that’s a result of all inherited poms:


mvn help:effective-pom

Help for Profiles

To view all profiles that are active from either manual or automatic activation:


mvn help:active-profiles

DEPENDENCIES

Declaring a Dependency

To express your project’s reliance on a particular artifact, you declare a dependency in the project’s pom.xml.

Hot Tip

You can use the search engine at repository.sonatype.org to find dependencies by name and get the xml necessary to paste into your pom.xml

<project>
  <dependencies>
    <dependency>
	 <groupId>com.yourcompany</groupId>
	 <artifactId>yourlib</artifactId>
         <version>1.0</version>
	 <type>jar</type>
	 <scope>compile</scope>
    </dependency>
   </dependencies>
  <!-- ... -->
</project>

Standard Scopes

Each dependency can specify a scope, which controls its visibility and inclusion in the final packaged artifact, such as a WAR or EAR. Scoping enables you to minimize the JARs that ship with your product.

Scope Description
compile Needed for compilation, included in packages.
test Needed for unit tests, not included in packages.
provided Needed for compilation, but provided at runtime by the runtime container.
system Needed for compilation, given as absolute path on disk, and not included in packages.
import An inline inclusion of a POM-type artifact facilitating dependency-declaring POM snippets.

PLUGINS

Adding a Plugin

A plugin and its configuration are added via a small declaration, very similar to a dependency, in the <build> section of your pom.xml.


<build>
  <!-- ... -->
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <maxmem>512m</maxmem>
     </configuration>
    </plugin>
  </plugins>
</build>

Common Plugins

Maven created an acronym for its plugin classes that aggregates “Plain Old Java Object” and “Maven Java Object” into the resultant word, Mojo.

There are dozens of Maven plugins, but a handful constitute some of the most valuable, yet underused features:

surefire Runs unit tests.
checkstyle Checks the code’s styling
clover Code coverage evaluation.
enforcer Verify many types of environmental conditions as prerequisites.
assembly Creates ZIPs and other distribution packages of apps and their transitive dependency JARs.

Hot Tip

The full catalog of plugins can be found at: http://maven.apache.org/plugins/index.html

VISUALIZE DEPENDENCIES

Users often mention that the most challenging task is identifying dependencies: why they are being included, where they are coming from and if there are collisions. Maven has a suite of goals to assist with this.

List a hierarchy of dependencies.


mvn dependency:tree

List dependencies in alphabetic form.


mvn dependency:resolve

List plugin dependencies in alphabetic form.


mvn dependency:resolve-plugins

Analyze dependencies and list any that are unused, or undeclared.


mvn dependency:analyze

REPOSITORIES

Repositories are the web sites that host collections of Maven plugins and dependencies.

Declaring a Repository


<repositories>
  lt;repository>
  <id>JavaDotNetRepo</id>
    <url>https://maven-repository.dev.java.net</url>
  </repository>
</repositories>

The Maven community strongly recommends using a repository manager such as Nexus to define all repositories. This results in cleaner pom.xml files and centrally cached and managed connections to external artifact sources. Nexus can be downloaded from http://nexus.sonatype.org/

Popular Repositories

Central http://repo1.maven.org/maven2/
Java.net https://maven-repository.dev.java.net/
Codehaus http://repository.codehaus.org/
JBoss http://repository.jboss.org/maven2

Hot Tip

A near complete list of repositores can be found at http://www.mvnbrowser.com/repositories.html

PROPERTY VARIABLES

A wide range of predefined or custom of property variables can be used anywhere in your pom.xml files to keep string and path repetition to a minimum.

All properties in Maven begin with ${ and end with }. To list all available properties, run the following command.


mvn help:expressions

Predefined Properties (Partial List)

${env.PATH} Any OS environment variable such as EDITOR, or GROOVY_HOME. Specifically, the PATH environment variable.
${project.groupId} Any project node from the aggregated Maven pom.xml. Specifically, the Group ID of the project
${project.artifactId} Name of the artifact.
${project.basedir} Path of the pom.xml.
${settings.localRepository} The path to the user’s local repository.
${java.home} Any Java System Property. Specifically, the Java System Property path to its home.
${java.vendor} The Java System Property declaring the JRE vendor’s name.
${my.somevar} A user-defined variable.

Project properties could previously be referenced with a ${pom.basedir} prefix or no prefix at all ${basedir}. Maven now requires that you prefix these variables with the word project ${project.basedir}.

Define a Property

You can define a new custom property in your pom.xml like so:


<project>
   [...]
   <properties>
      <my.somevar>My Value</my.somevar>
   </properties>
   [...]
</project>

DEBUGGING

Exception Full Stack Traces

If a Maven plugin is reporting an error, to see the full detail of the exception’s stack trace run Maven with the -e flag.


mvn <yourgoal> -e

Output Debugging Info

Whenever reporting a Maven bug, or troubleshooting a problem, turn on all the debugging info by running Maven like so:


mvn <yourgoal> -X

Debug Maven Core/Plugins

Core Maven operations and plugins can be stepped through with any JPDA-compatible debugger, the most common option being Eclipse. When run in debug mode, Maven will wait for you to connect your debugger to socket port 8000 before continuing with its lifecycle.


mvnDebug <yourgoal>
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000

Debug a Unit Test

Your suite or an individual unit test can be debugged in much the same fashion by telling the Surefire test-execution plugin to wait for you to attach a debugger to port 5005.


mvn test -Dmaven.surefire.debug
Listening for transport dt_socket at address: 5005

SOURCE CODE MANAGEMENT

Configuring SCM

Your project’s SCM connection can be quickly configured with just three XML tags, which adds significant capabilities to the scm, release, and reactor plugins.

The connection tag is your read-only view of your repository and developerConnection is the writable link. URL is your web-based view of the source.


<scm>
  <connection>scm:svn:http://myvendor.com/ourrepo/trunk</
connection>
  <developerConnection>
     scm:svn:https://myvendor.com/ourrepo/trunk
  </developerConnection>
  <url>http://myvendor.com/viewsource.pl</url>
</scm>

Hot Tip

Over 12 SCM systems are supported by Maven. The full list can be viewed at http://docs.codehaus.org/display/SCM/SCM+Matrix

Using the SCM Plugin

The core SCM plugin offers two highly useful goals.

The diff command produces a standard Unix patch file with the extension .diff of the pending (uncommitted) changes on disk that can be emailed or attached to a bug report.


mvn scm:diff

The update-subprojects goal invokes a recursive scm-provider specific update (svn update, git pull) across all the submodules of a multimodule project.


mvn scm:update-subprojects

PROFILES

Profiles are a means to conditionally turn on portions of Maven configuration, including plugins, pathing and configuration.

The most common uses of profiles are for Windows/Unix platform-specific variations and build-time customization of JAR dependencies based on the use of a specific Weblogic, Websphere or JBoss J2EE vendor.


<project>
     [...]
  <profiles>
    <profile>
      <id>YourProfile</id>
         [...settings, build, plugins etc...]
      <dependencies>
        <dependency>
          <groupId>com.yourcompany</groupId>
          <artifactId>yourlib</artifactId>
       </dependency>
      <dependencies>
   </profile>
 </profiles>
[...]
</project>

Profile Definition Locations

Profiles can be defined in pom.xml, profiles.xml (parallel to the pom.xml), ~/.m2/settings.xml, or $M2_HOME/conf/settings.xml.

Hot Tip

The full Maven Profile reference, including details about when to use each of the profile definition files, can be found at http://maven.apache.org/guides/introduction/introduction-to-profiles.html

PROFILE ACTIVATION

Profiles can be activated manually from the command line or through an activation rule (OS, file existence, Maven version, etc.). Profiles are primarily additive, so best practices suggest leaving most off by default, and activating based on specific conditions.

Manual Profile Activation


mvn <yourgoal> –P YourProfile

Automatic Profile Activation


<project>
     [...]
 <profiles>
   <profile>
     <id>YourProfile</id>
     [...settings, build, etc...]
  <activation>
    <os>
      <name>Windows XP</name>
      <family>Windows</family>
      <arch>x86</arch>
      <version>5.1.2600</version>
   </os>
    <file>
       <missing>somefolder/somefile.txt</missing>
    </file>
  </activation>
</profile>
</profiles>
[...]
</project>

CUTTING A RELEASE

Maven offers excellent automation for cutting a release of your project. In short, this is a plugin-guided ceremony for verifying that all tests pass, tagging your source code repository, and altering the POMs to reflect a product version increment.

The prepare goal runs the unit tests, continuing only if all pass, then increments the value in the pom <version> tag to a release version, tags the source repository accordingly, and increments the pom version tag back to a SNAPSHOT version.


mvn release:prepare

After a release has been successfully prepared, run the perform goal. This goal checks out the prepared release and deploys it to the POM’s specified remote Maven repository for consumption by other teams and Maven builds.


mvn release:perform

ARCHETYPES

An archetype is a powerful template that uses your corporate Java package names and project name in the instantiated project and establishes a baseline of dependencies, with a bonus of basic sample code.

You can leverage public archetypes for quickly starting a project that uses a familiar stack, such as Struts+Spring, or Tapestry+Hibernate. You can also create private archetypes within your company to offer new projects a level of consistent dependencies matching your approved corporate technology stack.

Using an Archetype

The default behavior of the generate goal is to bring up a menu of choices. You are then prompted for various replaceables such as package name and artifactId. Type this command, then answer each question at the command line prompt.


mvn archetype:generate

Creating Archetypes

An archetype can be created from an existing project, using it as the pattern by which to build the template. Run the command from the root of your existing project.


mvn archetype:create-from-project

Archetype Catalogs

The Maven Archetype plugin comes bundled with a default catalog of applications it can create, but other projects on the Internet also publish catalogs. To use an alternate catalog:


mvn archetype:generate –DarchetypeCatalog=<catalog>

A list of the most commonly used catalogs is as follows:


local
remote
http://repo.fusesource.com/maven2
http://cocoon.apache.org
http://download.java.net/maven/2


http://myfaces.apache.org
http://tapestry.formos.com/maven-repository
http://scala-tools.org
http://www.terracotta.org/download/reflector/maven2/

REPORTS

Maven has a robust offering of reporting plugins, commonly run with the site generation phase, that evaluate and aggregate information about the project, contributors, it’s source, tests, code coverage, and more.

Adding a Report Plugin


<:reporting>
 <:plugins>
    <:plugin>
      <:artifactId>maven-javadoc-plugin<:/artifactId>
    <:/plugin>
  <:/plugins>
<:/reporting>

Hot Tip

A list of commonly used reporting plugins can be reviewed here http://maven.apache.org/plugins/

About The Author

Photo of MatthewMcCullough

Matthew McCullough

Matthew McCullough is an Open Source Architect with the Denver, Colorado consulting firm Ambient Ideas, LLC which he co-founded in 1997. He’s spent the last 13 years passionately aiming for ever-greater efficiencies in software development, all while exploring how to share these practices with his clients and their team members. Matthew is a nationally touring speaker on all things open source and has provided long term mentoring and architecture services to over 40 companies ranging from startups to Fortune 500 firms. Feedback and questions are always welcomed at matthewm@ambientideas.com

Recommended Book

Maven

Several sources for Maven have appeared online for some time, but nothing served as an introduction and comprehensive reference guide to this tool -- until now. Maven: The Definitive Guide is the ideal book to help you manage development projects for software, webapplications, and enterprise applications. And it comes straight from the source.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

RichFaces 4.0

A Next Generation JSF Framework

By Nick Belaevski, Ilya Shailkovsky, Max Katz and Jay Balunas

11,848 Downloads · Refcard 138 of 151 (see them all)

Download
FREE PDF


The Essential RichFaces 4 Cheat Sheet

RichFaces 4.0 is an advanced JSF 2.0 based framework that provides a complete range of rich Ajax enabled UI components as well as a component development kit, dynamic resource support, and skinning. The 4.0 release brings complete JSF 2.0 support to the project. This DZone Refcard will get you started with RichFaces 4.0 and introduce the core JSF 2 extensions, render options, queue, client-side validation, rich tags, client functions, and skinning. It will also cover the component development kit, the rich components JavaScript API, and even Google AppEngine Support.
HTML Preview
RichFaces 4.0 A Next Generation JSF Framework

RichFaces 4.0: A Next Generation JSF Framework

By Nick Belaevski, Ilya Shailkovsky, Max Katz, and Jay Balunas

INTRODUCTION

RichFaces 4.0 is an advanced JSF 2.0 based framework that provides a complete range of rich Ajax enabled UI components, as well as other features such as a component development kit, dynamic resource support, and skinning. The 4.0 version brings complete JSF 2.0 support to the project.

RichFaces is made up of two component tag libraries. “a4j:” represents core Ajax functionality, and page wide controls. While the “rich:” component set represent self contained and advanced UI components such as calendars, and trees.

JavaServer Faces 2.0

The second version of JSF added many features such as, core Ajax functionality, integrated Facelets support, annotations, view parameters, and more. RichFaces 4.0 has been specifically redesigned to not only work with these new features, but to extend them.

Hot Tip

JSF 2.0 is covered in detail in the DZone JavaServer Faces 2.0 Refcard.

GETTING STARTED

RichFaces can be used in any container that JSF 2.0 is compatible with. This means all servers compliant with the EE6 specification ( JBoss AS6/7, Glassfish 3 ) and all major servlet containers (Tomcat, Jetty).

Hot Tip

Check the RichFaces project page for the latest information and downloads: http://richfaces.org

Installing RichFaces

Since RichFaces is build on top of JSF 2.0 its installation is as easy as adding a few jars to your project.

For Maven-based projects configure your repositories following the Maven Getting Started Guide here:
http://community.jboss.org/wiki/MavenGettingStarted-Users

Then simply add the following to you projects pom.xml.


<dependencyManagement>
  <dependencies>
   	<dependency>
	  <groupId>org.richfaces</groupId>
	  <artifactId>richfaces-bom</artifactId>
	  <version>${richfaces.version}</version>
	  <scope>import</scope>
	  <type>pom</type>
	</dependency>
  </dependencies>
</dependencyManagement>
…
<dependency>
  <groupId>org.richfaces.ui</groupId>
  <artifactId>richfaces-components-ui</artifactId>
</dependency>
<dependency>
  <groupId>org.richfaces.core</groupId>
  <artifactId>richfaces-core-impl</artifactId>
</dependency>

For other build systems such as Ant just add the following jars to your projects WEB-INF/lib directory: richfaces-core-api-<ver>.jar, richfaces-core-impl-<ver>.jar, richfaces-components-api-<ver>.jar, richfaces-components-ui-<ver>.jar, sac-1.3.jar, cssparser-0.9.5.jar, and google-guava-r08.jar.

Hot Tip

No filters or other updates to your web.xml are needed to install RichFaces 4.0.

Page Setup

To use RichFaces components in your views add:


xmlns:a4j=”http://richfaces.org/a4j”
xmlns:rich=”http://richfaces.org/rich”

Maven Archetypes

The project also contains several Maven archetypes to quickly create projects (including one for Google App Engine targeted project).

Simple project generation:

mvn archetype:generate
-DarchetypeGroupId=org.richfaces.archetypes
-DarchetypeArtifactId=richfaces-archetype-simpleapp
-DarchetypeVersion=<version> -DgroupId=<yourGroupId>
-DartifactId=<yourArtifactId> -Dversion=<yourVersion>

From the generated project directory you can build, and deploy as with any Maven project.

Hot Tip

Easily import in JBoss Tools using m2eclipse http://jboss.org/tools.

CORE JSF 2 EXTENSIONS

a4j:ajax

Upgrades the standard f:ajax tag/behavior with more features.


<h:inputText value=”#{bean.input}”>
  <a4j:ajax execute=”#{bean.process}” render=”#{bean.update}”/>
</h:inputText>
<h:panelGrid id=”list1”>...</h:panelGrid>

Execute & Render EL Resolution

JSF 2.0 determines the values for execute and render attributes when the current view is rendered. In the example above if #{bean.update} changes on the server the older value will be used. RichFaces processes attribute values on the server side so you will always be using the most current value.

Addition Common Enhancements

All RichFaces components that fire Ajax requests share the features above, and all of the ones from below:

Attribute Description
limitRender Turns off all auto-rendered panels (see Render Options section).
bypassUpdates When set to true, skips Update Model and Invoke Application phases. Useful for form validation requests.
onbegin JavaScript code to be invoked before Ajax request is sent.
onbeforedomupdate JavaScript code to be invoked after response is received but before Ajax updates happen.
oncomplete JavaScript code to be invoked after Ajax request processing is complete.
status Name of status component to show during Ajax request.

a4j:commandButton, a4j:commandLink

Similar to standard h:commandButton and h:commandLink tags but with Ajax behavior built-in.


<a4j:commandButton value=”Add”
  action=”#{bean.add}” render=”cities”/>
<h:panelGrid id=”cities”>...</h:panelGrid>

Hot Tip

Default execute value for both controls is @form.

a4j:poll

Periodically fires an Ajax request based on polling interval defined via interval attribute and can be enabled/disabled via enabled attribute (true|false). For example, in the following code snippet, an Ajax request will be sent every 2 seconds and render the time component:


<a4j:poll interval=”2000” enabled=”#{bean.active}”
	action=”#{bean.count}” render=”time”/>
<h:outputText id=”time” value=”#{bean.time}”/>

a4j:jsFunction

Allows the sending of an Ajax request from any JavaScript function.


<a4j:jsFunction name=”setdrink” render=”drink”>
  <a4j:param name=”param1” assignTo=”#{bean.drink}”/>
</a4j:jsFunction>
...
<td onmouseover=”setdrink(‘Espresso’)”
	onmouseout=”setdrink(‘’)”>Espresso</td>
<h:outputText id=”drink” value=”I like #{bean.drink}” />

When the mouse hovers or leaves a drink, the setdrink() JavaScript function is called. The function is defined by an a4j:jsFunction tag which sets up standard Ajax call. You can also invoke an action. The drink parameter is passed to the server via a4j:param tag.

a4j:status

Displays Ajax request status. The component can display content based on Ajax start, stop, and error conditions. Status can be defined in the following three ways: status per view, status per form and named statuses. The following example shows named status:


<a4j:status name=”ajaxStatus”>
	<f:facet name=”start”>
	  <h:graphicImage value=”/ajax.gif” />
	</f:facet>
</a4j:status>
<a4j:commandButton value=”Save” status=”ajaxStatus”/>

All RichFaces controls which fire an Ajax request have status attribute available.

a4j:repeat

Works just like ui:repeat but also supports partial table update (see Data Iteration):


<ul>
 <a4j:repeat value=”#{bean.list}” var=”city”>
	<li>#{city.name}</li>
 </a4j:repeat>
</ul>

a4j:push

“Push” server-side events to client using Comet or WebSockets. This is implemented using Atmosphere (http://atmosphere.java.net), and uses JMS for message processing (such as JBoss’s HornetQ - http://www.jboss.org/hornetq). This provides excellent integration with EE containers, and advanced messaging services.

The <a4j:push> tag allows you to define named topics for messages delivery and actions to perform:


<a4j:push address=”topic@chat”
	ondataavailable=”alert(event.rf.data)” />

Server side messages are published and topics are created/configured using a class similar to this:


@PostConstruct
public void init() {
	topicsContext = TopicsContext.lookup();
}
private void say(String message) throws
	MessageException {
	TopicKey key = new TopicKey(“chat”,”topic”);
	topicsContext.publish(key, message);
}
private void onStart() {
	topicsContext.getOrCreateTopic(new
		TopicKey(“chat”));
}	

For more details on usage and setup, including examples please see the RichFaces Component Guide (http://docs.jboss.org/richfaces/latest_4_0_X/Component_Reference/en-US/html/).

a4j:param

Works like <f:param> also allows client side parameters and will assign a value automatically to a bean property set in assignTo :


<a4j:commandButton value=”Select”>
  <a4j:param value=”#{rowIndex}”
	assignTo=”#{bean.row}”/>
</a4j:commandButton>	

a4j:log

Client-side Ajax log and debugging.


<a4j:log/>

ajaxlog

a4j:region

Provides declarative definition of components to be executed during Ajax request instead of using component ids. The following example wouldn’t work without a4j:region as no execute ids are defined on the a4j:poll which defaults to execute=”@this”:


<a4j:region>
	<a4j:poll interval=”10000”/>
	<h:inputText value=”#{bean.name}”/>
	<h:inputText value=”#{bean.email}”/>
</a4j:region>

If components are wrapped inside a4j:region without execute id defined, then the default value is execute=”@region”. You can also explicitly set execute=”@region”.

RENDER OPTIONS

In addition to supporting the standard render attribute in all controls which fire an Ajax request, RichFaces provides a number of advanced rendering options.

a4j:outputPanel

<a4j:outputPanel ajaxRendered=”true”> is an auto-rendered panel. All child components within a4j:outputPanel will be rendered on any Ajax request. There is no need to point to the panel via the render attribute.


<a4j:outputPanel ajaxRendered=”true”>
	<h:outputText />
	<h:dataTable>...</h:dataTable>
<a4j:outputPanel>

In example above, all components within a4j:outputPanel will be always rendered. Note that ajaxRendered must be set to true.

Limiting Rendering

To limit rendering to only components set in current render list, set limitRender=”true”. In the following example, only components c1 and c2 will be rendered (a4j:outputPanel update is turned off):


<a4j:commandLink render=”c1, c2” limitRender=”true”/>
<h:outputText id=”c1”/>
<h:panelGrid id=”c2”></h:panelGrid>
<a4j:outputPanel ajaxRendered=”true”>
	<h:dataTable>...</h:dataTable>
</a4j:outputPanel>

limitRender=true turns off all auto-rendered containers (a4j:outputPanel, rich:message(s)).

QUEUE

JSF 2 provides a basic client request queue out-of the box. RichFaces extends the standard JSF queue, and provides additional features to improve usability.

The RichFaces queue is defined via the a4j:queue tag. Queues can be named or unnamed as described below.

Named Queue

Named queues are given a name and will only be used by components which reference them directly:


<a4j:queue name=”ajaxQueue”>
<h:form>
	<a4j:commandButton>
	  <a4j:attachQueue name=”ajaxQueue”/>
	</a4j:commandButton>
</h:form>

Unnamed Queue

Unnamed queues are used to avoid having to reference named queues for every component and come with the following scopes: global, view, form.

Global level

Global queue is available on all the views and defined in web.xml file:


<context-param>
	<param-name>
	org.richfaces.queue.enabled</param-name>
	<param-value>true</param-value>
</context-param>

View level

Placed outside any form. All Ajax control on the view will use this queue:


<a4j:queue/>
<h:form>...</h:form>

Form-level

Queue definition is placed inside a form. All controls inside the form will use this queue:


<h:form>
<a4j:queue/>
</h:form>

Queue Attributes

Attribute Description
requestDelay Will delay sending the request by that number of millisecond. <a4j:queue requestDelay=”3000”/>
Used to “wait” to combine requests from the same request group
requestGroupingId Combines two or more controls into the same request group.
Requests from this group are treated as if coming from the same “logical” component. <a4j:attachQueue requestGroupingId=”grp1”/>
ignoreDupResponses Response processing for requests will not occur if a similar request is already waiting in the queue, saving the client side processing.

There are two ways to set queue options. Directly on a4j:queue tag:


<a4j:queue name=”ajaxQueue” requestDelay=”3000”/>

Or attaching a4j:attachQueue behavior to Ajax components:


<a4j:queue/>
<a4j:commandButton>
  <a4j:attachQueue requestDelay=”3000”
	requestGroupingId=”ajaxGroup”>
</a4j:commandButton>

CLIENT-SIDE VALIDATION

Bean Validation

Bean Validation (JSR-303) provides a tier agnostic approach to define constraints on model objects. Every tier must then validate those constraints. There are a set of built in constraints, defined by the Bean Validation specification. JSF 2.0 has built in Bean Validation support, but only with server side validation.

rich:validator

RichFaces 4.0 provides true client side validation that seamlessly integrates into JSF 2.0 Bean Validation support. There is an Ajax server side fallback mechanism if client side validation is not possible.

There are two ways to set queue options. Directly on a4j:queue tag:


<a4j:queue name=”ajaxQueue” requestDelay=”3000”/>

Or attaching a4j:attachQueue behavior to Ajax components:


<a4j:queue/>
<a4j:commandButton>
	<a4j:attachQueue requestDelay=”3000”
	  requestGroupingId=”ajaxGroup”>
</a4j:commandButton>

CLIENT-SIDE VALIDATION

Bean Validation

Bean Validation (JSR-303) provides a tier agnostic approach to define constraints on model objects. Every tier must then validate those constraints. There are a set of built in constraints, defined by the Bean Validation specification. JSF 2.0 has built in Bean Validation support, but only with server side validation.

rich:validator

RichFaces 4.0 provides true client side validation that seamlessly integrates into JSF 2.0 Bean Validation support. There is an Ajax server side fallback mechanism if client side validation is not possible.

Object constrained using Bean Validation

public class Foo{
	...
	@NotNull
	@Pattern(regexp=”^\d{5}(-\d{4})?$”)
	private String zipcode;
	...
}

Client side validation on a specific field

<h:inputText id=”input” value=”#{foo.zipcode}>
	<rich:validator event=”keyup”>
</h:inputText>
<rich:message for=”input” ..../>

Hot Tip

rich:message is required for client-side message updates.

The client side versions of constraints, converters, and messages must be implemented for this to work. All standard bean validation constraints are supported.

Hot Tip

Additional constraints and features will be added in the future.

Object Validation

Validate complete objects allowing for complex validation such as cross-field validation before the model gets updated (i.e. in the validation phase). Supports bean validation, but does not support client side validations at this time.

New password validation

<rich:graphValidator “value=”#{passwordBean}”>
	<h:inputText “value=”#{passwordBean.password}” />
	<h:inputText “value=”#{passwordBean.retypePassword}” />
</rich:graphValidator>

PasswordBean Implementation

public class PasswordBean implements Cloneable {

@Size(min=6) @GoodPassword
private String password ;

@Size(min=6)
private String retypePassword ;

@AssertTrue(message=”Passwords do not match”)
public boolean match(){
	return password.equals(retypePassword);
}}

The password bean is cloned, updated, and validated all in the validation phase, allowing only clean data to move to the update model phase.

RICH:* TAGS

Inputs and Selects:

Tag

Component Description
inplaceInput,inplaceSelect Inplace editing components.
inputNumberSpinner,
inputNumberSlider
UI controls for numerical input.
autocomplete Input component with live suggestions.
select Advanced select control. Provides skinning and direct typing feature.
calendar Advanced Date and Time input with various customization options.
fileUpload Asynchronous multiple files upload control.

Output

overview

Component Description
panel, popupPanel,collapsiblePanel Simple panels with header. Expansion, collapse, modal and non modal popups.
tabPanel, accordion,togglePanel Complex switchable panels.
tooltip, progressBar, message,messages Various status/message/ indication components.

Data Iteration

Data Iteration

Component Description
dataTable Customizable table with collapsible master-detail layouts, with sorting, filtering, partial Ajax updates.
extendedDataTable Additional features of: ajax scrolling, frozen columns, rows selection, columns re-adjustment and switching visibility.
list Allows dynamic rendering of any kind of HTML lists.
dataGrid panelGrid analog with dynamic models support
dataScroller paging support for any iteration component

Child components: column, columnGroup, collapsibleSubTable.

Trees

trees

Component Description
tree Rendering of hierarchical data in a tree control. Built in selection and nodes lazy loading.
treeNode Defines representation for a node of a concrete type.
treeModelAdaptor,treeModelRecursiveAdaptor Declarative definition of tree data model from various data structures.

Menus

menu

Component Description
panelMenu Vertical page menu.
dropDownMenu Drop-down menu for popup menus creation.
toolbar Laying out drop-down menus or just menu items.

Child component for content definition: panelMenuItem, panelMenuGroup,menuItem, menuGroup, menuSeparator, toolbarGroup.

Drag and Drop

Component Description
dragSource Add dragging capabilities to the parent component.
dropTarget Marks parent component as target for Ajax drop processing.
dragIndicator Visualization for dragged element.

Misc

Component Description
jQuery Declarative jQuery calls definitions.
componentControl Calling any RichFaces component client-side API.

CLIENT FUNCTIONS

RichFaces provides a number of client-side functions which make it easy to access elements in the browser.

Function Description/Example
rich:clientId(‘id’) Returns client id.
#{rich:client(‘id’)} returns form:id
rich:element(‘id’) Shortcut for
document.getElementById(#{rich:clientId(‘id’)})
rich:component(‘id’) Used to invoke client-side component JavaScript API.
rich:findComponent(‘id’)

Returns an instance of UIComponent taking the
component id.
<h:inputText id=”in”>
  <a4j:ajax />
</h:inputText>
<a4j:outputPanel
  ajaxRendered=”true”>
  #{rich:findComponent(‘in’) .value}
</a4j:outputPanel>

rich:isUserInRole(‘role’) Returns true or false whether current user is in specified role.

RICH COMPONENTS JS API

Using rich:component(‘id’)

Many rich components come with client-side JavaScript API. To use the API, get a reference to the client JavaScript object and invoke the available methods. Full description of each component API can be found in RichFaces Component Guide1. In the following example, show() and hide() method are used to show/hide panel:


<h:outputLink onclick=”#{rich:component(‘pnl’)}.show();”>
	Open
</h:outputLink>
<rich:popupPanel id=”pnl”>
  <h:outputLink onclick=”#{rich:component(‘pnl’)}.hide();”>
	Hide
  </h:outputLink>
</rich:popupPanel>

Using rich:componentControl

An alternative and more declarative approach to call JavaScript API is to use rich:componentControl:


<h:outputLink value=”#”>
  <h:outputText value=”Open” />
  <rich:componentControl operation=”show”
	  target=”pnl” event=”click”/>
</h:outputLink>
<rich:popupPanel id=”pnl”>
 <h:outputLink value=”#”>
    <h:outputText value=”Close” />
	  <rich:componentControl event=”click”
		target=”pnl” operation=”hide”/>
	</h:outputLink>
</rich:popupPanel>

SKINNING

skinning

Basic Architecture

The same three-level hierarchy that is used for RF 3.3.X is used here:

Skin parameters: configure an application-wide look and feel using dozens of parameters.

rf-* classes: added to all the components to provide a default look and feel based on parameters. To be used for redefinitions.

*Class: attributes on components.

New ECSS File Formats

Components use new *.ecss format of stylesheets:


.rf-pnl {
	color:’#{richSkin.panelBorderColor}’;
}

  1. Same CSS under the hood
  2. Dynamic properties using EL expressions

Out-of-the-box Skins

Richfaces provides various skins out of the box:

blueSky, classic, deepMarine, emeraldTown, japanCherry, plain, ruby, wine.

Application Skin Parameter Definition

To have the ability to change skin at runtime use a context parameter in the web.xml:


<context-param>
	<param-name>org.richfaces.skin</param-name>
	<param-value>#{skinBean.skin}</param-value>
</context-param>

The param-value from listing below could be just static string name. (e.g. bluesky).

Skinning Standard Components and Elements

With org.richfaces.enableControlSkinning context parameter set to true all the standard and third-party components will become skinned.

Usage of Skin Parameters on the Page

You could use implicit richSkin object in order to access skin parameters on the pages:


<h:button style=”background-color:’#{richSkin.tableBackgroundColor}’” .../>

The Same as CSS

It is the same as for usuall CSS:

<h:outputStylesheet name=”panel.ecss”/>

or


@ResourceDependency(name = “panel.ecss”)

Skinning using Static Resources

Finally you are able to serve our dynamic skins in a static way (E.g. using CDN):

  1. Add org.richfaces.cdk:maven-resources-plugin to build.
  2. Configure it. You should define directory which should be used to store generated recourses, skin names which should be processed, resources types to be included and so on… Refer to RichFaces GAE archetype or richfaces-showcase pom.xml files for getting complete code.
  3. Define static resources location via org.richfaces. staticResourceLocation context parameter using implicit resourceLocation variable in web.xml

COMPONENT DEVELOPMENT KIT

RichFaces CDK has been developed to boost productivity by providing easy-to-use environment for simplifying common components development tasks. Main features are:

  • Very easy creation and maintenance of classes such as component,converter, validator, etc.
  • Generation of renderer classes from files with VDL-like syntax.
  • Easy-to-use annotation—or XML-based configuration following Convention-over-Configuration principles.
  • Generation of XML configuration files.

GOOGLE APPLICATION ENGINE SUPPORT

Google Application Engine deployments require specific changes to be done at the application level mostly because of GAE’s restrictions and issues related to JSF deployment.

Archetype Usage

RichFaces provides a special archetype to generate an application skeleton for GAE deployments:


mvn archetype:generate -DarchetypeGroupId=org.richfaces.archetypes
-DarchetypeArtifactId=richfaces-archetype-gae -DarchetypeVersion=<archetyp
eVersion>
-DgroupId=<yourGroupId> -DartifactId=<yourArtifactId> -Dversion=1.0-
SNAPSHOT

Now you can run mvn install as usually to build application and use mvn gae:deploy for deployment.

Deployment Requirements

Exploring the application generated by the archetype is the easiest way to check settings which are required to be done for deployment. It includes:

  • static resources for skins has to be used as GAE not allows Java2D usage (see skinning section for details)
  • GAE-specific web.xml settings added

About The Authors

The Authors

Ilya Shaikovsky

Publications: DZone Richfaces 3 Refcard co-author
Projects: RichFaces, JBoss Tools

Nick Belaevski

Publications: DZone Richfaces 3 Refcard co-author
Blog: http://jroller.com/a4j, http://in.relation.to/Bloggers/Ilya
Twitter: http://twitter.com/ilya_shaikovsky

Jay Balunas

Publications: DZone RichFaces 3 Refcard co-author
Projects: RichFaces, Seam, Weld, and TattleTale
Blog: http://in.relation.to/Bloggers/Jay
Twitter: http://twitter.com/tech4j

Max Katz

Publications: DZone, TheServerSide, Practical RichFaces (Apress), DZone RichFaces 3 Refcard co-author
Projects: Flamingo, jsf4birt, Fiji, JavaFX plug-in for Eclipse on exadel.org, Interactive HTML prototypes: http://gotiggr.com
Blog: http://mkblog.exadel.com
Twitter: http://twitter.com/maxkatz

Recommended Book

Practical RichFaces

RichFaces 4.0 is an advanced JSF 2.0 based framework that provides a complete range of rich Ajax enabled UI components, as well as other features such as a component development kit, dynamic resource support, and skinning. The 4.0 version brings complete JSF 2.0 support to the project.

Practical RichFaces 4 describes how the new RichFaces 4 upgrades and extends JSF 2 with new features, advanced functionality and customization. Learn how to use a4j:* tags, rich:* tags, component JavaScript API, skins, and client-side validation. Assuming some JSF background, it shows you how you can radically reduce programming time and effort to create rich enterprise Ajax based applications.

In this definitive RichFaces 4 book, the authors bases all examples on Maven so that any IDE can be used—whether it’s NetBeans, Eclipse, IntelliJ or JBoss Tools.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Daily Dose - W3C Official: Don't Use HTML5 Yet

Philippe Le Hegaret, a World Wide Web Consortium domain leader says it's too early for browsers to be settling on unconfirmed HTML5-related specification drafts and it's too early for websites to be using the drafts to build their websites.  Of course, this...

2 replies - 16595 views - 10/07/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - HTML5 Pack for Adobe Illustrator

Adobe Labs has announced an HTML5/CSS3/SVG pack for Illustrator this week.  The add-on is for the most recent class of the Creative Suite, CS5.  It helps designers easily create web content for various form factors.   Check out Mordy Golding's video...

0 replies - 15763 views - 09/13/10 by Mitchell Pronsc... in Daily Dose

DZone Daily Dose - Hibernate 3.5.5 Deprecates CGLIB Support

A decent amount of uproar was generated this week when JBoss developers indicated that the latest stable release of Hibernate (3.5.5) would have deprecated support for CGLIB as a bytecode provider.  Developers can still use CGLIB as the bytecode provider,...

1 replies - 24756 views - 08/21/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Spring Ignites GemFire 1.0

Several months after the acquisition of GemStone, Spring has officially released a project integrating the company's technology.  The first milestone of GemFire 1.0 now includes the Spring development approach in its distributed data management platform. ...

1 replies - 15175 views - 08/04/10 by Mitchell Pronsc... in Daily Dose

Getting Started with Maven Repository Management

By Jason Van Zyl

20,298 Downloads · Refcard 98 of 151 (see them all)

Download
FREE PDF


The Essential Maven Repository Cheat Sheet

Maven Repositories provides a standard for storing and serving binary software. Maven and other tools such as Ivy interact with repositories to search for binary software artifacts, locate project dependencies, and retrieve software artifacts from a repository. Maven Repository managers serve two purposes: they act as highly configurable proxies between your organization and the public Maven repositories and they provide an organization with a deployment destination for your own generated artifacts. This DZone Refcard is an in-depth introduction to Maven Repository Management. We cover everything from what is Repository Management to Proxy Repositories, Hosted Repositories, and Repository Groups.
HTML Preview
Getting Started with Maven Repository Management

Getting Started with Maven Repository Management

By Jason Van Zyl

MAVEN REPOSITORY MANAGEMENT

A Maven repository provides a standard for storing and serving binary software. Maven and other tools such as Ivy interact with repositories to search for binary software artifacts, locate project dependencies, and retrieve software artifacts from a repository.

Maven Repository managers serve two purposes: they act as highly configurable proxies between your organization and the public Maven repositories and they also provide an organization with a deployment destination for your own generated artifacts.

Proxy Remote Repositories

When you proxy a remote repository, you repository manager accepts requests for artifacts from clients. If the artifact is not already cached, the repository manager will retrieve the artifact from the remote repository and cache the artifact. Subsequent requests for the same artifact will be served from the local cache.

cache"

Hosted Internal Repositories

When you host a repository, your repository manager takes care of organizing, storing, and serving binary artifacts. You can use a hosted, internal repository to store internal release artifacts, snapshot artifacts, or 3rd party artifacts.

artifacts"

Release Artifacts

These are specific, point-in-time releases. Released artifacts are considered to be solid, stable, and perpetual in order to guarantee that builds which depend upon them are repeatable over time. Released JAR artifacts are associated with PGP signatures and checksums verify both the authenticity and integrity of the binary software artifact. The Central Maven repository stores release artifacts.

Snapshot Artifacts

Snapshots capture a work in progress and are used during development. A Snapshot artifact has both a version number such as “1.3.0” or “1.3” and a timestamp. For example, a snapshot artifact for commons-lang 1.3.0 might have the name commons-lang-1.3.0-20090314.182342-1.jar.

Reasons to Use a Repository Manager

  • Builds will run much fasteras they will be downloading artifacts from a local cache.
  • Builds will be more stablebecause you will not be relying on external resources. If your internet connection becomes unavailable, your builds will rely on a local cache of artifacts from a remote repository.
  • You can deploy 3rd party artifacts to your repository manager. If you have a proprietary JDBC driver, add it to an internal 3rd party repository so developers can add it as a project dependency without having to manually install it in a local repository.
  • It will be easier to collaborateand distribute software internally. Instead of sending other developers instructions for checking out source from source control and building entire applications from source, publish artifacts to an internal repository and share binary artifacts.
  • If you are deploying software to the public, the fastest way to get your users productive is with a standard Maven repository.
  • You can control which artifacts and repositories are referenced by your projects.

Additional Features and Benefits

Searching and Indexing Artifacts:All repository managers provide an easy way to index and search software artifacts using the standard Nexus Indexer format.

Repository Groups:Repository managers can consolidate multiple repositories into a single repository group making it easier to configure tools to retrieve artifacts from a single URL.

Repository"

Procuring External Artifacts:Organizations often want some control over what artifacts are allowed into the organization. Many repository managers allow administrators to define lists of allowed and/or blocked repositories.

Staging and Release Management:Repository managers can also support decisions and workflow associated with software releases sending email notifications to release managers, developers, and testers.

Release

Security and LDAP Integration:Repository managers can be configured to verify artifacts downloaded from remote repositories and to integrate with external security providers such as LDAP.

Multiple Repository Formats:Repository managers can also automatically transform between various repository formats including OSGi Bundle repositories (OBR), P2 repositories, Maven repositories, and other repository formats.

REPOSITORY COORDINATES

Repositories store artifacts using a set of coordinates: groupId, artifactId, version, and packaging. The GAV coordinate standard is the foundation for Maven’s ability to manage dependencies.

Hot Tip

This set of coordinates is often referred to as a GAV coordinate, which is short for “Group, Artifact, Version coordinate.”

Coordinate: groupId

A group identifier groups a set of artifacts into a logical group. For example, software components being produced by the Maven project are available under the groupId org.apache.maven.

Coordinate: artifactId

An artifact is simply a name for a software artifact. A simple web application project might have the artifactId “simple-webapp”, and a simple library might be “simple-library”. The combination of groupId and artifactId must be unique for a project.

Coordinate: version

A numerical version for a software artifact. For example, if your simple-library artifact has a Major release version of 1, a minor release version of 2, and point release version of 3, your version would be 1.2.3. Versions can also contain extra information to denote release status such as “1.2-beta”.

Coordinate: packaging

Packaging describes the contents of the software artifact. While the most common artifact is a JAR, Maven repositories can store any type binary software format including ZIP, SWC, SWF, NAR, WAR, EAR, SAR.

Addressing Resources in a Repository

Tools designed to interact with Maven repositories translate artifact coordinates into a URL which corresponds to a location in a Maven repository. If a tool such as Maven is looking for version 1.2.0 of the some-library JAR in the group com.example, this request is translated into:


/com/example/some-library/1.2.0/some-library-1.2.0.jar
/com/example/some-library/1.2.0/some-library-1.2.0.pom

pg2"

PROJECT DEPENDENCIES

Build tools like Maven and Ivy allow you to define project dependencies using Maven coordinates.

Declaring Dependencies in Maven


<project>
...
  <dependencies>
  <dependency>
      <groupId>org.codehaus.xfire</groupId>
      <artifactId>xfire-java5</artifactId>
      <version>1.2.5</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
      <artifactId>junit</artifactId>
     <version>3.8.1</version>
     <scope>test</scope>
    </dependency>
</dependencies>
...
</project>

REMOTE REPOSITORIES

Central Maven Repository

The Central Maven repository contains almost 90,000 software artifacts occupying around 100 GB of disk space. You can look at Central as an example of how Maven repositories operate and how they are assembled.
http://repo1.maven.org

Apache Snapshot Repository

The Apache Snapshot repository contains snapshot artifacts for projects in the Apache Software Foundation. http://repository.apache.org/snapshots/

Codehaus Snapshot Repository

The Codehaus Snapshot repository contains snapshot artifacts for projects hosted by Codehaus. http://nexus.codehaus.org/snapshots/

ABOUT NEXUS

Nexus manages software “artifacts” required for development, deployment, and provisioning. If you develop software, Nexus can help you share those artifacts with other developers and end-users. Maven’s central repository has always served as a great convenience for users of Maven, but it has always been recommended to maintain your own repositories to ensure stability within your organization. Nexus greatly simplifies the maintenance of your own internal repositories and access to external repositories. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.

Downloading Nexus Open Source

To download Nexus Open Source, go to http://nexus.sonatype.org and click on the Download menu item. Download the nexus-oss-webapp-1.6.0-bundle.tar.gz or nexus-oss-webapp-1.6.0-bundle.zip file from the Download directory.

Downloading Nexus Professional

To download Nexus Professional, go to http://www.sonatype.com/products/nexus and click on Download Nexus Pro. After you fill out a simple registration form, a download link will be sent via email.

Installing Java

Nexus Open Source and Nexus Professional only have one prerequisite, a Java Runtime Environment (JRE) compatible with Java 5 or higher. To download the latest release of the Sun JDK, go to http://developers.sun.com/downloads/.

Installing Nexus

Unpack the Nexus distribution in any directory. Nexus doesn’t have any hard coded directories, it will run from any directory. If you downloaded the ZIP archive, run:


$ unzip nexus-webapp-1.6.0-bundle.zip

And, if you downloaded the GZip’d TAR archive, run:


$ tar xvzf nexus-webapp-1.6.0-bundle.tgz

This will create two directories nexus-webapp-1.6.0/ and sonatype-work/.

The Sonatype Work Directory

The Nexus installation directory nexus-webapp-1.6.0 has a sibling directory named sonatype-work/. This directory contains all of the repository and configuration data for Nexus and is stored outside of the Nexus installation directory to make it easier to upgrade to a newer version of Nexus.

RUNNING NEXUS

When you start Nexus for the first time, it will be running on http://localhost:8081/nexus/. To start Nexus, find the appropriate startup script for your platform in the ${NEXUS_HOME}/bin/jsw directory.

Starting Nexus

The following example listing starts Nexus using the script for Mac OS X. The Mac OS X wrapper is started with a call to nexus start:


$ cd ~/nexus-webapp-1.6.0
$ ls ./bin/jsw/
aix-ppc-32/ linux-ppc-64/ solaris-sparc-32/
aix-ppc-64/ linux-x86-32/ solaris-sparc-64/
hpux-parisc-32/ linux-x86-64/ solaris-x86-32/
hpux-parisc-64/ macosx-universal-32/ windows-x86-32/
$ chmod -R a+x bin
$ ./bin/jsw/macosx-universal-32/nexus start
Nexus Repository Manager...
$ tail -f logs/wrapper.log
INFO ... [ServletContainer:default] -SelectChannelConnector@0.0.0.0:8081


Configuring Nexus as a Service

When installing Nexus, you will often want to configure Nexus as a service. To configure Nexus as a service on Windows:

  • (A) Open a Command Prompt
  • (B) Change directories to C:/Program Files/nexus-webapp-1.6.0
  • (C) Change directories to bin/jsw/windows-x86-32
  • (D) Run InstallNexus.bat to install Nexus as a Windows Service
  • (E) Run “net start nexus-webapp” to start the Nexus service

To configure Nexus as a service on Linux:

  • (A) Copy bin/jsw/$PLATFORM/nexus to /etc/init.d
  • (B) chmod 755 /etc/init.d/nexus
  • (C) Edit the startup script changing APP_NAME, APP_LONG_NAME, NEXUS_HOME, PLATFORM, WRAPPER_CMD, and WRAPPER_CONF
  • (D) (Optional) Set the RUN_AS_USER to “nexus

Login to Nexus

To use Nexus, fire up a web browser and go to: http://localhost:8081/nexus. Click on the “Log In” link in the upper right-hand corner of the web page, and you should see the login dialog.

login"

Hot Tip

THE DEFAULT NEXUS USERNAME AND PASSWORD IS “admin” AND “admin123”.

Post-install Checklist

After installing Nexus make sure to make the following configuration changes.

  • Change the Administrative Password by clicking on Security -> Users. Right-click on the admin user and choose “Set Password”.
  • Configure the SMTP Settings by selecting Administration -> Server and filling out the SMTP server information.
  • Enable Remote Index Downloads for the Central Maven Repository. Click on Views/Repositories -> Repositories. Select the “Maven Central” repository and open up the Configuration tab. Under Remote Repository Access set Download Remote Indexes to true.
  • Install Professional License (Nexus Professional Only). Select Administration -> Licensing and upload your Nexus Professional License.

CONFIGURING MAVEN FOR NEXUS

To use Nexus, you will configure Maven to check Nexus instead of the public repositories. To do this, you’ll need to edit your mirror settings in your ~/.m2/settings.xml file.

Update your Maven Settings

Place the following XML into a file named ~/.m2/settings. xml. This Maven Settings file configures your Maven builds to fetch artifacts from the public group of the Nexus installation available at http://localhost:8081/nexus/


<settings>
 <mirrors>
  <mirror>
   <!--This sends everything else to /public -->
   <id>nexus</id>
   <mirrorOf>*</mirrorOf>
   <url>http://localhost:8081/nexus/content/groups/public</url>
  </mirror>
 </mirrors>
<profiles>
 <profile>
  <id>nexus</id>
  <repositories>
   <repository>
    <id>central</id>
     <url>http://central</url>
     <releases><enabled>true</enabled></releases>
     <snapshots><enabled>true</enabled></snapshots>
    </repository>
   </repositories>
 <pluginRepositories>
  <pluginRepository>
   <id>central</id>
    <url>http://central</url>
     <releases><enabled>true</enabled></releases>
     <snapshots><enabled>true</enabled></snapshots>
    </pluginRepository>
   </pluginRepositories>
 </profile>
</profiles>
  <activeProfiles>
   <!--make the profile active all the time -->
    <activeProfile>nexus</activeProfile>
  </activeProfiles>
</settings>

Deploying Artifacts to Nexus

To deploy artifacts to Nexus you must set server credentials in your Maven Settings and configure your project’s POM to publish to Nexus. Using the default deployment user’s credentials, put the following server element in your Maven Settings XML stored in ~/.m2/settings.xml


<settings>
…
<servers>
<server>
   <id>releases</id>
   <username>deployment</username>
   <password>deployment123</password>
 </server>
<server>
   <id>snapshots</id>
   <username>deployment</username>
   <password>deployment123</password>
<</server>
</servers>
…
</settings>

And, add the following XML to your Maven project’s pom.xml:


<distributionManagement>
  <repository>
     <id>releases</id>
     <name>Releases Repository</name>
     <url>
  http://localhost:8081/nexus/content/repositories/releases
</url>
  </repository>
    <snapshotRepository>
    <id>snapshots</id>
   <name>Snapshot Repository</name>
 <url>
http://localhost:8081/nexus/content/repositories/snapshots
  </url>
  </snapshotRepository>
</distributionManagement>

This configures your Maven build to deploy snapshots to the hosted Snapshots repository and releases to the hosted Releases repository. When Maven performs the deployment, it will match the id element of the repository with the id element of the server in the settings.xml and send the appropriate credentials.

Hot Tip

The default deployment user is deployment and the default password is deployment123.

PROXY REPOSITORIES

This section details working with Proxy Repositories.

What is a Proxy Repository?

A proxy repository sits between your builds and a remote repository like the Central Maven repository. When you ask a proxy repository for an artifact, it checks a local cache of artifacts it has already downloaded. If it does not have the artifact requested, it will retrieve the artifact from the remote repository.

Proxy repositories speed up your builds by serving frequently used artifacts from a local cache. They also provide for more stability in case when your internet connection or the remote repository becomes unavailable.

Adding a New Proxy Repository

To add a new Proxy Repository, go to Views/Repositories -> Repositories, and click on the Add button as shown in the following figure. Select Proxy Repository from the drop down:

Proxy"

Once you select Proxy Repository you will see the New Proxy Repository form shown here:

Proxy

Supply a unique identifier and name, choose a Repository Policy of either Release or Snapshot, and provide the URL of the remote repository in the Remote Storage Location.

Enabling Remote Index Downloads

While Nexus is preconfigured with the Central Maven repository, it is not configured to download indexes from remote repositories. Enabling indexes is essential if you want to take full advantage of Nexus’ intuitive search interface. To enable Remote Index Downloads. Go to Views/Repositories -> Repositories. Select the Maven Central repository and click on the Configuration tab. Set “Download Remote Indexes” to true and click on Save. Nexus will then download the repository index from the remote repository. This process may take a few minutes depending on the speed of your connection.

If the remote index has been successfully downloaded and processed, the Browse Index tab for the Maven Central repository will display thousands of artifacts.

HOSTED REPOSITORIES

What is a Hosted Repository?

A Hosted Repository contains artifacts which have been published to a Nexus instance. These published artifacts are stored in the Sonatype Work directory. This can include repositories that hold release artifacts and repositories that hold snapshot artifacts.

Nexus comes configured with three Hosted repositories: 3rd Party, Releases, and Snapshots. The Releases repository is for your own internal software release artifacts, and the Snapshots repository is for your own project’s snapshot artifacts. The 3rd Party repository is for 3rd party artifacts such as proprietary drivers or commercial libraries which are not available from a public Maven repository.

Adding a New Hosted Repository

Proxy

REPOSITORY GROUPS

What is a Repository Group?

A repository groups combines one or more repositories under a single repository URL. You use repository groups to simplify the configuration of tools like Maven which need to retrieve artifacts from a set of common repositories. As a Nexus administrator you can define new repositories, control which repositories are available in a group and the order in which artifacts are resolved from repositories in a group.

Adding Repositories to a Group

Nexus ships with a Public Repository Group which contains all of your hosted and proxy repositories. If you create a new repository, and you need to add this repository to the Public Group, go to Views/Repositories -> Repositories and select the Configuration tab.

Config

To add a repository to repository group, drag a repository from the “Available Repositories” list to the “Ordered Group Repositories” list and click on the Save button.

Reordering Repositories in a Group

When Nexus resolves an artifact from a Repository Group it iterates over the repositories in the group, returning the first match. If an artifact exists in more than one repository, you may need to change the order of repositories in a Repository Group. To change the order, go to Repositories/View -> Repositories, select the group you need to reorder, and then select the Configuration tab. To reorder repositories, click and drag repositories to the correct order in the Ordered Group Repositories field and then click Save.

NEXUS ADMINISTRATION

Configuring Nexus Server

To configure Sonatype Nexus, click on Administration -> Server this will load the Nexus configuration panel. The following is a list of some of the configuration sections in this panel:

SMTP Settings: Nexus supports release and deployment using email. Before Nexus can send emails, you will need to configure the appropriate SMTP settings in this section.

HTTP Request Settings: Configure custom timeouts and retry behavior for remote repositories as well as customize the Nexus User Agent.

Security Settings: Nexus’ pluggable security providers are configured in this section. You can control which security realms are active and the order in which they are consulted during authentication and authorization.

Anonymous Access:Control how and if Nexus is made available to anonymous, unauthenticated users.

Application Server Settings:If Nexus is hosted behind a proxy, or if you need to customize the URL, you can do so here.

System Notifications Settings:Configure automatic email notifications for important system events.

Configuring Scheduled Tasks

If you are publishing snapshots releases to Nexus, you will want to configure at least one scheduled task to periodically delete older snapshots releases. To configure a Scheduled Task, click on Administration -> Scheduled Tasks, and click on the Add button. Select the appropriate Task Type. Some of the more common and useful Task Types follow:

Backup All Nexus Configuration Files:Will cause Nexus to create a snapshot of all Nexus configuration files.

Download Indexes:Nexus will retrieve or update indexes for all remote, proxy repositories.

Evict Unused Proxy Items:If space is a premium, you can configure Nexus to remove proxy items which have not been used within a specific time period.

Remove Snapshots from Repository:Nexus can be configured to keep a minimum number of repositories and to delete snapshots older than a specific time period.

Scheduled tasks can be configured to send an email alert when they are executed, and you can schedule a task to run Once, Hourly, Daily, Weekly, Monthly, or using a custom cron expression.

Defining Repository Routes

Repository routes allow you to direct requests matching specific patterns to specific repositories. For example, if you wanted to make sure all requests for artifacts under org.someoss where directed to internal, hosted Releases and Snapshots repositories, you would define the following route:


Type: Inclusive
URL Pattern: .*/org/some-oss/.*
Repositories: Releases, Snapshots

To define a Repository Route, go to Administration -> Routing. The Routing panel is where you can edit existing routes and create additional routes.

Configuring Nexus Security

Nexus Security has a highly configurable Role-based Access Control system which relies on Privileges, Roles, and Users. By default, Nexus ships with a default admin, deployment, anonymous user along with associated roles. To configure a new Nexus user, go to Security -> Users and open up the Users panel. On the users panel, click on the Add button to add a new Nexus user. Once the user is created, click on the user to edit the user’s email address or to assign the user new Nexus roles.

To create or edit roles, click on Security -> Roles. Most of the default roles cannot be edited directly, but you are free to create new, custom roles by clicking on the Add button. Once a role is created, you can assign it new privileges, by dragging Roles and Privileges from the Available Roles/Privileges list to the Selected Roles/Privileges list and clicking on the Save button.

NEXUS PROFESSIONAL

Nexus Professional is a central point of access to external repositories which provides the necessary controls to make sure that only approved artifacts enter into your software development environment. Central features of Nexus Professional are:

Nexus Procurement Suite:Gives Nexus administrators control of what artifacts are allowed into an organization from a remote repository.

Nexus Staging Suite:Provides workflow support for software releases. Artifacts can be deployed to staging repositories, tested, and promoted only after they have been tested and certified.

Hosting Project Web Sites:With Nexus Professional, you can publish Maven project sites directly to your repository manager.

Support for OSGi Repositories:Nexus Professional supports OBR and P2 repositories used in OSGi and Eclipse development.

Enterprise LDAP Support:Nexus Professional adds support for LDAP clustering, and supporting mixed authentication configurations for multiple sources of security information including Atlassian’s Crowd server.

In addition to these features, Nexus Pro also adds support for Artifact Bundles, Centralized Management of Maven Settings, Custom Repository Metadata, Self-serve User Account Sign-up, and Artifact Validation and Verification.

OTHER NEXUS RESOURCES

For more information about Sonatype’s Nexus, see the following resources:

Free Nexus Book:
http://books.sonatype.com/nexus-book

Nexus OSS Site:
http://nexus.sonatype.org

Nexus Pro Site:
http://www.sonatype.com/products/nexus

Participate in the Nexus Community

Everyone is welcome to participate in the Nexus community as a developer or user. To participate, take advantage of the following resources:

Nexus IRC Channel:
#nexus on irc.codehaus.org:6667

Subscribe to the Nexus User Mailing List:
nexus-user-subscribe@sonatype.org

Subscribe to the Nexus Developer Mailing List:
nexus-dev-subscribe@sonatype.org

Subscribe to the Nexus Pro User Mailing List:
nexus-pro-users-subscribe@sonatype.org

Checkout Nexus Source Code from Subversion:
http://svn.sonatype.org/nexus/trunk

Browse the Nexus JIRA Project:
https://issues.sonatype.org/browse/NEXUS

About The Authors

Photo of author Jason Van Zyl

Jason Van Zyl

Jason Van Zyl is the founder and CTO of Sonatype, the Maven company, and founder of the Apache Maven Project, the Plexus IoC framework, and the Apache Velocity project.

Recommended Book

Nexus

This book covers both Nexus Open Source and Nexus Professional, a product which brings full control and visibility to organizations which depend on Maven repositories to manage releases and distribute software.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

DZone Daily Dose - 1/4

Rackspace Gets MySQL DaaS

0 replies - 13907 views - 01/03/10 by Mitchell Pronsc... in Daily Dose

Apache Maven 2 - The Better Path to Build Automation

Click here to download a PDF of our latest DZone Refcard on Apache Maven 2!

0 replies - 5787 views - 05/26/09 by Lyndsey Clevesy in Announcements