Custom Tags as an Alternative to Composite Components in JSF

Composite components are well known and the concept is widely adopted by JSF developers today. Regrettably, another powerful concept seems to be ousted by the popularity of composite components: Custom (Facelet)-Tags. This article is about how to use them.

The basic idea is to have a piece of XHTML code residing in an own document. This snippet can be included in a page using a tag with with custom name. The following example shows a custom “quote” tag that acts as decorator by wrapping its content with a div-element. This is what the rendered output may look like:


Weiterlesen

Veröffentlicht unter Did you know?, Java Web Frameworks | Verschlagwortet mit , , , | 1 Kommentar

Spring Data JPA 1.1.0 veröffentlicht

Mit Spring Data JPA läßt sich sehr leicht eine auf JPA basierende Datenzugriffsschicht realisieren. Features sind unter anderem eine generische DAO Implementierung, Auditierung von Domain-Objekten, Unterstützung von Paging und dynamischen Abfragen und Integration der Query-DSL (typsichere JPA-Abfrage-Alternative).

Mittlerweile ist die Version 1.1.0 veröffentlicht. Wichtige Änderungen sind unter anderem:

  • Integration von CDI (Context and Dependency Injection, JSR 299) in Repositories
  • weitere Schlüsselwörter für die Generation von Abfragen: Before, After, StartsWith, LessThanEqual, …
  • Unterstützung von nativen SQL in @Query

Weitere Infos gibt finden sich im offiziellen Release-Blogpost.

Veröffentlicht unter Java EE, Java Persistence, Java Runtimes - VM, Appserver & Cloud, Spring Universe | Verschlagwortet mit , , , | Hinterlasse einen Kommentar

JPA Security

Mit JPA Security gibt es eine relativ neue Access Control Lösung für objektrelationale Datenbankzugriffe über die Java Persistence API. Der große Vorteil gegenüber anderen Sicherheitslösungen ist, daß die Zugriffskontrolle und das Ausfiltern in der Datenbank stattfindet. Nicht erlaubte Daten werden also gar nicht erst geladen, wie es beispielsweise Spring Security machen muß, um die Objekte auf Zugriffsbeschränkungen zu untersuchen und gegebenenfalls bereits geladene Daten zu verwerfen.

JPA Security ist ein rein deklarativer Ansatz und kann per Annotationen oder auch XML konfiguriert werden. Sicherheitsrelavanter Code kann dadurch aus der Geschäftslogik eliminiert werden. Das spart vor allem Code-Duplikationen und erleichtert die Les- und Wartbarkeit. Es wird aber nicht versucht, bestehende Security Lösungen zu ersetzen. Vielmehr kann sich JPA Security auch innerhalb von Spring Security oder die Sicherheitsmechanismen der Java EE Plattform integrieren.
Weiterlesen

Veröffentlicht unter Java EE, Java Persistence, Security | Verschlagwortet mit , , | Hinterlasse einen Kommentar

Guava 12.0 released

A few days ago Guava 12.0 was released. We already published a few articles about Guava, a few more will follow in the next weeks. So this release announcement might be interesting for you.

Guava 12.0 is the first release which requires at least JDK 6. Further release notes can be found here.

Some nice features are:

  • FluentIterable provides a fluent interface for manipulating Iterables with chained method calls:

FluentIterable
  .from(myIterable)
  .transform(Functions.toStringFunction())
  .limit(10)
  .toImmutableList();

  • Enums.getIfPresent() returns an Optional and can be used to fall back to an optional value in very readable manner:

Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);

  • TypeToken: an alternative to java.lang.Class mechanisms, which uses reflection-based tricks to allow to manipulate and query generic types at runtime.
Veröffentlicht unter Java and Quality, Java Basics | Verschlagwortet mit | Hinterlasse einen Kommentar

Bootstrapping JSF applications with SystemEvents

SystemEvents offer a nice way to respond to events like system startup or  -teardown.

A frequent use case is to log if the application startup was successfull and if all neccessary resources are available. If a problem occurs during startup the application might respond to it or just send a mail to the developers to notify them about the problem.

I also prefer to have a debugging phase listener (see this post from BalusC) in my application. This listener should only be registered if the application is in development stage. The following example shows how to use SystemEventListeners to register the PhaseListener:

public class BootstrappingListener implements SystemEventListener {

	private static final java.util.logging.Logger LOG = java.util.logging.Logger.getLogger(BootstrappingListener.class.getSimpleName());

	@Override
	public boolean isListenerForSource(final Object obj) {
		boolean result = false;
		result = obj instanceof Application;
		return result;
	}

	@Override
	public void processEvent(final SystemEvent event) throws AbortProcessingException {

		if (event instanceof PostConstructApplicationEvent) {
			performBootstrap((PostConstructApplicationEvent) event);
		} else if (event instanceof PreDestroyApplicationEvent) {
			performTearDown((PreDestroyApplicationEvent) event);
		}

	}

	private void performBootstrap(final PostConstructApplicationEvent event) {

		Application application = event.getApplication();
		ProjectStage stage = application.getProjectStage();

		if (ProjectStage.Development == stage) {

			LifecycleFactory lcFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
			Lifecycle lc = lcFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
			lc.addPhaseListener(new DebugPhaseListener());

		}

		// do other stuff related to bootstrapping:
		// 1) check for availablity of web services
		// 2) init ressources
		// ...

		LOG.info("Application startup");
	}

	private void performTearDown(final PreDestroyApplicationEvent event) {

		LOG.info("Application destroyed");

	}
}

The class implements SystemEventListener, thus the methods isListenerForSource() and processEvent() need to be implemented. The first method recieves an object representing the application, so all we have to do is to make sure that it is a valid instance of javax.faces.application.Application. The processEvent method is where stuff happens: In the implementation above the method delegates to another method, depending on the event to handle. The JSF implementation will publish javax.faces.event.PostConstructApplicationEvent on application startup and javax.faces.event.PreDestroyApplicationEvent on shutdown.

In the example, processEvent() calls performBootstrap() to perform several actions on application startup:

  1. A PhaseListenerfor debugging purposes is installed if  the current ProjectStage is ‘DevelopmentStage’ (Note: you can  define the ProjectStage by setting the context-parameter “javax.faces.PROJECT_STAGE” to either one of “Development”,”Production”,”SystemTest” or “UnitTest”)
  2. Other tasks like:
    1. checking the environment for required ressources (e.g. availability of web-services)
    2. initialisation of resources (e.g. creation and pre-initialization of managed beans)
  3. Write to a log file.

The same principle applys to PreDestroyApplicationEvents. In the example above only logging output is created but other scenarios are possible, including notification of developers and/or admins via email / instant messaging / Twitter.

To have the listener called, it needs to be registered in faces-config.xml:

<?xml version="1.0" encoding="UTF-8"?>

<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

    <application>

	    <system-event-listener>

	    	<system-event-listener-class>
	    		de.oio.jsf.BootstrappingListener
	    	</system-event-listener-class>

	    	<system-event-class>
	    		javax.faces.event.PostConstructApplicationEvent
	    	</system-event-class>

	    </system-event-listener>

	    <system-event-listener>

	    	<system-event-listener-class>
	    		de.oio.jsf.BootstrappingListener
    		</system-event-listener-class>

	    	<system-event-class>
	    		javax.faces.event.PreDestroyApplicationEvent
    		</system-event-class>

	    </system-event-listener>

    </application>

</faces-config>

The example uses the same class for both events but this only for convenience. Several listener classes may be registered for both events.

While event listeners may also be defined using annotations, this is unfortunately not an option for PostConstructApplicationEvents.

Veröffentlicht unter Build, config and deploy, Java EE, Java Web Frameworks | Verschlagwortet mit , , | Hinterlasse einen Kommentar

REST API for JPA entities

The intial version 1.0.0.M1 of Spring Data REST has been released.

“Spring Data REST is part of the umbrella Spring Data project that makes it easy to expose JPA based repositories as RESTful endpoints.”

See http://www.springsource.org/spring-data/rest for more details.

Veröffentlicht unter Spring Universe | Verschlagwortet mit , , , | Hinterlasse einen Kommentar

Handling Null values with Guava

Handling null values in Java can be quite annoying. Careless use of null can also be a source of a variety of bugs.

“I call it my billion-dollar mistake.” – Sir C. A. R. Hoare, on his invention of the null reference

“Null sucks.” – Doug Lea

There exists a few guidelines, workarounds and solutions for handling the different occurencess of null values and avoid nasty null pointer (exceptions), for example the Null Object Pattern with its defined neutral (null) behaviour. In the case of returning possible null values from a method or for instance a collection, Guava (Google Core Libraries for Java 1.6+) offers the class Optional.

Weiterlesen

Veröffentlicht unter Java and Quality, Java Basics | Verschlagwortet mit , | Hinterlasse einen Kommentar