Frameworks

  • submit to reddit

Getting Started with Spring-DM

By Craig Walls

16,704 Downloads · Refcard 57 of 151 (see them all)

Download
FREE PDF


The Essential Spring-DM Cheat Sheet

Spring is a framework that promotes development of loosely coupled/highly cohesive objects through dependency injection and interface-oriented design. Spring Dynamic Modules (Spring-DM) brings Spring and OSGi together to enable a declarative service model for OSGi that leverages Spring’s power of dependency injection. This DZone Refcard shows you how to use Spring-DM to wire together OSGi services to build highly modular and dynamic applications. You may also enjoy the other Spring DZone Refcardz in our Collection: Spring Configuration and Spring Annotations.
HTML Preview
Getting Started with Spring-DM

Getting Started with Spring-DM

By Craig Walls

about spring-dm

Spring is a framework that promotes development of looselycoupled/ highly-cohesive objects through dependency injection and interface-oriented design. OSGi is a framework specification that promotes development of loosely-coupled/ highly-cohesive application modules through services and interface-oriented design. Seems like a match made in heaven! Spring Dynamic Modules (Spring-DM) brings Spring and OSGi together to enable a declarative service model for OSGi that leverages Spring’s power of dependency injection. This reference card will be your resource for working with Spring- DM to wire together OSGi services and ultimately building modular applications.

You may be interested to know that Spring-DM is the basis for the SpringSource dm Server, a next-generation application server that embraces modularity through OSGi. What’s more, the upcoming OSGi R4.2 specification includes a component model known as the OSGi Blueprint Services that is heavily influenced by Spring-DM.

Introducing Spring-DM

The star player of Spring-DM is a bundle known as the Spring- DM extender. The Spring-DM extender watches for bundles to be installed and inspects them to see if they are Springenabled (that is, if they contain a Spring application context definition file). When it finds a Spring-enabled bundle, the extender will create a Spring application context for the bundle.

Spring Application Contexts

Spring-DM also provides a Spring configuration namespace that enables you to declare and publish Spring beans as OSGi services and to consume OSGi services as if they were just beans in a Spring application context. This declarative model effectively eliminates the need to work with the OSGi API directly.

Installing Spring-DM

One of the nice things about Spring-DM is that you do not need to include it in the classpath of your OSGi bundles or even reference it from those bundles. Installing Spring-DM involves two parts:

  1. Installing the Spring-DM and supporting bundles in your OSGi framework
  2. Adding the Spring-DM configuration namespace to your bundle’s Spring configuration XML files

You can download Spring-DM from
http://www.springframework.org/osgi. The distribution comes complete with everything you need to work with Spring- DM, including the Spring-DM extender bundle and all of its dependency bundles.

Installing the Spring-DM extender bundles

There are several means by which you can install bundles into an OSGi framework, depending on the OSGi framework and any add-ons or tools you may be using. But the most basic way is to use the “install” command that is available in most OSGi framework shells. For example, to install the Spring- DM extender bundle and the supporting Spring-DM bundles (assuming that you’ve unzipped the Spring-DM distribution in / spring-dm-1.2.0):


osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-core-
   1.2.0.jar
osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-extender-
   1.2.0.jar
osgi> install file:///spring-dm-1.2.0/dist/spring-osgi-io-
   1.2.0.jar

Spring-DM depends on the Spring framework, so you’ll also need to install several other Spring bundles:

refcardzad


osgi> install file:///spring-dm-1.2.0/lib/spring-aop-2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-context-
    2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-core-2.5.6.A.jar
osgi> install file:///spring-dm-1.2.0/lib/spring-beans-2.5.6.A.jar

Finally, you’ll also need to install several other supporting bundles that Spring and Spring-DM depend on:


osgi> install file:///spring-dm-1.2.0/lib/com.springsource.net.
   sf.cglib-2.1.3.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.org.
   aopalliance-1.0.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   api-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   log4j-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/com.springsource.slf4j.
   org.apache.commons.logging-1.5.0.jar
osgi> install file:///spring-dm-1.2.0/lib/log4j.osgi-1.2.15-
   SNAPSHOT.jar

Hot Tip

Use tools to help install bundles Installing bundles using the “install” command should work with almost any OSGi framework, but it is also quite a manual process. Pax Runner (http:// paxrunner.ops4j.org) is an OSGi framework launcher that takes a lot of the tedium out of installing bundles. Just use Pax Runner’s “spring dm” profile: % pax-run.sh --profiles=spring.dm

The Spring-DM configuration namespace

Schema URI:

http://www.springframework.org/schema/osgi

Schema XSD:

http://www.springframework.org/schema/osgi/spring-osgi.xsd

When it comes to declaring services and service consumers in Spring-DM, you’ll use Spring-DM’s core namespace. To do that, you’ll need to include the namespace in the XML file.


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
	xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
	xmlns:osgi=”http://www.springframework.org/schema/osgi”
	xsi:schemaLocation=”http://www.springframework.org/
schema/beans
	    http://www.springframework.org/schema/beans/
spring-beans.xsd
		   http://www.springframework.org/schema/osgi
		     http://www.springframework.org/schema/
osgi/spring-osgi.xsd”>
...
</beans>

Spring’s “beans” namespace is the default namespace, but if you know that most or all of the elements in the Spring configuration file will be from the Spring-DM namespace, you can make it the default namespace:

spring beans

Publishing Services

To demonstrate Spring-DM’s capabilities, we’re going to create a few OSGi services that translate English text into some other language. All of these services will implement the following Translator interface:


package com.habuma.translator;
public interface Translator
   {
String translate(String text);
}

The first service we’ll work with is one that translates English into Pig Latin. It’s implementation looks something like this:


package com.habuma.translator.piglatin;
import com.habuma.translator.Translator;
public class PigLatinTranslator implements Translator {
	private final String VOWELS = “AEIOUaeiou”;
	public String translate(String text) {
	  // actual implementation left out for brevity
	}
}

If we were working with basic OSGi (that is, without Spring- DM), we’d publish this service to the OSGi service registry using the OSGi API, perhaps in a bundle activator’s start() method:


public void start(BundleContext context) throws Exception {
	context.registerService(Translator.class.getName(),
				new PigLatinTranslator(), null);
}

Although the native OSGi approach will work fine, it requires us to work programmatically with the OSGi API. Instead, we’ll publish services declaratively using Spring-DM. The first step: Create a Spring context definition file that declares the PigLatinTranslator as a Spring bean:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xsi:schemaLocation=”http://www.springframework.org/
schema/beans
		  http://www.springframework.org/schema/beans/springbeans.
xsd”>
  <bean id=”pigLatinTranslator”
    class=”com.habuma.translator.piglatin.PigLatinTranslator” />
</beans>

Hot Tip

Overriding the context configuration location By default, the Spring-DM extender looks for all XML files located in a bundle’s META-INF/spring folder and assumes that they’re all Spring context definition files that are to be used to create a Spring application context for the bundle; however, if you’d like to put your context definition files elsewhere in the bundle, use the Spring-Context: header in the META-INF/ MANIFEST.MF file.
For example, if you’d rather place your Spring configuration files in a directory called “spring-config” at the root of the bundle, add the following entry to your bundle’s manifest: Spring-Context: spring-config/*.xml

This Spring context file can be named anything, but it should be placed in the Pig Latin translator bundle’s META-INF/ spring directory. When the bundle is started in an OSGi framework, the Spring-DM extender will look for Spring context configuration files in that directory and use them to create a Spring application context for the bundle.

Publishing a simple OSGi service

By itself the Spring context we’ve created only creates a bean in the Spring application context. It’s not yet an OSGi service. To publish it as an OSGi service, we’ll create another Spring context definition file that uses the Spring-DM namespace:


<<?xml version=”1.0” encoding=”UTF-8”?>
<<beans:beans xmlns:beans=”http://www.springframework.org/schema/
beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xmlns=”http://www.springframework.org/schema/osgi”
		xsi:schemaLocation=”http://www.springframework.org/
schema/beans
			http://www.springframework.org/schema/beans/
spring-beans.xsd
			  http://www.springframework.org/schema/osgi
				http://www.springframework.org/schema/
osgi/spring-osgi.xsd”>
   <<service ref=”pigLatinTranslator”
	  interface=”com.habuma.translator.Translator” />
<</beans:beans>

Hot Tip

Don’t mix your Spring and OSGi contexts Although you can certainly define all of your bundle’s Spring beans and OSGi services in a single Spring context definition file, it’s best to keep them in separate files (all in META-INF/spring). By keeping the OSGi-specific declarations out of the normal Spring context definition, you’ll be able to use the OSGi-free context to do non-OSGi integration tests of your beans.

This new Spring context file uses Spring-DM’s element to publish the bean whose ID is “pigLatinTranslator” in the OSGi service registry. The ref attribute refers to the Spring bean in the other context definition file. The interface attribute identifies the interface under which the service will be available in the OSGi service registry.

Publishing a service under multiple interfaces

Let’s suppose that the PigLatinTranslator class were to implement another interface, perhaps one called TextProcessor. And let’s say that we want to publish the service under both the Translator interface and the TextProcessor interface. In that case, you can use the element to identify the interfaces for the service:


<service ref=”pigLatinTranslator”>
  <interfaces>
    <beans:value>com.habuma.translator.Translator</beans:value>
    <beans:value>com.habuma.text.TextProcessor</beans:value>
  </interfaces>
</service>

Auto-selecting service interfaces

Instead of explicitly specifying the interfaces for a service, you can also let Spring-DM figure out which interfaces to use by specifying the auto-export attribute:


<service ref=”pigLatinTranslator”
       auto-export=”interfaces” />

By setting auto-export to “interfaces”, it tells Spring-DM to publish the service under all interfaces that the implementation class implements. You can also set auto-export to “all-classes” to publish the service under all interfaces and classes for the service or “class-hierarchy.”

Publishing a service with properties

It’s also possible to publish a service with properties to qualify that service. These properties can later be used to help refine the selection of services available to a consumer. For example, let’s say that we want to qualify Translator services by the language that they translate to:


<rvice ref=”pigLatinTranslator”
      interface=”com.habuma.translator.Translator”>
<service-properties>
   <beans:entry key=”translator.language” value=”Pig Latin” />
 </service-properties>
</service>

The <service-properties> element can contain one or more <entry> elements from the “beans” namespace. In this case, we’ve added a property named “translator.language” with a value of “Pig Latin”. Later, we’ll use this property to help select this particular service from among a selection of services that all implement Translator.

Consuming Services

Now that we’ve seen how to publish a service in the OSGi service registry, let’s look at how we can use Spring-DM to consume that service. To get started, we’ll create a simple client class:


package com.habuma.translator.client;
import java.util.List;
import com.habuma.translator.Translator;
public class TranslatorClient {
  private static String TEXT = “Be very very quiet. I’m hunting
rabbits!”;
  public void go() {
     System.out.println(“ TRANSLATED: “ +
        translator.translate(TEXT));
  }
  private Translator translator;
  public void setTranslator(Translator translator) {
    this.translator = translator;
  }
}

TranslatorClient is a simple POJO that is injected with a Translator and uses that Translator in its go() method to translate some text. We’ll declare it as a Spring bean like this:


<?xml version=”1.0” encoding=”UTF-8”?>
		<beans xmlns=”http://www.springframework.org/schema/beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://www.springframework.org/
schema/beans
			http://www.springframework.org/schema/beans/springbeans.
xsd”>
  <bean class=”com.habuma.translator.client.TranslatorClient”
     init-method=”go”>
   <property name=”translator” ref=”translator” />
  </bean>
</beans>

As with the service’s Spring context declaration, the name of this Spring context definition can be named anything, but it should be placed in the client bundle’s META-INF/spring folder so that the Spring-DM extender will find it.

The bean is declared with the init-method attribute set to call the go() method when the bean is created. And we use the <property> element to inject the bean’s translator property with a reference to a bean whose ID is “translator”.

The big question here is: Where does the “translator” bean come from?

Simple service consumption

Spring-DM’s <reference> element mirrors the <service> element. Rather than publishing a service, however, <reference> retrieves a service from the OSGi service registry. The simplest way to consume a Translator service is as follows:


<reference id=”translator”
interface=”com.habuma.translator.Translator” />

When the Spring-DM extender creates a Spring context for the client bundle, it will create a bean with an ID of “translator” that is a proxy to the service it finds in the service registry. With that id attribute and interface, it is quite suitable for wiring into the client bean’s translator property.

Setting a service timeout

In a dynamic environment like OSGi, services can come and go. When the client bundle starts up, there may not be a Translator service available for consumption. If it’s not available, then Spring-DM will wait up to 5 minutes for the service to become available before giving up and throwing an exception.

But it’s possible to override the default timeout using the <reference> element’s timeout attribute. For example, to set the timeout to 1 minute instead of 5 minutes:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	timeout=”60000” />

Notice that the timeout attribute is specified in milliseconds, so 60000 indicates 60 seconds or 1 minute.

Optional service references

Another way to deal with the dynamic nature of OSGi services is to specify that a service reference is optional. By default, the cardinality of a reference to a service is “1..1”, meaning that the service must be found within the timeout period or else an exception will be thrown. But you can specify an optional reference by setting the cardinality to “0..1”:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	cardinality=”0..1” />

Filtering services

Imagine that we have two or more Translator services published in the OSGi service registry. Let’s say that in addition to the Pig Latin translator there’s also another Translator service that translates text into Elmer Fudd speak. How can we ensure that our client gets the Pig Latin service when another implementations may be available?

Earlier, we saw how to set a property on a service when it’s published. Now we’ll use that property to filter the selection of services found on the consumer side:


<reference id=”translator”
	interface=”com.habuma.translator.Translator”
	filter=”(translator.language=Pig Latin)” />

The filter attribute lets us specify properties that will help refine the selection of matching services. In this case, we’re only interested in a service that has its “translator.language” property set to “Pig Latin”.

Consuming multiple services

But why choose? What if we wanted to consume all matching services? Instead of pin-pointing a specific service, we can use Spring-DM’s <list> element to consume a collection of matching services:


<list id=”translators”
	interface=”com.habuma.translator.Translator” />

The Spring-DM extender will create a list of matching services that can be injected into a client bean collection property such as this one:


private List<Translator> translators;
public void setTranslators(List<Translator> translators) {
  this.translators = translators;
}

Optionally, you can use Spring-DM’s <set> element to create a set of matching services:


<set id=”translators”
   interface=”com.habuma.translator.Translator” />

The <list> and <set> elements share many of the same attributes with <reference>. For example, to consume a set of all Translator services filtered by a specific property:


<set id=”translators”
interface=”com.habuma.translator.Translator”
filter=”(translator.language=Elmer Fudd)” />

Testing Bundles

Hopefully, you’re in the habit of writing unit tests for your code. If so, that practice should extend to the code that is contained within your OSGi bundles. Because Spring-DM encourages POJO-based OSGi development, you can continue to write unit-tests for the classes that define and consume OSGi services just like you would for any other non-OSGi code.

But it’s also important to write tests that exercise your OSGi services as they’ll be used when deployed in an OSGi container. To accommodate in-OSGi integration testing of bundles, Spring-DM provides AbstractConfigurableBundleCreatorTests, a JUnit 3 base test class from which you can write your bundle tests.

What’s fascinating is how tests based on AbstractConfigurableBundleCreatorTests work. When the test is run, it starts up an OSGi framework implementation (Equinox by default) and installs one or more bundles into the framework. Finally, it wraps itself in an on-the-fly bundle and installs itself into the OSGi framework so that it can test bundles as an insider.

Writing a basic OSGi test

To illustrate, let’s write a simple test that loads our Translator interface bundle and the Pig Latin implementation bundle:


package com.habuma.translator.test;
import org.osgi.framework.ServiceReference;
import org.springframework.osgi.test.
AbstractConfigurableBundleCreatorTests;


import com.habuma.translator.Translator;
public class PigLatinTranslatorBundleTest
      extends AbstractConfigurableBundleCreatorTests {
  @Override
  protected String[] getTestBundlesNames() {
     return new String[] {
		“com.habuma.translator, interface, 1.0.0”,
		“com.habuma.translator, pig-latin, 1.0.0”
      };
  }
  public void testOsgiPlatformStarts() {
    assertNotNull(bundleContext);
  }
}

The getTestBundleNames() method returns an array of Strings where each entry represents a bundle that should be installed into the OSGi framework for the test. The format of each entry is a comma-separated set of values that identify the bundle by its Maven group ID, artifact ID, and version number.

So far, our test has a single test method, testOsgiPlatformStarts(). All this method does is test that the OSGi framework has started by asserting that bundleContext (inherited from AbstractConfigurableBundleCreatorTests) is not null.

Testing OSGi service references

A more interesting test we could write is one that uses the bundle context to lookup a reference to the Translator service and assert that it meets our expectations:


public void testServiceReferenceExists() {
  ServiceReference serviceReference =
    bundleContext.getServiceReference(Translator.class.
getName());
	assertNotNull(serviceReference);
	assertEquals(“Pig Latin”,
       serviceReference.getProperty(“translator.language”));
}

Here we retrieve a ServiceReference from the bundle context and assert that it isn’t null. This means that some implementation of the Translator service has been published in the OSGi service registry. Then, it examines the properties of the service reference and asserts that the “translator.language” property has been set to “Pig Latin”, as we’d expect from how we published the service earlier.

Testing OSGi services

One more thing we could test is that the Translator service does what we’d expect it to do. Certainly, this kind of test usually belongs in a unit test. But it’s still good to throw a smoke test its way to make sure that we’re getting the service we’re expecting.

We could use the ServiceReference to lookup the service. But, we can avoid any additional work with the OSGi API by having the Translator service wired directly into our test class. First, let’s add a Translator property and setter method to our test class


private Translator translator;
public void setTranslator(Translator translator) {
  this.translator = translator;
}

When the test is run, Spring will attempt to autowire the property with a bean from its own Spring application context. But we haven’t defined a Spring application context for the test yet. Let’s do that now:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans:beans xmlns:beans=”http://www.springframework.org/schema/
beans”
		xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
		xmlns=”http://www.springframework.org/schema/osgi”
   xsi:schemaLocation=”http://www.springframework.org/schema/
beans
      http://www.springframework.org/schema/beans/spring-beans.
xsd
    http://www.springframework.org/schema/osgi
    http://www.springframework.org/schema/osgi/spring-osgi.xsd”>
  <reference id=”translator”
    interface=”com.habuma.translator.Translator” />
</beans:beans>

You’ll recognize that this Spring context definition looks a lot like the one we created for the service consumer. In fact, our test class will ultimately be a consumer of the Translator service. We just have one more thing to do before we can test the service—we’ll need to override the getConfigLocations() method to tell the test where it can find the context definition file:


@Override
protected String[] getConfigLocations() {
   return new String[] { “bundle-test-context.xml” };
}

Now we can write our test method:


public void testTranslatorService() {
	assertNotNull(translator);
	assertEquals(“id-DAY is-thAY ork-wAY”,
       translator.translate(“Did this work”));
}

This method assumes that by the time it is invoked, the translator property has been set. It first asserts that it is not null and then throws a simple test String at it to test that the service does what we expect.

Changing the tested OSGi framework

By default, Spring-DM tests are run within Equinox. But you can change them to run within another OSGi framework implementation such as Apache Felix or Knopflerfish by overriding the getConfigLocations() method. For example, to run the test within Apache Felix:


@Override
  protected String getPlatformName() {
    return Platforms.FELIX;
}

Or for Knoplerfish:


@Override
protected String getPlatformName() {
  return Platforms.KNOPFLERFISH;
}

Providing a Custom Manifest

When a Spring-DM test gets wrapped up in an on-the-fly bundle, a manifest will be automatically generated for it. But if you’d like to provide a custom manifest. To provide a custom manifest for the on-the-fly bundle, all you need to do is override the getManifestLocation(). For example:


protected String getManifestLocation() {
  return “classpath:com.habuma.translator.Translator.MF”;
}

Be aware, however, that if you provide a custom manifest, you must include a few things in that manifest to make Spring-DM testing work. First, you’ll need to specify a bundle activator:


Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator

And you’ll need to import JUnit and Spring-DM packages:


Import-Package: junit.framework,
  org.osgi.framework,
  org.apache.commons.logging,
  org.springframework.util,
  org.springframework.osgi.service,
  org.springframework.osgi.util,
  org.springframework.osgi.test,
  org.springframework.context

References

Example Source Code:

http://www.habuma.com/refcard/spring-dm/translator.zip

Spring-DM Homepage:

http://www.springframework.org/osgi

OSGi Alliance:

http://www.osgi.org

Modular Java on Twitter:

http://twitter.com/modularjava

Craig’s Modular Java Blog:

http://www.modularjava.com

Craig’s Spring Blog:

http://www.springinaction.com

56 76

About The Author

Photo of Craig Walls

Craig Walls

is a Texas-based software developer with more than 15 years experience working the telecommunication, financial, retail, education, and software industries. He’s a zealous promoter of the Spring Framework, speaking frequently at local user groups and conferences and writing about Spring and OSGi on his blog. When he’s not slinging code, Craig spends as much time as he can with his wife, two daughters, six birds, and two dogs.

Craig’s Publications:

  • Modular Java: Creating Flexible Applications with OSGi and Spring, 2009
  • Spring in Action, 2nd Edition, 2007
  • XDoclet in Action, 2003

Craig’s Blog: http://www.springinaction.com

Recommended Book

Spring in action

Newcomers will find a thorough introduction to the framework, while experienced Drupal developers will learn best practices for building powerful websites. With Using Drupal, you’ll find concrete and creative solutions for developing the exact community website you have in mind.


Recommended Book

ModularJava

Modular Java is filled with tips and tricks that will make you a more proficient OSGi and Spring-DM developer. Equipped with the know-how gained from this book, you’ll be able to develop applications that are more robust and agile.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Getting Started with BIRT

By Virgil Dodson

12,396 Downloads · Refcard 49 of 151 (see them all)

Download
FREE PDF


The Essential BIRT Cheat Sheet

Eclipse Business Intelligence and Reporting Tools (BIRT) is an open source, Eclipse-based reporting system that integrates with your Java/J2EE application to produce compelling reports. BIRT is the only top-level Eclipse project focused on business intelligence.This DZone Refcard provides an overview of the BIRT components focusing on a few key capabilities of the BIRT Designer, BIRT Runtime APIs, and BIRT Web Viewer. This Refcard should be interesting to report designers as well as developers or architects involved in integrating BIRT reports into applications.
HTML Preview
BIRT

Getting Started with BIRT

By Virgil Dodson

What Is Birt?

Eclipse Business Intelligence and Reporting Tools (BIRT) is an open source, Eclipse-based reporting system that integrates with your Java/J2EE application to produce compelling reports. BIRT is the only top-level Eclipse project focused on business intelligence. BIRT provides core reporting features such as report layout, data access and scripting. This Refcard provides an overview of the BIRT components focusing on a few key capabilities of the BIRT Designer, BIRT Runtime APIs, and BIRT Web Viewer. This Refcard should be interesting to report designers as well as developers or architects involved in integrating BIRT reports into applications.

Design and Runtime components

BIRT has two main components: a report designer based on Eclipse, and a runtime component that you can add to your application. The charting engine within BIRT can also be used by itself, allowing you to add charts to your application.

Birt Components

Getting birt

Open Source BIRT can be downloaded from http://download. eclipse.org/birt/downloads/ or http://www.birt-exchange. com. There are several different packages containing BIRT depending on your needs.

BIRT All-In-One
Download
The fastest way to get started designing BIRT reports on Windows.
Includes everything you need to start designing BIRT Reports,
including the full Eclipse SDK.
BIRT Framework This download allows you to add the BIRT plug-in to your existing
Eclipse environment. (Make sure you check the dependencies and
update those too.)
RCP Designer Simple to use rich client version of the BIRT Report Designer
dedicated to creating reports without the rest of the Eclipse
development environment.
BIRT Runtime Deployment components of the BIRT project including a command
line example, API examples, and example web viewer.
BIRT Web Tools Integration Contains the plug-ins required to use the BIRT Web Project Wizard
and the BIRT Viewer JSP tag library.

Hot Tip

You can also get BIRT into your existing Eclipse environment through the Eclipse Update Manager. Be sure to also select the Data Tools Project when using this approach.

BIRT report designers

BirtReport

The BIRT report designers are easy-to-use, visual report development tools that meet a comprehensive range of reporting requirements. The report designers include taskspecific editors, builders, and wizards that make it easy to create reports that can be integrated into web applications. All BIRT report designers support:

  • Component-based model for reuse
  • Ease of use features
  • Support for a wide range of reports, layouts and formatting
  • Programmatic control
  • Data access across multiple data sources

BIRT FILE TYPES

Design File
(*.rptdesign)
An XML file that contains the data connection infromation, report layout and instructions. Created when making a report in the BIRT Designer.
Template File
(*.rpttemplate)
Ensures all reports you create start with some common elements such as a company header or predefined syles. The starting point for a BIRT report.
Library File
(*.rtplibrary)
Stores commonly used report elements, such as a company logo, so they are managed in one place for all reports.
Report Document
(*.rtpdocument)
The completed report including layout instructions and data. Can be transformed into final report output, such as HTML, PDF, and XLS.

BIRT Data Sources

BIRT supports a variety of data sources and can be extended to support any data to which you have access. In addition to the list below, BIRT also ships with a connection to the ClassicModels sample database and can be easily extended to connect to your custom data source. BIRT also includes a Joint Data Set which allows you to join data across data sources.

Flat File Data Source Supports tab, comma, semicolon, and pipe delimited data
JDBC Data Source Supports connections to relational databases
Scripted Data Source Allows you to communicate with Java objects or to any data you can get from you application.
Web Services Data
Source
Supports connections to a web service. A wizard helps you point at a service through a WSDL and select the data
XML Data Source Supports data from XML

Palette of report items

label Use to include static (or localized) text within a report. Typically for report titles, column headers or any other report text.
text Use to include richly formatted text to your report, including the ability to integrate HTML formatting with your dynamic data.
DynamicText Use to integrate your static text with dynamic or conditional data.
data Use to include data from your connection in the report.
image Use to include images from various embedded sources or dynamic locations.
grid Use to define the layout of a report. Can be nested within other grids to support complex layouts.
list Use to display Data elements from your data source that repeat and creates a new report row for each daata set row. Can contain multiple levels of grouping.
table Use to display repeating data elements within your report and has support for multiple columns and multiple levels of grouping.
chart Use to add rich, interactive charting to your BIRT report.
Cross Tab Use to display grouped and dynamic data by both the row and column level.
aggregation Use to build totals for tables and groups. Includes over 30 built-in functions like COUNT, SUM, MAX, MIN, AVE, RUNNINGSUM, COUNTDISTINCT, and RANK.

Chart types

Bar Chart1 Side-by-Side Bar Charts show bars from each series
one beside the other. These bars are arranged so that
they each have the same width. The width of the bars
depends on the number of series being plotted.
Stacked Bar Charts show bars stacked one above the
other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Bar Charts show bars stacked one
over the other in such a way that the total height of the
stacked bar (from its lowest to its highest) is 100%
Line Chart2 Overlay Line Charts show lines from each series
independent of the others. The lines are shown joining
the values for the series.
Stacked Line Charts show lines stacked one above
the other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Line Charts show lines stacked one
over the other in such a way that the total height of the
stacked lines (from the lowest point to the highest in
each unit) is 100%
Area Chart3 Overlay Area Charts show areas from each series
independent of the others. The areas are shown
joining the values for the series.
Stacked Area Charts show areas stacked one above
the other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Area Charts show areas stacked one
over the other in such a way that the total height of the
stacked areas (from the lowest point to the highest in
each unit) is 100%
Pie Chart4 Pie Charts show values as slices of a pie. The size of
each slice is proportional to the value it represents. Pie
charts for multiple series are plotted as multiple pies,
one for each series.
Meter Chart5 Standard Meter Charts contain a single dial with
region(s). The background of the dial can be divided
into regions with different colors.
Superimposed Meter Charts contain multiple dials
with identical regions. The dials overlap together so
that it can represent multiple needles within a single
region.
Scatter Chart6 Scatter Charts show the values arranged on the plot
using the category and value data as coordinates. Each
data value is indicated by a marker.
Stock Chart7 A Candlestick Stock Chart contains a box with lines
extending up and down from the ends. The upper and
lower edges of the box are the stock open and close
values. The upper and lower points of the line are the
high and low values.
A Bar-Stick Stock Chart contains a vertical line with
two horizontal lines sticking to it. The upper and lower
points of the vertical line are the stock open and close
values. The two horizontal lines are the high and low
values.
Bubble Chart8 Bubble Charts show the values arranged on the plot
using the category and value data as coordinates. Each
data value is indicated by a marker.
Difference Chart9 Difference Charts use two fills to represent the
positive and negative areas
Gantt Chart10 Standard Gantt Charts contain a connection line with
start and end markers.
Tube Chart1 Side-by-Side Tube Charts show tubes from each
series one beside the other. These tubes are arranged
so that they each have the same width. The width of
the tubes depends on the number of series being
plotted.
Stacked Tube Charts show tubes stacked one above
the other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Tube Charts show tubes stacked
one over the other in such a way that the total height
of the stacked tube (from its lowest point to its highest)
is 100%
Cone Chart11 Side-by-Side Cone Charts show cones from each
series one beside the other. These cones are arranged
so that they each have the same width. The width of
the cones depends on the number of series being
plotted.
Stacked Cone Charts show cones stacked one above
the other. The positive and negative values are stacked
separately above and below the origin.
Percent Stacked Cone Charts show cones stacked
one over the other in such a way that the total height
of the stacked cone (from its lowest point to its highest)
is 100%
Pyramid Chart12 Side-by-Side Pyramid Charts show pyramids from
each series one beside the other. These pyramids are
arranged so that they each have the same width. The
width of the pyramids depends on the number of
series being plotted.
Stacked Pyramid Charts show pyramids stacked one
above the other. The positive and negative values are
stacked separately above and below the origin.
Percent Stacked Pyramid Charts show pyramids
stacked one over the other in such a way that the total
height of the stacked pyramid (from its lowest point to
its highest) is 100%

Hot Tip

Creating your first report:
  • Create a new Report Project from the category of Business Intelligence of Reporting Tools. Change to the Report Design perspective.
  • File -> New ->Report. Select the template called “My First Report” which launches a cheat sheet containing a step-by-step tutorial assisting you with connecting to data sources, creating data sets, and laying out your report.

Localization

BIRT supports internationalization of report data including support for bidirectional text. BIRT also supports the localization of static report elements within a report allowing you to replace report labels, table headers, and chart titles with localized text. BIRT uses resources files with name/value pairs and a *.properties file extension. For example, a file called MyLocalizedText_de.properties can include a line that says “welcomeMessage=Willkommen”. To use these files within a BIRT report:

Assign Resource File to entire report Report -> Properties -> Resources -> Resource File
Assign individual keys to a label Label -> Properties -> Localization -> Text key

Styles

Reports designed with the BIRT report designer can be richly formatted with styles that match your existing web application

Built-in Styles Built-in styles can be shared in a report library for managing style across multiple reports.
CSS Style Sheet BIRT can import CSS files at design time or reference existing CSS files at run time.

Report Parameters

A BIRT report can contain parameters that effect the report. Parameters can be supplied by the user or passed in programmatically from the application. Parameters can be bound to a data set query effectively filtering the report data. Parameters can also be used in expressions and scripting. For example, a parameter can be used with a visibility expression to hide a column or entire table. Available report parameter values can be supplied from a static list, dynamically created from a data set, or even cascading dynamic parameters. For example, selecting a Country presents the available States, and selecting a State presents the available Cities. Related parameters can be grouped for easier user navigation.

Parameter collection from the user can be in several forms:

Text Box Empty text area where the user can type the values desired
Combo/List Box A list of values is presented to the user. This list can be provided as a
static list or dynamically generated based on a data set query. multiple
values can be accepted.
Radio Button Provides boolean Yes/No, True/False, On/Off of parameters
Custom Parameters can be passed in programmatically so you can creae your
own web front end to collect the parameters from the user.

Customization wi th expressions, scripting and Events

BIRT includes out-of-the-box functionality that is available through drag-and-drop or by setting some properties, but also supports more advanced customizations through expressions, scripting, and events. The expression builder in BIRT allows you to do conditional report processing just about anywhere you need to instead of hard coding values. For example, the expression below will display the shipped date for orders that have already shipped, otherwise, it will display the order date.


if (dataSetRow[“STATUS”] == “Shipped”) {
  dataSetRow[“SHIPPEDDATE”];
} else {
  dataSetRow[“ORDERDATE”];
}

Scripting of a BIRT report can be done in either JavaScript or Java depending on your skill set and needs. Scripting allows you to circumvent the traditional event processing of the BIRT report. You can add scripting to report object, data source, and data element event types. Each of these event types has several events that you can overwrite.

For example, you can use scripting to navigate your Java objects and add them to a BIRT Data Set.


favoritesClass = new Packages.SimpleClass();
favorites = favoritesClass.readData();
…
var favrow = favorites.get(currentrow);
var Customer = favrow[0];
var Favorite = favrow[1];
var Color = favrow[2];
row[“Customer”]=Customer;
row[“Favorite”]=Favorite;
row[“Color”]=Color;

Use scripting to change bar colors on a chart based on plotted data.


if (dph.getOrthogonalValue() < 1000) {
  fill.set(255,0,0); //red
} else if (dph.getOrthogonalValue() < 5000) {
  fill.set(255,255,0); //yellow
} else {
  fill.set(0,255,0); //green
}

Use scripting to add or drop a report table based on a user parameter.


if (params[“showOrders”] == false){
  reportContext.getReportRunnable().designHandle.getDesignHandle()
    .findElement(“table1”).drop();
}

Or use scripting to include dynamic images that are based on the report data.


if (row[“CREDITLIMIT”] <= 0) {
“down.jpg”
} else {
“up.jpg”
}

Report deployment options

Once you create your report designs, there are several different ways to generate the report output. Obviously, you can run these reports directly from the BIRT Designer, but you can also run BIRT reports from the command line, generate BIRT reports from you Java application using the BIRT APIs, integrate and customize the example web viewer, or deploy your reports with third-party components and report servers.

APIs

BIRT supplies several APIs and an example J2EE application for generating and viewing reports. The major APIs are the Design Engine API(DE API), Report Engine API(RE API) and the Chart Engine API (CE API). In addition to the APIs, BIRT supports scripting using either Java or JavaScript within report designs.

Design Engine API(DE API) Use the Design Engine API (DE API) to create a custom report designer tool, or to explore or modify BIRT report designs. The BIRT Designer uses this API. You can call this API within a BIRT script to modify the currently running report design.
Report Engine API(RE API) Use the Report Engine API to run BIRT reports directly from Java code or to create a custom web application front end for BIRT.
Chart Engine API(CE API) Use the Chart Engine API to create and render charts apart from BIRT.

Birt report engine tasks

There are several tasks supplied by the Report Engine API that can be used to generate report output. A few key tasks are listed below.

IRunAndRenderTask Use this task to run a report and create the output directly to one of the supported output formats. This task does not create a report document.
IRunTask Use this task to run a report and generate a report document, which is saved to disk.
IGetParameterDefinitionTask Use this task to obtain information about parameters and their default values.
IDataExtractionTask Use this task to extract data from a report document. The BIRT viewer uses this class to extract report data into CSV format.

World ’s Simplest birt engine example


static void executeReport() throws EngineException
{
  IReportEngine engine=null;
  EngineConfig config = null;
try{
  // start up Platform
  config = new EngineConfig( );
  config.setBIRTHome(“C:\\BIRT_231\\birt-runtime-2_3_1\\
  ReportEngine”);
  config.setLogConfig(“C:\\BIRT_231\\logs”, java.util.logging.Level.
  FINEST);
  Platform.startup( config );
  // create new Report Engine
  IReportEngineFactory factory = (IReportEngineFactory) Platform
  .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_
  ENGINE_FACTORY );
  engine = factory.createReportEngine( config );
  // open the report design
  IReportRunnable design = null;
  design = engine.openReportDesign(“C:\\BIRT_231\\designs\\param
  .rptdesign”);
  // create RunandRender Task
  IRunAndRenderTask task = engine.createRunAndRenderTask(design);
  // pass necessary parameters
  task.setParameterValue(“ordParam”, (new Integer(10101)));
  task.validateParameters();
  // set render options including output type
  PDFRenderOption options = new PDFRenderOption();
  options.setOutputFileName(“my_report.pdf”);
  options.setOutputFormat(“pdf”);
  task.setRenderOption(options);
  // run task
  task.run();
  task.close();
  engine.destroy();
}catch( Exception ex){
	ex.printStackTrace();
}
finally
{
  Platform.shutdown( );
}


Hot Tip

If you are deploying the BIRT Engine within an RCP application you should NOT set the BIRT Home variable or execute the Platform.startup() method.

WEb Viewer

Web Viewer

The BIRT WebViewer is an example application that illustrates generating and rendering BIRT report output in a web application. This viewer demonstrates report pagination, an integrated table of contents, report export to several formats, and printing to local and server side printers.

The BIRT Web Viewer can be used in a variety of ways:

Stand-alone Use as a pre-built web application for running and viewing reports.
Modify Viewer Source Use as a starter web application that you can customize to your needs.
RCP Application Use as a plug-in for your existing RCP application.
Integrated with existing web application The viewer can be integrated with URLs or BIRT JSP tag library.

The BIRT Web Viewer consists of two main Servlets, the ViewerServlet and the BirtEngineServlet. These Servlets handle three mappings: (/frameset, /run, and /preview).

/frameset Renders the report in the full AJAX viewer, complete with toolbar, navigation bar
and table of contents features. This mapping also generates an intermediate
report document from the report design file to support the AJAX based features.
For example.
http://localhost:8080viewer/frameset?_report=myreport .rptdesign&parm1=value
/run Runs and renders the report but does not create a report document. This
mapping does not supply HTML pagination, TOC or toolbar features, but does
use the AJAX framework to collect parameters, support report cancelling and
retrieve the report output in HTML format. For example.
http://localhost:8080/viewer/run?_report=myreport.rptdesign&parm1=value)
/preview Runs and renders the report but does not generate a report document, although
an existing report document can be used; in this case, just the render operation
occurs. The output from the run and render operation is sent directly to the
browser. For example
http://localhost:8080/viewer/prevew?_report=myreport.rptdesign&parm1=value)

Viewer URL Parameters

Below are a few of the key URL parameters available for the viewer. These parameters can be used along with the Servlet mappings, such as, run, frameset, and preview, listed in the Web Viewer section.

Attribute Description
__id Unique identifier for the viewer.
__title Sets the report file.
__showtitle Determines if the report title is shown in the frameset viewer. Defaults to true. Valid values are true and false.
__toolbar Determines if the report toolbar is shown in the frameset viewer. Defaults to true. Valid values are true and false.
__navigationbar Determines if the navigation bar is shown in the framset viewer. Defaults to true. Valid values are true and false.
__parameterpage Determines if the parameter page is displayed. By default, the frameset, run, and preview mappings automatically determine if the parameter page is required. This setting overrides this behavior. Valid values are true and false.
__report Sets the name of the report design to process. This setting can be absolute path or relative to the working folder.
__document Sets the name for the rptdocument. The document is created when the report engine separates run and render tasks, and is used to support features like table of contents and pagination. This setting can be an absolute path or relative to the working folder.
__format Specifies the desired output format, such as pdf, html, doc, ppt, or xls.
__Locale Specifies the locale for the specific operation. Note that this setting overrides the default locale.
__page Specifies page to render.
__pagerange Specifies page range to render such as, 1-4, 7.
__bookmark Specifies a bookmark in the report to load. The viewer automatically loads the appropriate page.

Viewer Web.xml settings

The BIRT Web Viewer has several configuration options. These settings can be configured by modifying the web.xml file located in the WebViewerExample/WEB-INF folder. Below are a few of the key settings available for the viewer.

Attribute Description
BIRT_VIEWER
_LOCALE
This setting sets the default locale for the Web Viewer.
BIRT_VIEWER
_WORKING
_FOLDER
This is the default location for report designs. If the report design specified
in a URL parameter is relative, this path is pre-pended to the report name.
BIRT_VIEWER
_DOCUMENT
_FOLDER
If the __document parameter is not used, a report document is generated
in this location. If this setting is left blank, the default value, webapp/
documents, is used. If the__document URL parameter is used and the value
is relative, the report document is created in the working folder.
BIRT_VIEWER
_IMAGE_DIR
Specifies the default location to store temporary images generated by the
report engine. If this setting is left blank, the default location of webapp/
report/images is used.
BIRT_VIEWER
_LOG_DIR
Specifies the default location to store report engine log files. If this setting
is left blank, the default location of webapp/logs is used.
BIRT_VIEWER
_LOG_LEVEL
Sets the report engine log level. Valid values are:
OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, and FINEST.
BIRT_VIEWER
_SCRIPTLIB_DIR
Specifies the default location to place JAR files used by the script engine
or JARs containing Java event handlers. These JARs are appended to the
classpath. If this setting is left blank the default value of webapp/scriptlib
will be used.
BIRT_
RESOURCE_
PATH
This setting specifies the resource path used by report engine. The
resource path is used to search for libraries, images, and properties files
used by a report. If this setting is left blank, resources are searched for in
BIRT_VIEWER
_MAX_ROWS
Specifies the maximum number of rows to retrieve from a dataset
BIRT_VIEWER
_PRINT
_SERVERSIDE
This setting specifies whether server side printing is supported. If
set to OFF the toolbar icon used for server side printing is removed
automatically. Valid values are ON and OFF.

Viewer JSP Tag library

The BIRT Web Viewer includes a set of tags to make it easy to integrate BIRT reports into browser pages. These tags are available from the BIRT Web Tools Integration download. Below are a few the key JSP tags and a description of their usage.

Tag Description
viewer Displays the complete Viewer inside an IFRAME. This tag allows you to use frameset and run Servlet mappings. The AJAX Framework is used.
report Displays the report inside an IFRAME or DIV tag without the Viewer. This tag allows you to use preview mapping and does not create an rptdocument. The AJAX Framework is not used.
param Used to set parameter values when using the viewer or report tags. This tag must be nested within the viewer or report tag.
value Used to specify multiple values for a given param tag.
parameterPage Used to launch the BIRT parameter dialog or to create a customized parameter entry page. This tag can be used with the frameset, run, or preview mappings to launch the viewer after the parameters are entered.
paramDef Used within a parameterPage tag to retrieve pre-generated HTML for specific parameter control types such as radio, checkbox, dynamic or cascaded parameters

Simple viewer jsp tag example


<%@ taglib uri=”/birt.tld” prefix=”birt” %>
…
<birt:viewer
id=”birtViewer” pattern=”preview”
reportDesign=”TopNPercent.rptdesign”
height=”600” width=”800”
format=”html”
title=”My Viewer Tag”
isHostPage=”false”
showTitle=”true” showToolBar=”true”
showNavigationBar=”true”
showParameterPage=”true”>
</birt:viewer> 

BIRT REPORT OUTPUT FORMATS

In addition to delivering paginated report content to a web browser, BIRT also supports several other output formats. These formats listed below are support by both the Report Engine API as well as the BIRT Web Viewer.

Paginated web output An example web viewer is included with BIRT allowing for on demand paginated web output.
DOC Microsoft Word Document.
HTML Suitable for creating HTML pages of report data deployable to any server.
PDF Adobe PDF output suitable for emailing or printing.
Postscript Output can be directed to a printer that supports postscript.
PPT Powerpoint output.
XLS Excel file output.

Birt extension points

The APIs in BIRT define extension points that let the developer add custom functionality to the BIRT framework. These extensions can be in the form of custom data sources, report items, chart types, output formats, and functions. Once implemented, these custom extensions will show along with the built-in types. For example, you can create a custom report item, like a rotated text label, that will show up in the BIRT Palette along with the existing items.

Data Sources BIRT supports the Open Data Access (ODA) architecture, which means it can be extended to support custom data sources.
Functions BIRT allows you to create custom functions that extend those available in BIRT Expressions.
Report Items Report Items can be extended, allowing you to create your own custom report item.
Chart Types Additional chart types can be added to BIRT as plug-ins.
Output Emitters BIRT can be extended to include your own custom output type. For example, a simple CSV emitter exists and can be added to BIRT.

Additional Birt resources

Eclipse BIRT Project Site http://www.eclipse.org/birt
BIRT Exchange Community Site http://www.birt-exchange.com
Submitting/Searching BIRT Bugs http://bugs.eclipse.org/bugs/enter_bug.cgi?product=BIRT
Online BIRT Documentation http://www.birt-exchange.com/modules/documentation/

About The Author

Photo of author Virgil Dodson

Virgil Dodson

Virgil Dodson is a Developer Evangelist at Actuate Corporation and blogger/forum moderator at the BIRT Exchange community site. Virgil has over 13 years experience as a software developer. For the past 6 years he has helped Java developers get started with Actuate’s embedded reporting products. He holds a Bachelor of Science degree in Computer Information Systems from DeVry.

Recommended Book

Birt

Topics Discussed Include: Installing and deploying BIRT Deploying a BIRT report to an application server Understanding BIRT architecture Scripting in a BIRT report design Integrating BIRT functionality in applications Working with the BIRT extension framework


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

IntelliJ IDEA

Updated for 8.1

By Hamlet DArcy

7,700 Downloads · Refcard 52 of 151 (see them all)

Download
FREE PDF


The Essential IntelliJ IDEA Cheat Sheet

IntelliJ IDEA Looking to update your IntelliJ IDEA IDE? In this DZone Refcard, updated for IntelliJ IDEA 8.1, author Hamlet D’Arcy helps you navigate the various facets of this world-class IDE, including the Editor, Project, and Structure panes. With a rich collection of editing shortcuts, debugging tips and techniques for writing less code, IntelliJ newbies and IDEA-savvy developers will both benefit with this cheat sheet by their side. Still using IntelliJ IDEA 6.0? Relax, our original IntelliJ IDEA Refcard is exactly what you need.
HTML Preview
IntelliJ IDEA

IntelliJ IDEA

By Hamlet D'Arcy

ABOUT INTELLIJ IDEA

Software developers know the importance of using the best tool for the job. Often this means choosing a world-class integrated development environment (IDE), which JetBrains’ IntelliJ IDEA certainly is. But the best developers don’t just have the right tools, they are experts in those tools. This is a guide to becoming that expert. The basics of navigating and understanding the IDE are covered; but this guide is really about unlocking all the powerful features of the tool and helping you be more productive.

Getting Yourself Oriented

Editor

The three most important elements of the IDE are the Editor pane (a), where your code is shown, the Project pane (b), where your project’s contents are shown, and the Structure pane (c), where the details of the open object are shown.

Editor Pane: Shows the currently active file, with recently viewed files in the tab bar. IntelliJ IDEA shows the most recently used files in the tabs, and there is seldom a need to manually close tabs. If the maximum number of tabs is reached, then the oldest tab is closed when a new tab is opened. Also, there is seldom a need to save a file; file saving is performed automatically in the background. The IDE supports syntax highlighting for many languages, but is also language aware and shows syntax errors as they occur.

Navigate faster by learning these commands:

Back Ctrl+Alt+Left Move back to the last cursor position
Forward Ctrl+Alt+Right Move forward to the next cursor position
Next Tab Alt+Right Activate tab to the right of the active one
Previous Tab Alt+Left Activate tab to the left of the active one
Goto Line Ctrl+G Go to a specific line in the active file
Goto Last Edit
Location
Ctrl+Shift+Backspace Go to the position of the last edit

Hot Tip

Toolbar icons are shown throughout this guide, but you’ll be much faster if you learn the key bindings. The mouse is slow: stop using it! IntelliJ IDEA key bindings have received praise over the years, and many believe they are simply better than other IDE’s default bindings. If you’re switching from another tool, consider learning the new bindings rather than loading an alternate key map. The KeyPromoter plugin can help you with this.

Edit faster by learning these commands:

Move Statement Up Ctrl+Shift+Up Moves the current code block up in the file
Move Statement Down Ctrl+Shift+
Down
Moves the current code block down in the file
Copy/Paste Line Ctrl+C /
Ctrl+V
When nothing is selected, copy, cut, and paste operate on the entire line
Clipboard Stacking Ctrl+Shift+V When copying text, the IDE remembers your previous copies. Use Ctrl+Shift+V to show the clipboard history dialog and paste from a previous copy instead of the most recent clipboard contents
Select/Unselect Word at Caret Ctrl+W /
Ctrl+Shift+W
Selects and unselects the word at the caret. Quickly select or unselect the word, statement, block, and method by repeating this action. Experiment to learn how this works differently depending on where your cursor starts
Toggle Bookmark F11 Sets or removes a bookmark on the current line, which shows as black in both the left and right gutter
Comment/
Uncomment
Ctrl+/ Comments out current selection, or removes comments from current selection. This is supported across many languages
Column Mode Ctrl+Shift+
Insert
Column mode allows you to select a rectangular fragment of code. Effectively using this can greatly speed up bulk edits on structured data like SQL or csv files

Getting Yourself Oriented, continued

Project Pane: Shows the contents of the current project, allowing you to view the project as files, packages, or scopes (more about this later). Objects in the project view visually indicate their type with an icon (which also appears on the editor tabs).

Find objects faster by learning what the icons mean:

code Class code Class with main( )
(indicated by green triangle)
interface Interface interface public
Protector Abstract Class Protector protected
Enumeration Enumeration package package
Exception Exception private private
Annotation Annotation ReadOnly Read Only (indicated by lock)
TestCase Test Case (indicated by red and
green triangles)
Not in version control (object
name appears in red)
FinalClass Final Class (Indicated by pin) In version control (object name
appears black, or blue if edited)

Properly configuring the Project pane makes it more effective:

Autoscroll Autoscroll to Source When an object or method is clicked in the Project pane, that item is opened in the Editor pane.
AutoscrollFrom Autoscroll from Source When an item is opened in the Editor pane, that item is scrolled to in the Project pane
StructurePane Show structure Shows the Structure pane (explained next) as a window nested within the Project pane
FinalClass Show/Hide Members Shows the methods and properties of objects within the Project pane
FinalClass Sort by type Sorts the Java classes by type from the most abstract to the most concrete

Structure Pane: Shows the structure of the active file, including methods, properties, and inner classes. Leaving this pane open helps you quickly locate the desired point within a class. Make this pane more useful by tweaking the configuration options:

Autoscroll Autoscroll to source Properties Show properties
AutoscrollFrom Autoscroll from source inherited Show inherited
visibility Sort by visibility ShowFields Show fields
SortAlphabetically Sort alphabetically non-public Show non-public
GroupMethods Group Methods by defining type

Hot Tip

IntelliJ IDEA provides almost endless amounts of configuration through the Settings (Ctrl+Alt+S) window. Use the search box to quickly find what you need. Just start typing what the option might be called and the window will highlight to show which buttons lead to a panel containing that keyword. Wildcards work too!

Finding What You Need

IntelliJ IDEA sets itself apart by offering incredibly advanced ways to find objects and files within large projects. Mastering the act of finding what you need is key to faster development.

Goto Class Ctrl+N Provides dialog for finding classes. Accepts wildcards, camel case, and package prefixes. For example, “BOS” matches BufferedOutputStream, “Str*Buff” matches StringBuffer, and “java.lang.I” matches all objects starting with “I” in the java.lang package. Use Up/Down error to select the class, and Shift+Up/ Down or Ctrl+Click to perform multiple selections.
Goto File Ctrl+Shift+N Provides a similar dialog for finding files that are not classes. For example, “*spring*xml” matches any xml files with the word “spring” in the name, and “*Test.groovy” matches any test case implemented in Groovy.

The navigation bar is a useful alternative to the Project pane. This horizontal bar provides breadcrumb style navigation based on the active file. To navigate to a different package, simply click the + to expand a node higher up in the tree. The navigation bar can be a faster alternative to the Project pane.

navigationbar

You can also use Alt+Home to quickly open the navigation bar from the current editor pane.

Navigating a single class is done through the Structure pane (described earlier) and the file structure popup.

File Structure Popup: (Ctrl+F12) allows quick navigation to methods, fields, and properties. Use the Up/Down arrows to select an entry, or (better) use the search as you type field. Just start typing to narrow the list down. The field provides wildcard and camel case matching. Selecting an entry scrolls the active file to that entry’s declaration.

Navigating large object oriented codebases is greatly simplified by learning these commands:

Ctrl+B /
Middle Click
Go to declaration. Navigates to the declaration of the selected instance or type.
Ctrl+Alt+B Go to implementers or overriders of the selected method. Clicking the icon in the left gutter performs the same action
Ctrl+U Go to the parent of the selected method or type. Clicking the icon in the left gutter performs the same action
Ctrl+Mouse
Over
Shows the declaration of a local variable or field in a popup window
Ctrl+H Opens the Type Hierarchy pane for the active class. This pane explores the super and subclasses of the current object with a variety of different views
Ctrl+Shift+H Opens the Method Hierarchy pane for the active method. This pane explores the definitions and implementations of the current method.
F4 Jump to Source. Many tool windows display objects within project. Used from a tool window, F4 universally opens the element from the tool in the editor. If you’re in the Ant, Hierarchy, or Find window, then F4 will open the selection in the editor pane.

Finding usages is an important feature of any IDE. Being Java aware, IntelliJ IDEA offers more intelligent searching than simple string matching.

Highlight Usages in File (Ctrl+Shift+F7) takes the current mouse selection and highlights all occurrences of that element in the file. The Editor pane and the right gutter provide visual keys to where the occurrences appear. Use F3 and Shift+F3 to jump to the next and previous occurrence.

Finding What You Need, continued

Show Usages Popup (Ctrl+Alt+F7) takes the current mouse selection and searches the project for any references made to the field or type. Results appear in an in-editor popup window.

Show Usages in Find Panel (Alt+F7) behaves the same as the Show Usages Popup, except that results are displayed in the Find pane. Learning to operate the Find pane with the keyboard helps you move faster to the intended object.

Rerun Rerun the last find
Shift+Esc Rerun Close the Find pane
Ctrl+NumPad + Expand Expand all the nodes in the list
Ctrl+NumPad - Collapse Collapse all the nodes in the list
Ctrl+Alt+Up Rerun Navigate to the previous occurrence
Ctrl+Alt+Down Rerun Navigate to the next occurrence
Ctrl+E Recent Find Usages dialog. Quickly jump to a past search result.

Hot Tip

Turn on Scroll to Source in the Find pane and use Ctrl+Alt+Up and Ctrl+Alt+Down to quickly cycle through the usages in the main editor window.

Search Structurally (Ctrl+Shift+S) and Replace Structurally (Ctrl+Shift+M) allows searching (and replacing) references using patterns. Again, this is Java aware and done structurally, and is not just text string search and replace. This very rich feature is best explained with an example. Here are the steps to find any factory methods within the project (ie, methods whose name starts with “create”):

  • Open Search Structurally (Ctrl+Shift+S)
  • Click “Copy the existing template” and select method calls, which is $Instance$.$MethodCall$($Parameter$)
  • Click “Edit variables” and select MethodCall
  • For the MethodCall variable, enter “create.*” in the Text / Regular Expression. This is the regular expression for the word create followed by any number of other characters
  • Click “Find” to open the Find pane showing all the factory methods

Scopes

Often, you only want to search a subset of your project, for instance just the test or production source. IntelliJ IDEA provides Scopes to create smaller filesets used in searching, replacing, and inspections. Some default scopes are “Project Production Files”, “Project Test Files”, and “Changed Files”. Fine tune your searching by defining your own scope, perhaps based on a set of packages. Scopes can also be helpful to speed up searches on large projects. Here are the steps to define a scope:

  1. Open Settings (Ctrl+Alt+S) and select Scopes
  2. Click Rerun to create a new scope
  3. Select a package to include from the project browser. Use include and include recursively to broaden the fileset, and exclude and exclude recursively to narrow the fileset
  4. Save. New Scope is now available for many operations

Finding Documentation

There are many ways to find documentation on objects within your project and dependencies. Master these commands to get the information you need without leaving the IDE:

Ctrl+P Parameter Info. Displays quick information on the parameter types (and overloading options) of a method call when the caret is within the parenthesis of a method declaration
Ctrl+Q Quick Documentation Lookup. Displays Javadoc in a popup for the item at the caret
Ctrl+Shift+I Quick Definition. Displays the source code for the item at the caret
Shift+F1 External Javadoc. Opens an external browser to the Javadoc for the item at the caret. May require setting Javadoc locations within Settings (Ctrl+Alt+S) Project Settings (1)

Hot Tip

Is an option you need buried deep in the menu system? Use Ctrl+Shift+A to bring up the Action finder. Type the name of the action you’re looking for and IntelliJ IDEA searches the keymap, menus, and toolbars for the item you need to invoke. Wildcards and camelCase works, of course

Running and Debugging Your Project

Running and debugging the project is an essential part of any IDE. The easiest way to run an application is to right click the object within the Editor pane and select Run. This works for classes with main() and test cases. You can also right click the object and do the same thing in the Project pane. To run tests in an entire package simply right click the package.

Manage run targets by using the Run/Debug configurations window, adding any VM parameters or advanced settings you may need. Open the window by clicking Edit Configurations within the toolbar's dropdown.

Toolbar Dropdown

Common run targets can be saved here for future runs.

Running an entry point will display the Run pane. This pane provides diagnostics on the running process. Get the information you need from running processes by learning to use the pane:

Ctrl+F5 Run Run the last target
pause Pause execution
Ctrl+F2 stop Stop execution
Ctrl+Break Dump Thread Dump Thread information to a new window or clipboard
Ctrl+Alt+Up Move Up Move Up Stack Trace, opening the Editor pane to the exception location
Ctrl+Alt+Down Move Down Move Down Stack Trace, opening the Editor pane to the exception location

Running and Debugging Your Project, continued

When debugging an application, the IDE provides a variety of ways to set breakpoints and watchpoints. The easiest is to click the left gutter of the line or method on which you want a breakpoint. More advanced breakpoints are available through the Breakpoints window (Ctrl+Shift+F8).

Line Break on the specified line of code
Exception Break when the specified exception is thrown
Method Break when the specified method is called
Field Break when the specified field instance is accessed or changed

Once stopped on a breakpoint, the Debug pane will open. This pane provides features common to all debuggers, as well as more advanced, uncommon actions.

Alt+F10 ExecutionPoint Show Execution Point
F8 Step Over Step Over
F7 Step Into Step Into
Shift+F7 Smart Step Into. Pick which method to step into when multiple calls exist on one line.
Alt+Shift+F7 Force Step Force Step Into
Shift+F8 Step Out Step Out
Drop Frame Drop Frame
Ctrl+Alt+Up Previous Frame Previous Stack Frame
Ctrl+Alt+Down Next Stack Frame Next Stack Frame
Alt+F9 Cursor Run to Cursor

Hot Tip

Control what not to step into in Settings (Ctrl+Alt+S) Debugger (G). Exclude certain library classes using the “Do not step into” list, skip simple getters, skip constructors, and more.

Once in the debugger, several panels provide different views of the application state. The Frames Panel shows the current stack frames on the selected thread, and you can navigate quickly between frames and threads. The Variables Panel shows any variables currently in scope. And the Watches Panel shows expanded information on selected variables. When entering variables to watch, autocompletion and smart-type both work.

Expression Evaluation (Alt+F8) allows quick execution of code snippets or blocks. From this window you can reference any in-scope variable of the application. It works a bit like a REPL window open with the current breakpoint’s environment, and is most useful in code fragment mode, where you can evaluate multi-line statements.

Hot Tip

Drop Frame within the debugger pops the current stack frame and puts control back out to the calling method, resetting any local variables. This is very useful to repeatedly step through a function, but be warned: field mutations or global state changes will remain.

Code Coverage: IntelliJ IDEA offers code coverage statistics using the EMMA or IntelliJ IDEA toolkit. Enable tracking in the Code Coverage tab of the Run/Debug Configurations window. The built in runner provides more accurate branching coverage when tracing is enabled. Results appear in several places:

Package Coverage Project pane shows % class and % line coverage per package
Class Coverage Project pane shows % class and % line coverage per class
Line Coverage Editor pane left gutter shows red for uncovered line, green for covered line

Code Coverage Data (Ctrl+Alt+F6) displays a list of previous runs, and selecting an entry shows the coverage data for that run. You can use this to compare coverage between subsequent runs.

Hot Tip

Under certain circumstances, code coverage may make your automated tests fail because instrumented bytecode is different than normal bytecode (I’ve seen this happen when remote CORBA interfaces were invoked). If this happens then simply exclude the affected classes from code coverage within the Run/Debug Configurations window.

Write Less Code

Typing less to produce more is a feature of any modern IDE. IntelliJ IDEA provides top tier code completion support, as well as many other code generation, file template, and refactoring features.

Code Completion: Leveraging code completion is essential to productivity:

Ctrl+Space Basic. Completes the names of in-scope classes, methods, fields and keywords. Also complete paths, when appropriate
Ctrl+Shift+Space Smart Type. Displays a suggestion list where the type of the object required can be inferred from the code, such as in the right hand side of assignments, return statements, and method call parameters
Ctrl+Alt+Space Class Name. Completes the names of classes and interfaces. Accepts camel case matching on input
Ctrl+Shift+Enter Complete Statement. Adds closing punctuation and moves cursor to next line
Alt+Slash Expand Word. Cycles through suggested word choices, highlighting the prototype in the editor

Hot Tip

Confused by all the options? Just start using them and let muscle memory take over. It works.

Code Generation: Letting the IDE infer the code you need to create and drop in the appropriate template can be a huge time saver.

Ctrl+O Override Methods... quickly specify a parent method to override and create a stub implementation
Ctrl+I Implement Methods... quickly specify a parent method to implement and create a stub
Code->Delegate Methods... Delegate Methods... creates adapter classes by delegating method calls to member fields. A small wizard guides you through the delegation
Ctrl+Alt+T Surround With... surrounds the current selection with a variety of code wrappers, like if/else, for, try/catch, synchronized, Runnable, and more

Write Less Code, continued

Generate (Alt+Insert) provides its own set of powerful options for code generation:

Constructor Select any of your object’s fields from a list to create a constructor with the proper parameters and body
Getter Select a field from a list to create an accessor method
Setter Select a non-final field from a list to create a mutator method
equals() /
hashCode()
Provides a dialog to automatically create equals() and hashCode() methods based on your object’s fields

Live Templates are fragments of commonly occurring code, which can be inserted into the active file in a variety of ways. Learning the live templates will save you many, many keystrokes. A full list is available in Settings (Ctrl+Alt+S) Live Templates.

To insert a live template, press Ctrl+J followed by the following keys:

psf public static final thr throw new
itar Iterate elements of an
array
sout Prints a string to
System.out
itco Iterate elements of
collection
soutm Prints the current class and method name to System.out
ritar Iterate elements of array
in reverse order
soutv Prints the value of a variable to System.out
toar Stores members of
Collection in Array
psvm main() method declaration

Hot Tip

Logging live templates are very useful, but many projects use log4J or Commons Logging instead of System.out. Replace the System.out calls with your framework within Settings (Ctrl+Alt+S) Live Templates.

Surround with Live Template (Ctrl+Alt+J) will surround the current selection with a block of code. Some of the useful surrounds are:

B Surround with { }
R Surround with Runnable
C Surround with Callable

Hot Tip

Use the existing surrounds templates to create your own, like surround with SwingUtilities.invokeLater() or new Thread().start()

Live Template in Multiple Languages: Many live templates exist for languages other than Java. JSP, XML, Spring definitions, and more all exist. Here are some examples of templates from other platforms and toolsets:

sb Creates an XML based Spring bean definition
sbf Creates an XML based Spring bean definition instantiated by a factory method (many more Spring intentions exist, too)
itws Generate Axis web service invocation (many more flavors of web services supported, too)
CD Surround with CDATA section
T Surround with <tag></tag>

Hot Tip

The free keymap from JetBrains provides a larger list of live templates. Post the keymap next to your monitor to learn the live templates quickly.

Refactoring: IntelliJ IDEA offers excellent refactoring support. Refactoring is aware of comments, reflection, Spring, AOP, JSP, and more. When the refactoring features are unsure on the safety of a refactoring, a preview mode is invoked so that you can verify the changes. Refactoring works on more than just Java code too: many refactorings exists for XML files as well as other languages. Learning the refactoring tools (and reading the refactoring literature, for that matter) is well worth your time. Here are some of the more common refactorings:

Rename Shift+F6 Renames a package, class, method, field or variable
Move F6 Moves an entity
Change Signature Ctrl+F6 Change the method or class name,parameters, return type, and more
Extract Method Ctrl+Alt+M Moves the current selection to a new method, replacing duplicates if found
Inline Ctrl+Alt+N Takes a method, variable, or inner class and replaces usages with a unique definition
Introduce Variable Ctrl+Alt+V Moves the selected expression into a local variable
Introduce Field Ctrl+Alt+F Moves the selected local variable into a field,prompting you for how initialization should occur
Introduce Constant Ctrl+Alt+C Moves the selected variable or field into a static final field, replacing duplicates if found
Introduce Parameter Ctrl+Alt+P Moves the selected local variable into a parameter argument, updating any callers in the process
Extract Interface Moves a set of methods from the object onto an interface, updating callers to reference the interface if possible
Pull Member Up Move a method from a subclass up to an interface or parent class
Encapsulate Fields Provides getter and/or setters for the selected field

Hot Tip

Ctrl+Shift+J will join two lines together, which is a sort of shorthand for inline variable.

Improve Your Project ’s Quality

The IDE’s features aren’t just about writing code faster, they are also about coding more accurately. Understanding the intentions, inspections, and analysis tools are key to keeping code high quality.

Intentions: Keeps code clean by flagging potential problems in the Editor pane as they occur, and then offers an automated solution. An available intention is signaled by a lightbulb appearing in the left gutter, and the suggested fix can be applied by pressing Alt+Enter. There are several types of intentions:

  • n “Create from usage” intentions allow you to use new objects and methods without defining them first. Need a new method? Just call it from code; IntelliJ IDEA will prompt you to create it, inferring the parameter and result types. This works for classes, interfaces, fields, and variables. If the missing reference is in all capital letters, then it will even create a constant for you.

Improve Your Project’s Quality, continued

  • n “Quick fix” intentions find common mistakes and makes context-based suggestions on how to fix them. Examples of issues flagged with a quick fix are assigning a value to the wrong type or calling a private method.
  • “Micro-refactorings” fix code that compiles but could be improved. Examples are removing an unneeded variable and inverting an if condition.

Some of the intentions or fixes might violate your coding standard. Luckily, they can all be configured within Settings (Ctrl+Alt+S) Intentions.

Intentions and Quick Fixes are indicated by different icons in the left gutter, but in practice there is little need to differentiate between the two:

Icon Box

Inspections: Keeps code clean by detecting inconsistencies, dead code, probable bugs, and much, much more. The near-1000 default inspections can do a lot to enforce common idioms and catch simple bugs across the project. There are way too many inspections to list, but here are examples to provide a flavor of what inspections can do:

  • Flag infinite recursion or malformed regular expression
  • Catch error handling issues like continue within finally block or unused catch parameter
  • Find threading issues like await() outside a loop or non-thread safe access
  • Error on Javadoc issues like missing tags or invalid links

Inspections work with many languages and tools beyond the Java language, like Spring, JSF, Struts, XML, JavaScript, Groovy, and many others. The inspection set is highly configurable through Settings (Ctrl+Alt+S) Errors. Each inspection can carry its own set of options, and most can be shown as warnings or errors within the IDE. When an inspection violation is shown in the right gutter, Alt+Enter triggers the suggestions to be shown.

Some inspections appear within the Editor pane, while others appear within the Inspection pane when they are run as a batch. To run inspections for a scope, go to Analyze Inspect Code in the menu.

Inspection settings can be configured and shared across the team. An “IDE” inspection profile is saved within the user’s $HOME directory, but a “Project” profile is saved within the IDEA project file. This means a shared, version controlled project file can be created which contains the team’s inspections.

Hot Tip

By default, IDEA uses a great set of inspections, but many more options are not turned on by default. Check out http://hamletdarcy.blogspot.com/ 2008/04/10-best-idea-inspections-youre-not.html to see some non-default inspections you might want to use.

Code Analysis: Provides several different views of dependencies and duplicates within your project. These tools help you modularize your code and find areas of potential reuse. All of the following features are available from the Analyze menu.

The Dependency Viewer provides a split tree-view of your project with a list panel at the bottom. From here you can navigate the dependencies or mark certain undesirable dependencies as illegal. Which analysis feature chosen determines what the Viewer displays:

Dependencies Left: Your packages. Right: Packages your code depends on
Backward Dependencies Left: Your packages. Right: Packages that depend on your
code. Bottom: Line by line usages
Cyclic Dependencies Left: All of your packages that have a cyclic dependency. Right: The objects that form the cycle. Bottom: Line by line usages

Not all analysis tools report to the Dependency Viewer, however. Module Dependencies uses a separate panel to display dependencies across all the included modules within the project. This is useful for multi-module projects. Dependency Matrix launches the Dependency Structure Matrix in a separate window. This tool helps you visualize module and class dependencies across the project using a colored matrix.

Locate Duplicates: Finds suspected copy and pastes within your project or desired scope. Use this to find and consolidate duplicate modules or statements. The results are displayed in the Duplicates pane, which ranks the copy/paste violations and allows you to extract methods on the duplicates by simply clicking the Eliminate duplicates icon Icon1

Work as a Tea m

IntelliJ IDEA includes many features that allow team members to collaborate effectively.

Version Control (VC) integration exists for Subversion, Git, CVS, Perforce, StarTeam, Visual SourceSafe, TFS, and ClearCase. When enabled, local changes appear as a blue bar in the left gutter:

Version Control

Clicking the blue bar displays some VC options, including a quick line diff (displayed), a rollback of the line changes, or a full file diff in the IntelliJ IDEA Diff Viewer. More VC options are available from the menu or by right-clicking the active editor:

View History See revision history for active file with check-in comments
View
Differences
Launch the side-by-side file comparison window. Merge changes from one file to another, accept non conflicting changes, and more
Annotate Show the user ID of the last person to touch each line in the left gutter

Local History can be used even if you don’t have version control. The IDE keeps track of saves and changes to files, allowing you to rollback to previous versions if desired. Older versions can also be labeled, making it easy to find previous save points.

Shared Project: The project file can be put in version control, keeping all environments up to date as changes are made. Use this guide to the project files to determine what files need to be shared:

.ipr Contains project info like module paths, compiler settings, and library locations. This should be in version control
.iml Used in a multi-module project, each module is described by an .iml file. This should be in version control
.iws Contains workspace and personal settings. This should not be in version control

Work as a Team, continued

File Templates: Shared file templates provide a common starting point for frequently typed code. Templates exist, and can be changed, for creating new classes, interfaces, and enumerations. Templates for includes, like a copyright notice, can also be stored and shared, as well as code templates, like default catch statements and method bodies. Modify the file templates in Settings (Ctrl+Alt+S) File Templates.

Ant Integration: Many projects use Ant as a common build script, and IntelliJ IDEA offers integration with it. Features include syntax highlighting, code completion, and refactorings. Several inspections and intention settings are also available. Use the Ant Build Window to run one or several Ant targets. For larger projects with many targets, use the filter targets feature to hide uncommon targets. The Maven build system is also supported.

Work With the Database

IntelliJ IDEA 8 ships with a data source editor and JDBC console. Once configured with a JDBC or SQL data source, the console is a great environment for working with the database, providig SQL syntax completion, error and syntax highlighting, and completion of the table and column names. Middle click entities like table names or columns to navigate to their definition in the DDL view, and run the entire script (Ctrl+Enter) or snippits (Ctrl+Shift+Enter) using the controls provided. The results pane can be copied to the clipboard as comma separated values. You can also use parameters within the scripts, which are variables marked with the @, #, $, or ? characters. Any parameters found are displayed in the parameters Pane, and from there they can be edited without modifying the SQL source script.

Endless tweaking awaits

A massive amount of configuration options are available in Settings (Ctrl+Alt+S). Beyond that, you may wish to experiment with different plugins. Plugins are installed and managed using Settings (Ctrl+Alt+S) Plugins. Many plugins exist, adding features like Scala, Ruby, or web framework support. JetBrains holds plugin contests annually, so check the site periodically.

About The Author

Photo of author Hamlet D’Arcy

Hamlet D’Arcy

Hamlet D’Arcy has been writing software for over a decade, and has spent considerable time coding in Groovy, Java, and C++. He’s passionate about learning new languages and different ways to think about problems, and recently he’s been discovering the joys of both F# and Scheme. He’s an active member and speaker at the Groovy Users of Minnesota and the Object Technology User Group, and is involved with several open source projects including the Groovy language and the IDEA Jet- Groovy plugin. He blogs regularly at http://hamletdarcy.blogspot.com, tweets as HamletDRC, and can be contacted at hamletdrc@gmail.com.

Recommended Book

Easy PHP Websites with the Zend Framework

For new users, IntelliJ IDEA in Action is a logically organized and clearly expressed introduction to a big subject. For veterans, it is also an invaluable guide to the expert techniques they need to know to draw a lot more power out of this incredible tool. You get a broad overview and deep understanding of the features in IntelliJ IDEA.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


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

Mastering Portal UI Development With Vaadin and Liferay

By Sami Ekblad and James Falkner

7,997 Downloads · Refcard 148 of 151 (see them all)

Download
FREE PDF


The Essential Vaadin and Liferay Cheat Sheet

This cheat sheet will help you with both the Liferay Portal and the Vaadin framework. Liferay Portal is a popular open source technology for building enterprise websites and business applications. Vaadin, an open source web framework, allows you to build web apps with a process that is familiar to desktop developers. This Refcard gives a quick overview of the user interface development with Vaadin on Liferay and it covers topics like portlet setup, configuration, inter-portlet communication (IPC), UI composition, and theming.
HTML Preview
Mastering Portal UI Development With Vaadin and Liferay

Mastering Portal UI DevelopmentWith Vaadin and Liferay

By Sami Ekblad, James Falkner

The open source Liferay Portal has become a popular way of implementing enterprise websites. Providing an integrated platform for application development and deployment, Liferay has also become an environment for running business applications. For application development, Liferay Portal includes Vaadin as a pre-packaged framework for developing attractive, easy-to-use applications.

About this Refcard

This Refcard gives a quick overview of the user interface development with Vaadin on Liferay. It covers topics like portlet setup, configuration, inter-portlet communication (IPC), UI composition, and theming. To get a more general understanding of Liferay Portal and Vaadin framework, see the Refcards “Liferay Essentials” and “Vaadin: A Familiar Way to Build Web Apps With Java”.

STARTING THE DEVELOPMENT

Strategies for Portal User Interface

Portlets are small web applications written in Java. They run in a piece of a web user interface within a portal. Portal manages the lifecycle and aggregation of portlets to a single visible web page. When designing a user interface for a portal, there are a few strategies based on UI granularity:

Strategy Description
Small generic portlets communicating with each other Small user interface, very generic and portal-wide functions:
  • Light-weight, custom user interface
  • Requires more inter-portlet communication
  • Fine-grained portlets for portal-wide reuse
  • Typically small, public applications like search boxes,shopping carts
ntegrated application developed as a single portlet Leverage Liferay as an application platform for a business application:
  • Reuse an existing application user interface or create and application that can run also as standalone application.
  • Complete, integrated user interface
  • Rich desktop-like user experience

portal there are few strategies based on UI granularity:

Naturally, it is possible to have a mixture of these and use different approaches to meet the usability requirements.

Available UI frameworks

Liferay supports a number of web frameworks for development of portlet user interfaces. Which you should use depends on your background as well as the strategy you choose for you application.

Framework Description Programming Languages
Alloy UI Rich client-side JavaScript/CSS framework based on YUI Library. JavaScript, JSP
JavaServerFaces Server-side user interface component framework based on JSP and tag libraries. Java, XML, JSP
Spring MVC Action oriented Model-View-Controller framework for web pages. Java, XML, JSP
Struts 2 Action oriented Model-View-Controller framework for web pages. Java, XML, JSP
Vaadin A rich Java-only component framework based on Ajax/GWT Java
Apache Wicket Server-side component framework based on Java and HTML. Java, HTML

Different portlets can use different frameworks to implement the user interface.

PORTLET DEVELOPMENT WITH VAADIN

Vaadin is a server- and component-oriented user interface framework for Java web applications. Vaadin applications can be hosted as standalone web applications as well as portlets in portals like Liferay. Vaadin is a good choice for building complete applications that use Liferay as a platform.

Portlets created with Vaadin are essentially Ajax web applications that can be considered single-page applications. This means that the page is not reloaded after it is opened initially; rather, it communicates user interaction with the server through Ajax communications.

Along with the desktop-like user experience, Vaadin provides all the typical features of a web framework, such as deep-linking and backbutton support

.

TOOLS FOR VAADIN DEVELOPMENT

Since Liferay 6.x, there have been several tools to help you in developing portlets with Vaadin. These tools are meant to simplify the creation of portlets and help portal administrators maintain the system.

Liferay Plugins SDK

The Liferay Plugins SDK is a development environment that helps in the development of portlets. This development environment is command-line-based and relies on the Apache Ant (though you may also use Maven) and allows development of all types of Liferay plugins.

The Plugins SDK is both a project skeleton generator and a location where your projects are stored. You can download the Plugins SDK from http://liferay.com/downloads/liferay-portal/additional-files.

To get started using the Plugins SDK, refer to the Refcard “Liferay Essentials: A Definitive Guide for Enterprise Portal Development” at http://refcardz.dzone.com/refcardz/essential-liferay-leading-open.

Liferay IDE

Liferay IDE is an extension for the Eclipse IDE that adds support for the development of plug-in projects for the Liferay Portal platform. Since version 1.2, the Liferay IDE has supported Vaadin by offering wizards for creating portlet plugin projects. Up-to-date information about Liferay IDE can be found at http://www.liferay.com/community/ wiki/-/wiki/Main/Liferay+IDE.

The Vaadin Plugin for Eclipse can also be used with the Liferay IDE to give developers the ability to easily create Vaadin+Liferay projects and visually compose Vaadin components and portlets for use within Liferay.

Vaadin Control Panel for Liferay

The Vaadin Control Panel for Liferay gives portal administrators an interface to maintain the portal-wide Vaadin resources. You can use it to:

  • Check and update the Vaadin libraries in portal
  • Recompile the Vaadin widgetset when installing new Vaadin Add-ons.

You can access the Control Panel in Liferay after logging in as an administrator at Manage > Control Panel > Portal > Vaadin.

The latest version of the control panel is available at http://vaadin.com/addon/vaadin-control-panel-for-liferay.

COMPOSING THE USER INTERFACE WITH VAADIN

With Vaadin, the user interface is built from user interface components. They are server-side Java classes that implement a single UI control such as a button, select, or a layout.

With layout components, you can compose larger components that hierarchically build up the application UI.

Vaadin Application

A Vaadin application is defined in a class that extends the com. vaadin.Application. This is the class that you should define as the ‘application’ init-param in portlet.xml as described in later sections.

A new instance of this class is created when a new user comes to portal view where the portlet resides.

Here is the code for a minimal Vaadin application:


package org.vaadin.sample;

import com.vaadin.Application;
import com.vaadin.ui.Label;
import com.vaadin.ui.Window;

public class MyApplication extends Application {
	@Override
	public void init() {
		Window w = new Window();
		w.addComponent(new Label(“Hello Liferay!”));
		setMainWindow(w);
	}
}	

Vaadin UI Components

Vaadin Framework includes over 60 stock components. You can find a rapidly growing number of open-source and commercial add-on components at http://vaadin.com/directory.

Furthermore, you can extend Vaadin by creating new components with the Google Web Toolkit (GWT). GWT is an open-source Javato- JavaScript compiler that allows you to build client-side features without JavaScript. See additional information at http://code.google.com/webtoolkit/.

You can find all the components in the Java package com.vaadin.ui. Add-ons may use their own package naming, but it is typical that they start with org.vaadin.

TIP: You can test and try different Vaadin components online at http:// demo.vaadin.com/sampler. All the demos include source code and documentation.

User Interface Layout

Start by creating a main Window for your application and putting the initial content in there. The user interface structure is a hierarchy of nested layouts and components. Here is an example of a simple user interface hierarchy:


MyApplication
	Window
		VerticalLayout
		 TextField
		 TextField
		 Button

The above UI could be created in Java as follows:

Window w = new Window(“Subscribe Newsletter”); setMainWindow(w); w.setContent(new VerticalLayout());

TextField name = new TextField(“Name”); TextField email = new TextField(“Email”); Button subscribeBtn = new Button(“Subscribe”);

w.addComponent(name); w.addComponent(email); w.addComponent(subscribeBtn);

TIP: You should avoid creating too deeply nested layout structures. In particular, older browsers can become slow. Instead, use the CustomLayout, GridLayout, or some lightweight layouts like the CSSLayout.

User Interface Events

Vaadin is an event-based framework. You can receive user-triggered events in your application by registering a listener for it. Here is an example for Button.ClickEvent:


subscribeBtn.addListener(new Button.ClickListener() {
		@Override
		public void buttonClick(ClickEvent event) {
			// ...
		}
	});

Event listeners are executed in the server side synchronously. You can fetch data and update the user interface by adding and removing components.

TIP: Good practice for event listeners is to only call your Java control code and let them do the UI updates. This is better object-oriented design, and it enhances readability of your Java code.

Vaadin Visual Editor

The visual editor is part of the Vaadin Plugin for Eclipse and is available at http://vaadin.com/eclipse. It includes a WYSIWYG editor for defining a CustomComponent; that is, UI composites in Vaadin.

The visual editor generates the Java code that you can continue to modify and extend.

The visual editor runs inside the Eclipse IDE, giving developers a quick way of creating user interface without writing the code itself.

To activate the visual editor, create a new component using the Eclipse wizard: New > Vaadin CustomComponent (composite), open the file with the right editor Open with > Vaadin Editor, and choose “Design” tab.

Every time you save the file in the Design mode, the Vis ual Designer generates the Java code that makes up the UI.

Note: The Visual editor works with the “reindeer” theme, but you can change the theme in your Application class by calling the setTheme method. For example: myApplication.setTheme(“liferay”)

THEMING VAADIN APPLICATIONS

Vaadin is designed to support parallel work of application developers and graphic designers by strongly separating the graphical elements from the functionality.

All Vaadin applications have an associated theme. Themes are essentially a collection of CSS and images that define the look and feel of the Vaadin’s user interface components.

The following Vaadin themes are included in Liferay by default:

Theme Description
base Base theme for creating your own customized theme. Handles most of the cross-browser issues.
liferay A Liferay 6 look-a-like theme. Use this to create applications that match the Liferay 6 default styles.
reindeer Reindeer is default look and feel of Vaadin. It provides minimalistic, but stylish look for business applications.
runo More colorful and rounded theme for web applications.

Structure of a Vaadin Theme

Vaadin themes are located in the themes folder of the portal. They are a collection of CSS and images that give the Vaadin components their look and feel.

The theme folder must contain the styles.css stylesheet, and custom layouts must be placed in the layouts sub-folder. Other contents may be named freely.

A typical Vaadin theme follows the structure under the theme folder:

Theme Description
styles.css The CSS for the whole theme.
layouts/ Directory for CustomLayout definition files.
<component>/ CSS definitions for a single UI component. Only used to split the CSS for easier maintenance. These are compiled into styles.css is as a single CSS file.
<component>/img/ Static image resources for the component.

Typically, you start to develop your theme by inheriting some existing -theme:


@import url(../liferay/styles.css);

After that, you can apply the CSS rules that override the original theme without completely rewriting a theme.

To activate the theme in your portlet, add the following to the init method of your application:


public void init() {
setTheme(“mytheme”);
// ...
}	

CSS Classnames in Vaadin

To maximize the use of theme inheritance and to help customize components, the CSS class selectors in Vaadin are defined the following scheme .v-<component|item>. All style names are lowercase.

As an example, the following CSS rules change the color of all captions and adds borders to all TextFields:


.v-caption {color: red;}
	
	.v-textfield {border: 1px solid red;}

The most relevant CSS class names are:

Class Name Description
.v-app The top-level DIV container for the whole application.
.v-window Container for the application window.
.v-<component> Container for a specific component type. Note that captions are managed outside the component, by the containing Layout.

To avoid style leakage outside the Vaadin application, it is recommended that you use the most specific CSS selector when applying your own styles and limit them by using container, such as:


.v-app .v-caption {color: green; }

VAADIN PORTAL-WIDE SETTINGS

The core Vaadin Framework consists of a single jar file that includes the framework itself along with the core components. This jar along with the CSS themes and custom widgets are installed to the portal itself, and they are shared by all Vaadin-based portlets. This means that only a single version of Vaadin is supported in a portal installation.

A Liferay 6 installation includes the following Vaadin-related files and directories:

Class Name Description
vaadin.jar
(Java jar-file)
Vaadin Framework, portlet integration and core UI components.
widgetsets/<name>/
(directory)
Client-side widgets of Vaadin. JavaScript compiled with Google Web Toolkit (GWT). Must be publicly accessible.
theme/<theme name>/
(directory)
Collection of CSS and static images that define the look of the Vaadin components. Must be publicly accessible.
<add-on>-<version>.jar
(Java jar-file)
An extension to Vaadin - new UI component, data-binding or a theme. Standard jar file.
gwt-user.jar, gwt-dev.jar
(Java jar-files)
Google Web Toolkit libraries needed to re-compile the clientside JavaScript if new components are imported.

Depending on the application server used, these files are installed in different locations.

Tomcat 6.x Location
Global vaadin.jar ${TOMCAT_DIR}/webapps/ROOT/WEB-INF/lib
Vaadin Add-ons ${TOMCAT_DIR}/webapps/ROOT/WEB-INF/lib
Vaadin CSS Themes ${TOMCAT_DIR}/webapps/ROOT/html/VAADIN/themes
Vaadin Client-side Widgetset ${TOMCAT_DIR}/webapps/ROOT/html/VAADIN/widgetset
GWT jar-files (only needed for compiling widgetset) ${TOMCAT_DIR}/webapps/ROOT/WEB-INF/vaadin/gwt
GlassFish 3.x Location
Global vaadin.jar ${GLASSFISH_DOMAIN_DIR}/applications/j2ee-modules/ Liferay-portal/WEB-INF/lib
Vaadin Add-ons ${GLASSFISH_DOMAIN_DIR}/applications/j2ee-modules/ Liferay-portal/WEB-INF/lib
Vaadin CSS Themes ${GLASSFISH_DOMAIN_DIR}/applications/j2ee-modules/ Liferay-portal/VAADIN/themes
Vaadin Client-side Widgetset ${GLASSFISH_DOMAIN_DIR}/applications/j2ee-modules/ Liferay-portal/VAADIN/widgetset
GWT jar-files (only needed for compiling widgetset) ${GLASSFISH_DOMAIN_DIR}/applications/j2ee-modules/ Liferay-portal/WEB-INF/vaadin/gwt/
JBoss 5.x Location
Global vaadin.jar ${JBOSS_INSTANCE_DIR}/deploy/ROOT.war/WEB-INF/lib
Vaadin Add-ons ${JBOSS_INSTANCE_DIR}/deploy/ROOT.war/WEB-INF/lib
Vaadin CSS Themes ${JBOSS_INSTANCE_DIR}/deploy/ROOT.war/VAADIN/themes
Vaadin Client-side Widgetset ${JBOSS_INSTANCE_DIR}/deploy/ROOT.war/VAADIN/widgetsets/
GWT jar-files (only needed for compiling widgetset) ${JBOSS_INSTANCE_DIR}/deploy/ROOT.war/WEB-INF/vaadin/gwt

Liferay Portlet Setup

To use Vaadin in a Liferay portlet, the portlet has to be configured to use Vaadin and optional add-on libraries by creating and/or editing various configuration files.

Anatomy of a Portlet Project

Portlets (Vaadin and non-Vaadin) are built as Liferay plugins, which can be compiled and hot-deployed into a Liferay environment. In their source (uncompiled) form, there are several file and directory structures used to manage the project.

Folder Description
WebContent/ (or docroot/) This folder is the “root” of your Vaadin portlet application
WEB-INF Standard WEB-INF folder for web applications. Also contains Liferay-specific descriptors such as portlet.xml, liferay-portlet. xml, and others.
WEB-INF/src Java source code for the Vaadin Portlet
build.xml ANT build script controlling building and deploying
liferay-display.xml Describes the category under which the portlet should appear in the Liferay UI
liferay-plugin-package. properties Describes properties used by Liferay’s hot deploy mechanism, most notably which Vaadin dependencies to include when compiling the plugin.
liferay-portlet.xm Describes Liferay-specific portlet enhancements (akin to portlet.xml for generic portlets). There are many settings here to customize your portlet.
portlet.xml Standard JSR-168 or JSR-286 portlet descriptor, including settings for performing non-Vaadin portlet IPC.
web.xml Standard Web Application descriptor. You should not need to edit this for use with Vaadin.

Liferay Plugin Package Properties

The liferay-plugin-package.properties file defines a number of settings for the portlet, most importantly the Vaadin Framework and Vaadin Add-on jar-files to be used.

The following example of a dependency definition:


name=MyVaadinPortletName
module-group-id=vaadin
module-incremental-version=1
tags=
short-description=
change-log=
page-url=http://www.liferay.com
author=Your Company, Inc.
licenses=LGPL
portal-dependency-jars=\
	vaadin.jar,\
	paperstack-0.8.1.jar,\
	console-1.0.0.jar

The Vaadin-related portlet dependencies are highlighted. The vaadin.jar contains the framework itself. The other dependencies, paperstack-0.8.1.jar and console-1.0.0.jar, are Vaadin add-ons used by the portlet.

Refer to the application server setup to see where these jar dependencies should be installed to work at compiletime and runtime.

Portlet Descriptor

To wire the portlet to your Vaadin application class, configure portlet mapping in the portlet.xml:


<portlet>
	<portlet-name>MyVaadinPortlet</portlet-name>
	<display-name>MyVaadinPortlet</display-name>
	<portlet-class>
	com.vaadin.terminal.gwt.server.ApplicationPortlet2
	</portlet-class>
	<init-param>
		<name>application</name>
		<value>org.vaadin.sample.MyApplication</value>
	</init-param>
</portlet>

Vaadin portlets always use the same portlet class, com.vaadin.terminal.gwt.server.ApplicationPortlet2, and the actual application is defined as an init-param.

Liferay Portlet Descriptor

Liferay also requires a liferay-portlet.xml descriptor file that defines Liferay-specific parameters. In particular, Vaadin portlets must be defined as “instanceable” but not as “ajaxable”:


<liferay-portlet-app>
	<portlet>
	  <!-- Matches definition in portlet.xml. -->
	  <!-- Note: Must not be the same as servlet name. -->
	  <portlet-name>Portlet Example portlet</portlet-name>
	  
	  <instanceable>true</instanceable>
	  <ajaxable>false</ajaxable>
	</portlet>
</liferay-portlet-app>

This is because Vaadin portlets handle the Ajax requests internally without Liferay’s Ajax mechanisms.

Liferay Portlet Display Descriptor

The liferay-display.xml file defines the portlet category under which portlets are located in the Add Application window in Liferay. Without this definition, portlets will be organized under the “Undefined” category.

The following puts the application in a new category called “Vaadin”:


<display>
		<category name=”Vaadin”>
				<portlet id=”MyVaadinExamplePortlet” />
		</category>
	</display>

For more information on these and other optional descriptors, see the Chapter 11.8 of the “Book of Vaadin” at http://vaadin.com/book and refer to the Liferay Developer Guide at http://liferay.com/ documentation

INTER-PORTLET COMMUNICATION (IPC)

Liferay offers different IPC mechanisms to allow portlets communicate with each other. The following table summarizes the different IPC methods in Liferay:

Method Description
JSR 286 Portlet Events Standard portlet communication mechanism. Requires page reload.
JavaScript Traditional client/server communication, using client-side JavaScript, calling other portlets running in the same page using Liferay's client-side JavaScript API: Liferay. fire(eventName, data) Liferay.on(eventName, function, [scope])
Vaadin Addon for Liferay IPC Mechanism for sending and receiving events between Vaadin and non-Vaadin portlets.
Custom Event Bus Direct client-side communication between portlets (e.g. using OpenAjax Hub). No page refresh necessary, and no server communication is required.
Ajax Push (Reverse Ajax) Typically used for server->client notifications (for example, in-browser chat). Long-held connections are used to push data from server to client, as needed, instead of separate communications for each message.

IPC in Vaadin Portlets

Vaadin portlets are based on Ajax communication that is most useful if the user never changes the page in the browser. In this scenario, the application talks to the server frequently and only small user interface updates are sent to the browser. This makes the best user experience.

When communicating with other portlets in a portal, the different scenarios may require different approaches to optimize the user experience.

A Vaadin portlet sending an event to a non-Vaadin portlet.

Depending on the other portlet, this typically requires a page reload. Below is an example of sending a “date” event to another portlet.

Configure an event definition in the portlet.xml:


<event-definition>
	<qname xmlns:vaadin=”http://vaadin.com/portletevents”>
vaadin:date</qname>
	<value-type>java.util.Date</value-type>
</event-definition>

Send a portlet event from a Vaadin application:


((PortletApplicationContext2) getApplication().getContext())
.sendPortletEvent(getMainWindow(),
			new QName(“http://vaadin.com/portlet-events”,
“date”),
(Date)dateField.getValue());

Receive an event in a non-Vaadin portlet:


Receiving an event in a non-Vaadin portlet:
public class MyPortlet extends GenericPortlet

	@Override
	public void processEvent(EventRequest request,
						EventResponse response)
			throws PortletException, IOException {
		Event e = request.getEvent();
		if (“date”.equals(e.getName())) {
			Date date = (Date) e.getValue();
	       // ...
		}
	}
}

This style of IPC relies on server-side processing of the events and, therefore, requires a page reload to see the effects of the event in the non-Vaadin portlet.

Communicating with a Vaadin-based portlet using Ajax. In this case, the full page request is not needed.

Note: This requires the Liferay IPC add-on to be installed in the application. For more details and instructions, go to: http://vaadin.com/addon/vaadin-ipc-for-liferay. Receive an event in a Vaadin application/portlet:

Receive an event in a Vaadin application/portlet:


LiferayIPC ipc = new LiferayIPC();
ipc.addListener(“uniqueEventId”, new LiferayIPCEventListener() {
	public void eventReceived(LiferayIPCEvent event) {
		// Process event here
	}
});

Send an event from another portlet using JavaScript:


LiferayIPC ipc = new LiferayIPC(); ipc.sendEvent(“uniqueEventId”,
“payloadData”);

Receive an event from a Vaadin application/portlet using JavaScript:


<script>
Liferay.on(“uniqueEventId”,
	function(event) {
		alert(event);
	}
);
</script>

Send an event from another portlet using JavaScript:


<script>
Liferay.fire(“uniqueEventId”, “someData”);
</script>

This method is not suitable for sending a large amount of data, rather, it’s for notifying the portlet that something has updated. The actual data should be shared using the database, files, or some external storage.

Note: When sending events to non-Vaadin portlets that are ajaxenabled (ajaxable set to true and render-weight < 1), be aware that if a portlet takes some time to load, it might not receive the event in the case that the event is sent before the portlet is fully initialized.

Further Information

For up-to-date and in-depth information, refer to the Liferay official documentation for Liferay at www.liferay.com/ and Vaadin documentation at vaadin.com/book/.

About The Authors

Sami Ekblad

Sami Ekblad is one of the original authors of the Vaadin framework. Working in web application development since 1998, he now works as Partner Manager at Vaadin Ltd to help professional web developers to get most out of the Vaadin framework and tools. He holds B.Sc. degree in Computer Science from the University of Turku.

James Falkner

James Falkner is an open-source evangelist, community manager, and software developer working at Liferay, producers of the world’s leading open source enterprise portal. In addition to Liferay, James has been active in a number of other open source products and projects, including the GlassFish Enterprise portfolio, Community/Social Equity, OpenSolaris, OASIS standards, and more. contributor and speaker at industry events such as JavaOne, JAX, and others.

Recommended Book

Liferay in Action

Liferay in Action is a comprehensive and authoritative guide to building portals on the Liferay 6 platform. Fully supported and authorized by Liferay, this book guides you smoothly from your first exposure to Liferay through the crucial day-to-day tasks of building and maintaining an enterprise portal that works well within your existing IT infrastructure. The book starts with the basics: setting up a development environment and creating a working portal. Then, you’ll learn to build on that foundation with social features, tagging, ratings, and more. As the book progresses, you’ll explore the Portlet 2.0 API, and learn how to create your own portlet applications.

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,853 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 - Java Contracts: By Google

Contracted code in Java can reveal failures much closer to their fault, shaving hours off your debugging sessions.  It's good news then that Google has just made it easier to implement contracts in Java with the launch of their new open source tool:...

1 replies - 23824 views - 02/06/11 by Mitchell Pronsc... in Daily Dose

Daily Dose - New OpenJDK Bylaws Revealed

Mark Reinhold just posted the new community bylaws draft for the Open JDK.  Mark Wielaard, a Red Hat engineer, posted his feedback in the comments and Simon Phipps has commentary on his blog (On a scale of -10 to +10, he gave the current draft a -3).  You...

5 replies - 24623 views - 02/04/11 by Mitchell Pronsc... in Daily Dose

Daily Dose - Seam 3 Goes Beta

JBoss' grand, all-encompassing Java development framework is nearly finished.  This weekend, the 3.0 version reached Beta 1 status.  It is the first release to have all of the Seam modules (Drools, Errai, Servlet, JBoss ESB, etc.) bundled into a single...

0 replies - 27548 views - 01/31/11 by Mitchell Pronsc... in Daily Dose

Daily Dose - Spring Data Graph - Bringing NoSQL, MapReduce, and Cloud Data to Spring Apps

A new project from Spring has been announced recently with its first milestone release.  Spring Data Graph 1.0 will focus on making it simpler for developers to build Spring-based apps that hook into things like MapReduce, NoSQL data stores, and cloud data...

3 replies - 13443 views - 01/24/11 by Mitchell Pronsc... in Daily Dose

Liferay Essentials

A Definitive Guide for Enterprise Portal Development

By James Falkner

11,763 Downloads · Refcard 126 of 151 (see them all)

Download
FREE PDF


The Essential Liferay Cheat Sheet

Liferay, a free and open source enterprise portal written in Java. More than just a portal, Liferay in its eleventh year of development. It is a platform for creating effective business applications and solutions while portals (and portlets) remain the only reasonable way to offer multiple applications in a single UI. It offers a robust feature set, impressive scalability, time-saving development tools, support for over 30 languages, and a flexible architecture that is open source developed and enterprise refined. Contents for this card include web content management, workflow, administration, hot tips and more.
HTML Preview
Liferay Essentials A Definitive Guide for Enterprise Portal Development

Liferay Essentials: A Definitive Guide for Enterprise Portal Development

By James Falkner

INTRODUCTION

Liferay Portal is a free and open-source enterprise portal written in Java and distributed under the GNU LGPL. Now in its eleventh year of development, the award-winning product is one of the most widely deployed portal technologies on the market, with an estimated 250,000 deployments worldwide. More than a portal, Liferay is a platform for creating effective business applications and solutions. It offers a robust feature set, impressive scalability, time-saving development tools, support for over 30 languages, and a flexible, scalable architecture that is open-source developed and enterprise refined.

About this Refcard

This Refcard will help both novices and professionals quickly navigate some of Liferay’s most popular features and hidden gems. It will cover topics such as installation, configuration, administration, and development features.

Getting Set up

Liferay Portal Community Edition is freely downloadable from http://liferay.com. Click the Downloads link at the top of the page and you will be presented with multiple download options:

Bundles are archives that combine Liferay Portal with popular application servers such as Tomcat, GlassFish, and others.

Standalone (WAR) distributables contain Liferay Portal alone and are suitable for installation into an existing application server environment.

All bundles and WAR distributables are cross-platform and should run on any modern flavor of Windows, Linux, Mac OS X, or other Unix-based operating systems.

Bundle Directory Structure

liferay-portal-<version> This top-level folder is known as the Liferay Home directory.

Data: This folder is used to store the embedded HSQL database that the bundles use, as well as the configuration and data for the Jackrabbit JSR-170 content repository and the Lucene search index.

LiferayPortal

Deploy: Plugins that you wish to deploy to Liferay can be copied into this folder. It is also used by Liferay’s graphical plugin installer utility, which is available from the Control Panel.

License: This folder contains both Liferay’s license and a file that describes the licenses for many of the other open-source projects that are used internally by Liferay.

[Application Server]: There will also be an application server folder that is different depending on which bundle you have downloaded. This folder contains the application server in which Liferay has been installed.

Starting Liferay

In most cases, installing a bundle is as easy as uncompressing the archive and then starting the application server.

For example, Tomcat is started with:


$ ${LIFERAY_HOME}/tomcat-6.0.26/bin/startup.sh
$ tail –f ${LIFERAY_HOME}/tomcat-6.0.26/logs/catalina.out

Other bundles are started in a similar fashion.

Once started, your Web browser should automatically be launched and directed to http://localhost:8080, which should display the default Liferay website, as shown here.

Liferay Basics

Liferay is a portal server. This means that it is designed to be a single environment where all of the required applications (represented by individual portlets) can run, and these applications are integrated together in a consistent and systematic way.

Portal Architecture

In the illustration below, each arrow may be read using the words “can be a member of.” It is important to note that the diagram illustrates only users and their collections. Permissions ` do not flow through all of these collections; permissions can be assigned to roles only.

LiferayPortal

The following concepts are used throughout Liferay:

  • Portals are accessed by Users.
  • Users can be collected into User Groups.
  • Users can belong to Organizations and join/leave Communities.
  • Roles are collections of permissions on portal objects that can be assigned to Users.
  • Organizations can be grouped into hierarchies, such as Home Office  Regional Office  Satellite Office. Communities are not hierarchical.
  • Users, Groups, and Organizations can belong to Communities that have a common interest.
  • Within Organizations and Communities, users can belong to Teams, which are groupings of users for specific functions within a community or organization.
  • Users, Organizations and Communities have two separate collections of Pages called Public and Private Pages. Each page can have as many applications (portlets) as desired. The page administrator can lay out these applications into zones defined by a default or customized layout template.

WEB CONTENT MANAGEMENT

Liferay’s Web Content Management (WCM) is a system which allows non-technical users to publish content to the Web without having advanced knowledge of Web technology or programming of any sort. Liferay Content Management System (CMS) empowers you to publish your content with a simple point-andclick interface, and it helps you to keep your site fresh.

You can use WCM to author both structured and unstructured content. Unstructured content is authored using an HTML-based WYSIWYG editor. Structured content is authored and displayed by combining Web Content Structures, Web Content Templates, and Web Contents. Structures and Templates are defined individually using a text editor or through the Liferay WCM UI.

Accessing Structure Elements

The following table shows how to access structure data from your Web Content Template code (when using Velocity templates; other template languages such as FreeMarker, XSL, or CSS have similar constructs). The variable name defined in the structure are denoted in bold and will be different depending on the name assigned in the structure.

Element Type Velocity Template Accessors
Text Field $tf.name, $tf.data, $tf.type
Text Box $textbox.data
Text Area (HTML) $textarea.data
Checkbox $checkbox.data
Selectbox $selectbox.data
Multi-Selection List #foreach($selection in $mylist.options)
$selection
#end
Image Gallery <img src=”/image/image_gallery?img_id=$img.getData()”/>
Link to Page $linkToPage.url
Repeatable $el.siblings
Hierarchy #foreach($child in $el.children)
$child.data
#end
Reserved Variables $reserved-article-[id,version,title,create-date,modifieddate,display-date,author-id,author-name,author-emailaddress,author-comments,author-organization,authorlocation,author-job-title].data

Template and Theme Variables

The following table lists the most common built-in variables accessible from Velocity Template code (when using Velocity templates; other template languages such as FreeMarker, CSS, or XSL have similar constructs). For example, $layout.getChildren(). Items marked with an asterisk (*) are only available from Liferay Theme files.

Variable Name Description
request HTTPServletRequest object
company The current company object. This represents the portal instance on which the user is currently navigating.
companyId The current company ID.
groupId ID of the group in which this web content is published.
locale The current user's locale, as defined by Java.
randomNamespace A randomized string. It is very useful for creating IDs that are guaranteed to be unique.
browserSniffer Dynamic browser capabilities. e.g.$browserSniffer.isMobile()
portal Current portal instance
portletURLFactory Creates portlet URLs (action URLs, etc)
stringUtil Useful string utilities
portletConfig* Standard PortletConfig object describing information from the portal.xml file.
renderRequest* Standard Portlet RenderRequest object
renderResponse* Standard Portlet RenderResponse object
themeDisplay* Contains many useful items, such as the logged in user, the layout,logo information, paths, and much more.
user* The User object representing the current user.
layoutSet* The set of pages to which the user has currently navigated. Generally, communities and organizations have two: a public set and a private set.
scopeGroupId* groupId that is used to identify the scope where the data of the current portlet is stored and retrieved. The scope can represent a community, organization, user, the global scope, or a scope tied to a specific page.
timeZone* The current user's time zone, as defined by Java.
viewMode e.g. “print” when clicked print icon
fullTemplatesPath* Path to all templates used.
pageTitle* Title of the page
serviceLocator Access to other Liferay services. Note by default this variable is disabled, must be enabled via portal-ext.properties
prefsPropsUtil Access to portal settings that were set from the Control Panel or through the portal.properties configuration file.
permissionChecker An object which can determine given a particular resource whether or not the current user has a particular permission for that resource.
[css|images|javascrip
t|templates]_folder*
Full path to various theme files

Hot Tip

A web Content Template that is set as Cacheable will return a cached result when accessing the variables (potentially returning stale or sensitive data). To ensure you get an uncached result, make sure that you uncheck the Cacheable option for your Web Content Template.

WORKFLOW

A Liferay Workflow is a predetermined sequence of connected steps. In Liferay, workflow is designed to manage the creation, modification, and publication of all supported web content types (including Web Content, Blogs, Wikis, Message Boards, Documents, and other user-generated content). Liferay ships with a default workflow engine called Kaleo. It can generate and reference roles scoped for Organizations, Communities, and for the entire Portal. This engine is deeply integrated with Liferay, but can be replaced with an external engine, such as jBPM.

Kaleo Workflow Definitions

Liferay comes with a default Kaleo workflow definition called “Single Approver” that means that a single approval is needed before content is published. You can create custom workflow definitions by using the APIs and workflow definition format provided. An example skeleton of a simple workflow is shown below:


<workflow-definition>
	<name>MyName</name>
	<version>1</version>
	<state>
	</state>
	<state>
	</state>
	<task>
	</task>
	<task>
	</task>
</workflow-definition>

Assets, States, Transitions, and Tasks

The key parts of the workflow definition are the asset, states, transitions, and tasks. The asset is whatever piece of content is being reviewed and approved in the workflow. States represent stages of the workflow, such as “created”, “rejected”, or “approved”. Transitions occur between states, and indicate what the next state should be. Tasks are steps in the workflow that require user action.

Example State

<state>
  <name>MyState</name>
  <initial>true</initial>
  <actions>
   <action>
	 <name>SomeAction</name>
	 <execution-type>onEntry</execution-type>
	 <script>
	    <![CDATA[
     // some javascript code here
        ]]>
	</script>
	<script-language>javascript</script-language>
	<priority>7</priority>
   </action>
  </actions>
  <transitions>
    <transition>
	 <name>Task1</name>
	 <target>task1</target>
	 <default>true</default>
    </transition>
  </transitions>
</state>

Notable Elements Options
<actions> Defines actions to be taken upon entering state
<transitions> Defines possible transitions out of this state
<script-language> groovy, javascript, python, ruby
<priority> Integer, controls execution order of actions
<execution-type> onEntry, onAssignment, onExit
<template-language> text, velocity, freemarker
<notification-type> email, im, private-message
Example Task


  <task>
	<name>MyTask</name>
	<due-date-duration>12</due-date-duration>
	<due-date-scale>day</due-date-scale>
	<actions>
	  <notification>
		<name>A Notification</name>
		<execution-type>onAssignment</execution-type>
		<template>You have a new task</template>
		<template-language>text</template-language>
		<notification-type>email</notification-type>
	  </notification>
	</actions>
	<assignments>
	  <roles>
		<role>
			<role-type>community</role-type>
	    	<name>Community Administrator</name>
	    </role>
 	  </roles>
	</assignments>
	<transitions>
	  <transition>
		<name>Transition1</name>
		<target>state1</target>
		<default>true</default>
      </transition>
	   <transition>
		  <name>Transition2</name>
		  <target>state2</target>
		  <default>false</default>
	   </transition>
      </transitions>
 </task>

Notable Elements Options
<due-date-duration> Defines when the task is due
<ue-date-scale> second, minute, hour, day, week, month, year
<roles> Users who have this role can be assigned this task
<role-type> regular, community, organization

LIFERAY ADMINISTRATION

Portal Properties

Liferay uses the concept of overriding the defaults in a separate file, rather than going in and customizing the default configuration file. The default configuration file is called portal. properties, and it resides inside of the portal-impl.jar file. This .jar file is located in Liferay Portal’s WEB-INF/lib folder. If you have a copy of the Liferay source code, this file can be found in portal-impl/src. The file which is used to override the configuration is portal-ext.properties. This file can be created in your Liferay Home folder or anywhere in the application server’s classpath.

Database Setup

Out of the box, Liferay bundles are configured to use HSQLDB, which should only be used for development or demo purposes. You cannot use this database in production.

For production use, Liferay supports the following databases: MySQL, Microsoft SQL Server, Oracle Database, IBM DB2, PostgresSQL, and Sybase. Liferay can also connect to Apache Derby, Firebird, Informix, Ingres, or SAP DB. To use these databases, the database and user with appropriate access must be created, and the appropriate JDBC driver must be available in your app server. Consult your database documentation for details on syntax and how to create databases and users.

To use a particular database, you must set the following four properties in your portal-ext.properties.

MySQL Example:

1. jdbc.default.driverClassName=com.mysql.jdbc.Driver
2. jdbc.default.url=jdbc:mysql://localhost/lportal?
			useUnicode=true&characterEncoding=UTF-
			8&useFastDateParsing=false
3. jdbc.default.username=
4. jdbc.default.password=

Oracle Example:

jdbc.default.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.default.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.default.username=lportal
jdbc.default.password=lportal

It’s also possible to delegate this configuration to the application server through a DataSource by using the following property:


jdbc.default.jndi.name=NameOfDataSource

App Server Configuration

Liferay is supported on the following app servers or servlet containers: Geronimo, GlassFish, JBoss, Jetty, JOnAS, Oracle, Resin, Tomcat, WebLogic, and WebSphere. Consult your app server documentation for details on configuration. The following table lists common files that are involved in configuring your app server.

Tomcat 6.x Location
Global Libraries ${TOMCAT_DIR}/lib/ext
Portal Libraries ${TOMCAT_DIR}/webapps/ROOT/WEB-INF/lib
Primary Configuration ${TOMCAT_DIR}/conf/server.xml
Primary Log Files ${TOMCAT_DIR}/logs/catalina.out
GlassFish 3.x Location
Default Domain Directory ${GLASSFISH_DIR}/domains/domain1
Global Libraries ${GLASSFISH_DOMAIN_DIR}/lib
Portal Libraries ${GLASSFISH_DOMAIN_DIR}/applications/j2ee-modules/Liferay-portal/WEB-INF/lib
Primary Configuration ${GLASSFISH_DOMAIN_DIR}/config/domain.xml
Primary Log Files ${GLASSFISH_DOMAIN_DIR}/logs/server.log
JBoss 5.x Location
Default Instance Directory ${JBOSS_DIR}/server/default
Global Libraries ${JBOSS_INSTANCE_DIR}/lib
Portal Libraries ${JBOSS_INSTANCE_DIR}/deploy/ROOT.war/WEB-INF/lib
Primary Configuration ${JBOSS_INSTANCE_DIR}/conf/jboss-service.xml
Primary Log Files ${JBOSS_INSTANCE_DIR}/log/server.log ${JBOSS_INSTANCE_DIR}/log/boot.log

Troubleshooting and Debugging

The following items should be checked when troubleshooting a problem.

Item Notes
Log Files Log files for several app servers are listed above. These should be checked for warnings, errors, Java stack traces, etc.
Log Settings Liferay uses the Apache Log4j library to perform all of its logging operations. See below on how to configure log settings.
JMX Liferay provides out-of-the-box JMX MBeans, which allow introspection into the runtime, for example to identify and isolate problematic behavior such as poor cache performance or slow portlet rendering.
Debug To attach a Java debugger to Liferay, you must start the JVM with special properties. Some servers have done this for you. For example, to start Tomcat under a debugger, run “bin/catalina.sh jpda start”
Other servers may need the JVM properties added manually. A typical set of properties is:
-Xdebug
-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005

Logging Configuration

Liferay uses Log4j for its logging operations. When debugging an issue, it is useful to be able to increase verbosity of certain areas of Liferay to diagnose an issue. There are two ways to do this:

Interactively

Interactively changing the log levels will only persist until the next system restart, when the log level settings will revert to their previous values. This is done through the Control Panel-> Server Administration -> Log Levels user interface.

Config File

To make a more permanent change, copy Liferay’s default METAINF/portal-log4j.xml file from the portal-impl.jar, rename to portal-log4j-ext.xml, make any edits, and place the file somewhere along the servers classpath. For example, if you were using Tomcat, one could create ${TOMCAT_DIR}/lib/META-INF/portal-log4j-ext.xml.

For example, to enable debug logging for Hibernate, add this to your portal-log4j-ext.xml file:


<category name=”org.hibernate”>
 	<priority value=”DEBUG” />
</category>

Hot Tip

JBoss includes its own Log4j configuration that may override Liferay’s configuration. The JBoss Log4j configuration file can be found in $JBOSS/server/default/ conf/log4j.xml. Read the JBoss documentation for details.

Portal Properties

Listed below are several properties and descriptions that can be used to configure Liferay. These settings belong in your portal-ext.properties file.

Property Name Description and Examples
liferay.home
Default: Depends on App Server
Specifies the root of Liferay’s working directory /configuration. Example: /var/lr-home
portal.ctx
Default: /
Specifies the path of the portal servlet context. If you change this, you must also change the setting in web.xml Example: /mysite
jdbc.default.jndi.name
Default: Not Set
Set the JNDI name to lookup the JDBC data source. If none is set, then Liferay will attempt to create the JDBC data source based on the properties prefixed with jdbc. default. Example: jdbc/LiferayPool
jdbc.default.driverClassName
jdbc.default.url
jdbc.default.username
jdbc.default.password
Defaults: settings for HSQL
Database configuration options for creating the Liferay Database connection pool
company.default.web.id
Default: liferay.com
Default Web ID. Omni administrators must belong to this company. Example: mycompany.com

DEVELOPING FOR LIFERAY

You can develop many things both for and in Liferay: portlets, hooks, themes, layout templates, services, and more.

Plugins SDK

The Plugins SDK is both a project generator and a location where your projects are stored. Download the Plugins SDK from liferay.com/downloads/liferay-portal/additional-files.

Do not forget to create a build.username.properties file (where username is your OS username). Set the app.server.dir property to point at an extracted Liferay/App Server bundle. For example, app.server.dir=${user.home}/lr-6.0.5.

Building projects in the Plugins SDK requires that you have Ant 1.7.0 or higher installed on your machine. Download the latest version of Ant from http://ant.apache.org/.

Creating and Deploying New “Hello World” Plugins

Use the “create” script for creating new portlet, theme, hook, layout, or Web plugins:


$ cd portlets; ./create.sh hello-world “Hello World Portlet”
$ ant deploy

Other ANT targets include: Clean: removes build artifacts. War: creates distributable .war file. Compile: compiles source code. build-service: invokes Liferay’s Service Builder to create and build service source code.

Anatomy of a Portlet Project

Several directories and files are created when you use the create.sh tool.

Folder Description
docroot This folder is the “root” of your application.
WEB-INF Standard WEB-INF folder for Web applications. Also contains Liferayspecific descriptors.
WEB-INF/src Portlet source code.
build.xml ANT build script controlling building and deploying your plugin.
liferay-display.xml Describes what category the portlet should appear under in the Liferay UI.
liferay-pluginpackage.
properties
Describes properties used by Liferay’s hot-deploy mechanism.
liferay-portlet.xml Describes Liferay-specific portlet enhancements (akin to portlet.xml for generic portlets). There are many settings here to customize your portlet.
portlet.xml Standard JSR-168 or JSR-286 portlet descriptor
web.xml Standard Web Application descriptor

Liferay Hooks

Hooks are the best way to extend or modify Liferay’s behavior. They allow you to override parts of core Liferay with custom implementations. You specify what you wish to hook into in your liferay-hook.xml file. Within this file, you can customize:

Portal Properties

<hook>
<portal-properties>my.custom.portal.propertie</portal-properties>
</hook>

Within custom properties files, add startup action:


application.startup.events=org.mypkg.MyStartupEventClass

Add Model Listener for Blogs:


value.object.listener.com.liferay.portlet.blogs.model.BlogsEntry=org.mypkg.
BlogEntryAction

Language Properties

<hook>
<language-properties>content/Language_fr.properties</language-properties>
</hook>

JSP File Override

Allows overriding of any JSP from the core of Liferay by using the same paths as Liferay uses within the specified directory. Use with care:


<hook>
<custom-jsp-dir>/META-INF/custom_jsp</custom-jsp-dir>
</hook>

Then create custom JSPs:


/META-INF/custom_jsps/html/portlet/blogs/view.jsp
/META-INF/custom_jsps/html/portlet/calendar/week.jsp

Services

By wrapping services it’s possible to extend any core Liferay service method to perform additional operations or even to replace the default operations.


<hook>
  <service>
	<service-type>
	  com.liferay.portal.service.UserLocalService
	</service-type>
	<service-impl>
	  com.liferay.test.hook.service.impl.MyUserLocalServiceImpl
	</service-impl>
  </service>
</hook>

Liferay Themes

Themes are plugins, and are therefore hot-deployable just like portlet plugins. You can use the Plugins to build your themes automatically so that they can be deployed to any Liferay instance. The Plugins SDK packages a theme into a .war file just like a portlet, and this .war file can then be hot-deployed to Liferay.

Anatomy of a Theme
Path within Theme Description
/css/base.css, custom.css, … Defines many aspects of Liferay’s UI. To override, create your own _diffs/css/custom.css within your theme source code
/images/ Static image resources references from CSS, JS, VM, etc.
/javascript/main.js Defines stub functions that fire at certain points of page loading when using theme. Override using custom main.js
/templates/ Various Velocity Macro Templates that are executed during page rendering
init-custom.vm Allows you to add your own custom Velocity variables
init.vm Sets many Velocity variables that correspond to Liferay Java objects. See the section on Web Content for common variables available from your custom theme code.
navigation.vm Implements the page navigation within the theme
portal_normal.vm The overall template for all pages the theme implements. This file includes the other files.
portal_pop_up.vm The overall template for any portlets which implement popup windows.
portlet.vm The template for portlet windows within the theme.

Service Builder

Service Builder is a source code generation tool built by Liferay to automate the creation of interfaces and classes for database persistence, local and remote services. This is useful when developing data-driven applications that make frequent calls to the underlying database.

service builder

Hot Tip

A “service” in Liferay is simply a class or set of classes designed to handle retrieving and storing data classes. A local service is used by code running in the local instance of Liferay, while a remote service can be accessed from anywhere over the internet or your local network. Remote services support SOAP, JSON, and Java RMI.
Sample Service

Services are defined by creating a service.xml file. Once defined, source code can be generated for the persistence and data access/transfer layers of your Data-driven app. An example:


<service-builder package-path=”com.sample.portlet.library”>
  <namespace>Library</namespace>
  <entity name=”Book” local-service=”true” remote-service=”true”>
	<!-- PK fields -->
	<column name=”bookId” type=”long” primary=”true” />
	<!-- Group instance -->
	<column name=”groupId” type=”long” />
	<!-- Audit fields -->
	<column name=”companyId” type=”long” />
	<column name=”userId” type=”long” />
	<column name=”userName” type=”String” />
	<column name=”createDate” type=”Date” />
	<column name=”modifiedDate” type=”Date” />
	<!-- Other fields -->
	<column name=”title” type=”String” />
  </entity>
</service-builder>

Generating the Code

$ ant build-service

JSP Variable Reference

To get access to Liferay contextual objects when writing a JSP:


<liferay-theme:defineObjects />

Then, the following variables are available to your JSP:

Variable Name Description
themeDisplay A runtime object which contains many useful items, such as the loggedin user, the layout, logo information, paths, and much more.
company The current company object. This represents the portal instance on which the user is currently navigating.
account The user's account object. This object maps to the Account table in the Liferay database.
user The User object representing the current user.
realUser When an administrator is impersonating a user, this variable tracks the administrator's user object.
contact The user's Contact object. This object maps to the Contacts table in the Liferay database.
layout The set of pages to which the user has currently navigated. Generally, communities and organizations have two: a public set and a private set.
plid A Portal Layout ID. This is a unique identifier for any page that exists in the portal, across all portal instances.
layoutTypePortlet This object can be used to programmatically add or remove portlets from a page.
scopeGroupId A unique scope identifier for custom scopes, such as the page scope that was introduced in Liferay Portal 5.2.
permissionChecker An object that can determine, given a particular resource, whether or not the current user has a particular permission for that resource.
locale The current user's locale, as defined by Java.
timeZone The current user's time zone, as defined by Java.
theme An object representing the current theme that is being rendered by the portal.
colorScheme An object representing the current color scheme in the theme that is being rendered by the portal.
portletDisplay An object that gives the programmer access to many attributes of the current portlet, including the portlet name, the portlet mode, the ID of the column on the layout in which it resides, and more

Social Tools and Activity Streams

Liferay’s portal, content, and collaboration frameworks are tied together using a rich suite of social features. For developers, plugging social software into Liferay can be achieved in many ways. For example, using the native Social Relationship API for managing relationships between users (via the com.liferay.portlet. social package), interacting with the Activity Stream (via the SocialActivity model), calculating and visualizing Social Equity participation and contribution values, or dropping OpenSocial gadgets onto a page and managing via Liferay’s Control Panel.

More Information

For up-to-date and in-depth information, please refer to the official documentation for Liferay at http://www.liferay.com/ documentation.

About The Authors

Photo of author James Falkner

James Falkner

James Falkner is an open source evangelist, community manager, and software developer working at Liferay, producers of the world’s leading open source enterprise portal. In addition to Liferay, James has been active in a number of other open source products and projects, including the GlassFish Enterprise portfolio, Community/Social Equity, OpenSolaris, OASIS standards, and more. James is a regular contributor and speaker at industry events such as JavaOne, JAX, and others.

Websites: http://www.liferay.com/web/james.falkner

Email: james.falkner@liferay.com

Blog: http://www.liferay.com/web/james.falkner/blog

Recommended Book

Liferay in action

Liferay in Action is a comprehensive and authoritative guide to building portals on the Liferay 6 platform. Fully supported and authorized by Liferay, this book guides you smoothly from your first exposure to Liferay through the crucial day-to-day tasks of building and maintaining an enterprise portal that works well within your existing IT infrastructure. The book starts with the basics: setting up a development environment and creating a working portal. Then, you’ll learn to build on that foundation with social features, tagging, ratings, and more. As the book progresses, you’ll explore the Portlet 2.0 API, and learn how to create your own portlet applications.


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 - WebM Available for 80% of YouTube Daily Videos

According to Google's John Luther, over 80% of daily YouTube videos are now available in WebM: a completely free and open source codec pack for HTML5 video.  After it was open sourced at Google I/O in the spring, WebM was quickly adopted by browser-makers...

0 replies - 20035 views - 11/15/10 by Mitchell Pronsc... in Daily Dose