JBoss.orgCommunity Documentation

Errai

Errai Reference Guide

Legal Notice

Abstract

This is the Errai Reference Guide.


Preface
1. Document Conventions
2. Feedback
1. Introduction
1.1. What is it?
1.2. Required software
2. Messaging
2.1. Messaging Overview
2.2. Messaging API Basics
2.2.1. Sending Messages with the Client Bus
2.2.2. Recieving Messages on the Server Bus / Server Services
2.2.3. Sending Messages with the Server Bus
2.2.4. Receiving Messages on the Client Bus/ Client Services
2.3. Conversations
2.4. Handling Errors
2.5. Handling Transport Errors
2.6. Single-Response Conversations & Pseudo-Synchronous Messaging
2.7. Broadcasting
2.8. Client-to-Client Communication
2.8.1. Relay Services
2.9. Asynchronous Message Tasks
2.10. Repeating Tasks
2.11. Sender Inferred Subjects
2.12. Message Routing Information
2.13. Queue Sessions
2.13.1. Lifecycle
2.13.2. Scopes
2.14. Client Logging and Error Handling
2.15. Wire Protocol (J.REP)
2.15.1. Payload Structure
2.15.2. Message Routing
2.15.3. Bus Management and Handshaking Protocols
2.16. WebSockets
2.16.1. Configuring the sideband server
2.16.2. Deploying with JBoss AS 7
3. Dependency Injection
3.1. Container Wiring
3.2. Wiring server side components
3.3. Scopes
3.3.1. Dependent Scope
3.4. Built-in Extensions
3.4.1. Bus Services
3.4.2. Client Components
3.4.3. Lifecycle Tools
3.5. Client-Side Bean Manager
3.5.1. Looking up beans
3.5.2. Availability of beans
3.6. Alternatives and Mocks
3.6.1. Alternatives
3.6.2. Test Mocks
3.7. Bean Lifecycle
3.7.1. Destruction of Beans
4. Errai CDI
4.1. Features and Limitations
4.1.1. Other features
4.2. Events
4.2.1. Conversational events
4.2.2. Client-Server Event Example
4.3. Producers
4.4. safe dynamic lookup
4.5. Deploying Errai CDI
4.5.1. Deployment in Development Mode
4.5.2. Deployment to a Servlet Engine
4.5.3. Deployment to an Application Server
5. Marshalling
5.1. Mapping Your Domain
5.1.1. @Portable and @NonPortable
5.1.2. Manual Mapping
5.1.3. Manual Class Mapping
5.1.4. Custom Marshallers
6. Remote Procedure Calls (RPC)
6.1. Making calls
6.1.1. Proxy Injection
6.2. Handling exceptions
6.3. Client-side Interceptors
6.4. Session and request objects in RPC endpoints
7. Errai JAX-RS
7.1. Server-Side Prerequisites
7.1.1. Server-Side JAX-RS Implementation
7.1.2. Shared JAX-RS Interface
7.2. Creating Requests
7.2.1. Proxy Injection
7.3. Handling Responses
7.4. Client-side Interceptors
7.5. Wire Format
7.6. Configuration
7.6.1. Configuring the default root path of JAX-RS endpoints
7.6.2. Enabling Jackson marshalling
8. Errai JPA
8.1. Getting Started
8.1.1. Compile-time dependency
8.1.2. GWT Module Descriptor
8.1.3. INF/persistence.xml
8.1.4. Declaring an Entity Class
8.1.5. Entity Lifecycle States
8.1.6. Obtaining an instance of EntityManager
8.1.7. Named Queries
8.1.8. Entity Lifecycle Events
8.1.9. JPA Metamodel
8.1.10. JPA Features Not Implemented in Errai 2.1
8.1.11. Other Caveats for Errai 2.1 JPA
9. Data Binding
9.1. Bindable Objects
9.2. Initializing a DataBinder
9.3. Creating Bindings
9.4. Specifying Converters
9.4.1. Registering a global default converter
9.4.2. Providing a binding-specific converter
9.5. Property Change Handlers
10. Errai UI
10.1. Get started
10.1.1. App.gwt.xml
10.2. Use Errai UI Composite components
10.2.1. Inject a single instance
10.2.2. Inject multiple instances (for iteration)
10.3. Create a @Templated Composite component
10.3.1. Basic component
10.3.2. Custom template names
10.4. Create an HTML template
10.4.1. Select a template from a larger HTML file
10.5. Use other Widgets in a composite component
10.5.1. Annotate Widgets in the template with @DataField
10.5.2. Add corresponding data-field attributes
10.6. How HTML templates are merged with Components
10.6.1. Example
10.6.2. Element attributes (template wins)
10.6.3. DOM Elements (component field wins)
10.6.4. Inner text and inner HTML (preserved when component implements HasText or HasHTML)
10.7. Event handlers
10.7.1. Concepts
10.7.2. GWT events on Widgets
10.7.3. GWT events on DOM Elements
10.7.4. Native DOM events on Elements
10.8. Data Binding
10.8.1. Default, Simple, and Chained Property Bindings
10.8.2. Binding of Lists
10.8.3. Data Converters
10.9. Nest Composite components
10.10. Extend Composite components
10.10.1. Template
10.10.2. Parent component
10.10.3. Child component
11. Errai UI Navigation
11.1. Getting Started
11.1.1. Compile-time dependency
11.1.2. GWT Module Descriptor
11.2. How it Works
11.2.1. Declaring a Page
11.2.2. Declaring a Link
11.2.3. Following a Link
11.2.4. Installing the Navigation Panel into the User Interface
11.2.5. Viewing the Generated Navigation Graph
12. Configuration
12.1. Appserver Configuration
12.2. Client Configuration
12.2.1. Disabling remote communication
12.2.2. Configuring an alternative remote remote bus endpoint
12.3. ErraiApp.properties
12.3.1. As a Marker File
12.3.2. As a Configuration File
12.4. ErraiService.properties
12.4.1. Configuration Properties
12.4.2. Example Configuration
12.5. Dispatcher Implementations
12.5.1. SimpleDispatcher
12.5.2. AsyncDispatcher
12.6. Servlet Implementations
12.6.1. DefaultBlockingServlet
12.6.2. JBossCometServlet
12.6.3. JettyContinuationsServlet
12.6.4. StandardAsyncServlet
13. Debugging Errai Applications
14. Troubleshooting & FAQ
14.1. Why does it seem that Errai can't see my class at compile time?
14.2. Why am I getting "java.lang.ClassFormatError: Illegal method name "<init>$" in class org/xyz/package/MyClass"?
14.3. I'm getting "java.lang.RuntimeException: There are no proxy providers registered yet." in my @PostConstruct method!
15. Upgrade Guide
15.1. Upgrading from 1.* to 2.0
15.2. Upgrading from 2.0.Beta to 2.0.*.Final
16. Downloads
17. Sources
18. Reporting problems
19. Errai License
A. Revision History

Errai requires a JDK version 6 or higher and depends on Apache Maven to build and run the examples, and for leveraging the quickstart utilities.

Launching maven the first time

Please note, that when launching maven the first time on your machine, it will fetch all dependencies from a central repository. This may take a while, because it includes downloading large binaries like GWT SDK. However, subsequent builds are not required to go through this step and will be much faster.

This section covers the core messaging concepts of the ErraiBus messaging framework.

ErraiBus forms the backbone of the Errai framework's approach to application design. Most importantly, it provides a straight-forward approach to a complex problem space. Providing common APIs across the client and server, developers will have no trouble working with complex messaging scenarios from building instant messaging clients, stock tickers, to monitoring instruments. There's no more messing with RPC APIs, or unweildy AJAX or COMET frameworks. We've built it all in to one, consice messaging framework. It's single-paradigm, and it's fun to work with.

The MessageBuilder is the heart of the messaging API in ErraiBus. It provides a fluent / builder API, that is used for constructing messages. All three major message patterns can be constructed from the MessageBuilder .

Components that want to receive messages need to implement the MessageCallback interface.

But before we dive into the details, let look at some use cases first.

In order to send a message from a client you need to create a Message and send it through an instance of MessageBus . In this simple example we send it to the subject 'HelloWorldService'.

In the above example we build and send a message every time the button is clicked. Here's an explanation of what's going on as annotated above:

In the following example we extend our server side component to reply with a message when the callback method is invoked. It will create a message and address it to the subject ' HelloWorldClient ':

The above example shows a service which sends a message in response to receiving a message. Here's what's going on:

Asynchronous messaging necessitates the need for asynchronous error handling. Luckily, support for handling errors is built directly into the MessageBuilder API, utilizing the ErrorCallback interface. In the examples shown in previous exceptions, error handing has been glossed over with aubiquitous usage of the noErrorHandling() method while building messaging. We chose to require the explicit use of such a method to remind developers of the fact that they are responsible for their own error handling, requiring you to explicitly make the decision to forego handling potential errors.

As a general rule, you should always handle your errors . It will lead to faster and quicker identification of problems with your applications if you have error handlers, and generally help you build more robust code.

The addition of error handling at first may put off developers as it makes code more verbose and less-readable. This is nothing that some good practice can't fix. In fact, you may find cases where the same error handler can appropriately be shared between multiple different calls.

The error handler is required to return a boolean value. This is to indicate whether or not Errai should perform the default error handling actions it would normally take during a failure. You will almost always want to return true here, unless you are trying to explicitly surpress some undesirably activity by Errai, such as automatic subject-termination in conversations. But this is almost never the case.

Errai further provides a subject to subscribe to for handling global errors on the client (such as a disconnected server bus or an invalid response code) that occur outside a regular application message exchange. Subscribing to this subject is useful to detect errors early (e.g. due to failing heartbeat requests). A use case that comes to mind here is activating your application's offline mode.

A repeating task is sent using one of the MessageBuilder's repeatXXX() methods. The task will repeat indefinitely until cancelled (see next section).

The above example sends a message very 1 second with a message part called "time" , containing a formatted time string. Note the use of the withProvided() method; a provided message part is calculated at the time of transmission as opposed to when the message is constructed.

Cancelling an Asynchronous TaskA delayed or repeating task can be cancelled by calling the cancel() method of the AsyncTask instance which is returned when creating a task. Reference to the AsyncTask object can be retained and cancelled by any other thread.

Every message that is sent between a local and remote (or server and client) buses contain session routing information. This information is used by the bus to determine what outbound queues to use to deliver the message to, so they will reach their intended recipients. It is possible to manually specify this information to indicate to the bus, where you want a specific message to go.

You can obtain the SessionID directly from a Message by getting the QueueSession resource:

You can extract the SessionID from a message so that you may use it for routing by obtaining the QueueSession resource from the Message . For example:

The SessionID can then be stored in a medium, say a Map, to cross-reference specific users or whatever identifier you wish to allow one client to obtain a reference to the specific SessionID of another client. In which case, you can then provide the SessionID as a MessagePart to indicate to the bus where you want the message to go.

By providing the SessionID part in the message, the bus will see this and use it for routing the message to the relevant queue.

It may be tempting however, to try and include destination SessionIDs at the client level, assuming that this will make the infrastructure simpler. But this will not achieve the desired results, as the bus treats SessionIDs as transient. Meaning, the SessionID information is not ever transmitted from bus-to-bus, and therefore is only directly relevant to the proximate bus.

The ErraiBus maintains it's own seperate session management on-top of the regular HTTP session management. While the queue sessions are tied to, and dependant on HTTP sessions for the most part (meaning they die when HTTP sessions die), they provide extra layers of session tracking to make dealing with complex applications built on Errai easier.

ErraiBus implements a JSON-based wire protocol which is used for the federated communication between different buses. The protocol specification encompasses a standard JSON payload structure, a set of verbs, and an object marshalling protocol. The protocol is named J.REP. Which stands for JSON Rich Event Protocol.

All wire messages sent across are assumed to be JSON arrays at the outermost element, contained in which, there are 0..n messages. An empty array is considered a no-operation, but should be counted as activity against any idle timeout limit between federated buses.


In Figure 1 , we see an example of a J.REP payload containing two messages. One bound for an endpoint named "SomeEndpoint" and the other bound for the endpoint "SomeOtherEndpoint" . They both include a payload element "Value" which contain strings. Let's take a look at the anatomy of an individual message.


The message shown in Figure 2 shows a very vanilla J.REP message. The keys of the JSON Object represent individual message parts , with the values representing their corresponding values. The standard J.REP protocol encompasses a set of standard message parts and values, which for the purposes of this specification we'll collectively refer to as the protocol verbs.

The following table describes all of the message parts that a J.REP capable client is expected to understand:

Part

Required

JSON Type

Description

ToSubject

Yes

String

Specifies the subject within the bus, and its federation, which the message should be routed to.

CommandType

No

String

Specifies a command verb to be transmitted to the receiving subject. This is an optional part of a message contract, but is required for using management services

ReplyTo

No

String

Specifies to the receiver what subject it should reply to in response to this message.

Value

No

Any

A recommended but not required standard payload part for sending data to services

PriorityProcessing

No

Number

A processing order salience attribute. Messages which specify priority processing will be processed first if they are competing for resources with other messages in flight. Note: the current version of ErraiBus only supports two salience levels (0 and >1). Any non-zero salience in ErraiBus will be given the same priority relative to 0 salience messages

ErrorMessage

No

String

An accompanying error message with any serialized exception

Throwable

No

Object

If applicable, an encoded object representing any remote exception that was thrown while dispatching the specified service

Federation between buses requires management traffic to negotiate connections and manage visibility of services between buses. This is accomplished through services named ClientBus and ServerBus which both implement the same protocol contracts which are defined in this section.

Both bus services share the same management protocols, by implementing verbs (or commands) that perform different actions. These are specified in the protocol with the CommandType message part. The following table describes these commands:


Part

Required

JSON Type

Description

CapabilitiesFlags

Yes

String

A comma delimited string of capabilities the bus is capable of us

Subject

Yes

String

The subject to subscribe or unsubscribe from

SubjectsList

Yes

Array

An array of strings representing a list of subjects to subscribe to

ErraiBus has support for WebSocket-based communication. When WebSockets are enabled, capable web browsers will attempt to upgrade their COMET-based communication with the server-side bus to use a WebSocket channel.

There are two different ways the bus can enable WebSockets. The first uses a sideband server, which is a small, lightweight server which runs on a different port from the application server. The second is native JBoss AS 7-based integration.

It is currently necessary use the native connector in JBoss AS for WebSockets to work. So the first step is to configure your JBoss AS instance to use the native connector by changing the domain/configuration/domain.xml file, and change the line:

to:

You will then need to configure the servlet in your application's web.xml which will provide WebSocket upgrade support within AS7.

Add the following to the web.xml :

This will tell the bus to enable web sockets support. The websocket-path-element specified the path element within a URL which the client bus should request in order to negotiate a websocket connection. For instance, specifying in.erraiBusWS as we have in the snippit above, will result in attempted negotiation at http://<your_server>:<your_port>/<context_path>/in.erraiBusWS . For this to have any meaningful result, we must add a servlet mapping that will match this pattern:

The core Errai IOC module implements the JSR-330 Dependency Injection specification for in-client component wiring.

Dependency injection (DI) allows for cleaner and more modular code, by permitting the implementation of decoupled and type-safe components. By using DI, components do not need to be aware of the implementation of provided services. Instead, they merely declare a contract with the container, which in turn provides instances of the services that component depends on.

Classpath Scanning and ErraiApp.properties

Errai only scans the contents of classpath locations (JARs and directories) that have a file called ErraiApp.properties at their root. If dependency injection is not working for you, double-check that you have an ErraiApp.properties in every JAR and directory that contains classes Errai should know about.

A simple example:



public class MyLittleClass {
  private final TimeService timeService;
  @Inject
  public MyLittleClass(TimeService timeService) {
    this.timeService = timeService;
  }
  public void printTime() {
    System.out.println(this.timeService.getTime());
  }
}

In this example, we create a simple class which declares a dependency using @Inject for the interface TimeService . In this particular case, we use constructor injection to establish the contract between the container and the component. We can similarly use field injection to the same effect:



public class MyLittleClass {
  @Inject
  private TimeService timeService;
  public void printTime() {
    System.out.println(this.timeService.getTime());
  }
}

In order to inject TimeService , you must annotate it with @ApplicationScoped or the Errai DI container will not acknowledge the type as a bean.



@ApplicationScoped
public class TimeService {
}

Best Practices

Although field injection results in less code, a major disadvantage is that you cannot create immutable classes using the pattern, since the container must first call the default, no argument constructor, and then iterate through its injection tasks, which leaves the potential – albeit remote – that the object could be left in an partially or improperly initialized state. The advantage of constructor injection is that fields can be immutable (final), and invariance rules applied at construction time, leading to earlier failures, and the guarantee of consistent state.

In contrast to Gin , the Errai IOC container does not provide a programmatic way of creating and configuring injectors. Instead, container-level binding rules are defined by implementing a Provider , which is scanned for and auto-discovered by the container.

A Provider is essentially a factory which produces type instances within in the container, and defers instantiation responsibility for the provided type to the provider implementation. Top-level providers use the standard javax.inject.Provider<T> interface.

Types made available as top-level providers will be available for injection in any managed component within the container.

Out of the box, Errai IOC implements these default top-level providers, all defined in the org.jboss.errai.ioc.client.api.builtin package:

  • CallerProvider : Makes RPC Caller<T> objects available for injection.

  • DisposerProvider : Makes Errai IoC Disposer<T> objects available for injection.

  • InitBallotProvider : Makes instances of InitBallot available for injection.

  • IOCBeanManagerProvider : Makes Errai's client-side bean manager, IOCBeanManager , available for injection.

  • MessageBusProvider : Makes Errai's client-side MessageBus singleton available for injection.

  • RequestDispatcherProvider : Makes an instance of the RequestDispatcher available for injection.

  • RootPanelProvider : Makes GWT's RootPanel singleton injectable.

  • SenderProvider : Makes MessageBus Sender<T> objects available for injection.

Implementing a Provider is relatively straight-forward. Consider the following two classes:

TimeService.java



public interface TimeService {
  public String getTime();
}

TimeServiceProvider.java



@IOCProvider
@Singleton
public class TimeServiceProvider implements Provider<TimeService> {
  @Override
  public TimeService get() {
    return new TimeService() {
      public String getTime() {
        return "It's midnight somewhere!";
      }
    };
  }
}

If you are familiar with Guice, this is semantically identical to configuring an injector like so:



Guice.createInjector(new AbstractModule() {
  public void configure() {
    bind(TimeService.class).toProvider(TimeServiceProvider.class);
  }
 }).getInstance(MyApp.class);

As shown in the above example code, the annotation @IOCProvider is used to denote top-level providers.

The classpath will be searched for all annotated providers at compile time.

Important

Top-level providers are regular beans, so they can inject dependencies–particularly from other top-level providers–as necessary.

As Errai IOC provides a container-based approach to client development, support for Errai services are exposed to the container so they may be injected and used throughout your application where appropriate. This section covers those services.

The IOC container, by default, provides a set of default injectable bean types. They range from basic services, to injectable proxies for RPC. This section covers the facilities available out-of-the-box.

A problem commonly associated with building large applications in the browser is ensuring that things happen in the proper order when code starts executing. Errai IOC provides you tools which permit you to ensure things happen before initialization, and forcing things to happen after initialization of all of the Errai services.

It may be necessary at times to obtain instances of beans managed by Errai IOC from outside the container managed scope or creating a hard dependency from your bean. Errai IOC provides a simple client-side bean manager for handling these scenarios: org.jboss.errai.ioc.client.container.IOCBeanManager .

As you might expect, you can inject the bean manager into any of your managed beans.


If you need to access the bean manager outside a managed bean, such as in a unit test, you can access it by calling org.jboss.errai.ioc.client.container.IOC.getBeanManager()

It may be desirable to have multiple matching dependencies for a given injection point with the ability to specify which implementation to use at runtime. For instance, you may have different versions of your application which target different browsers or capabilities of the browser. Using alternatives allows you to share common interfaces among your beans, while still using dependency injection, by exporting consideration of what implementation to use to the container's configuration.

Consider the following example:

and

In our controller logic we in turn inject the View interface:

This code is unaware of the implementation of View , which maintains good separation of concerns. However, this of course creates an ambiguous dependency on the View interface as it has two matching subtypes in this case. Thus, we must configure the container to specify which alternative to use. Also note, that the beans in both cases have been annotated with javax.enterprise.inject.Alternative .

In your ErraiApp.properties for the module, you can simply specify which active alternative should be used:

You can specify multiple alternative classes by white space separating them:

You can only have one enabled alternative for a matching set of alternatives, otherwise you will get ambiguous resolution errors from the container.

Similar to alternatives, but specifically designed for testing scenarios, you can replace beans with mocks at runtime for the purposes of running unit tests. This is accomplished simply by annotating a bean with the org.jboss.errai.ioc.client.api.TestMock annotation. Doing so will prioritize consideration of the bean over any other matching beans while running unit tests.

Consider the following:

You can specify a mock implementation of this class by implementing its common parent type ( UserManagement ) and annotating that class with the @TestMock annotation inside your test package like so:

In this case, the container will replace the UserManagementImpl with the MockUserManagementImpl automatically when running the unit tests.

The @TestMock annotation can also be used to specify alternative providers during test execution. For example, it can be used to mock a Caller<T> . Callers are used to invoke RPC or JAX-RS endpoints. During tests you might want to replace theses callers with mock implementations. For details on providers see Section 3.1, “Container Wiring” .



@TestMock @IOCProvider
public class MockedHappyServiceCallerProvider implements ContextualTypeProvider<Caller<HappyService>> {
 
  @Override
  public Caller<HappyService> provide(Class<?>[] typeargs, Annotation[] qualifiers) {
    return new Caller<HappyService>() {
      ...
    }
}

All beans managed by the Errai IOC container support the @PostConstruct and @PreDestroy annotations.

Beans which have methods annotated with @PostConstruct are guaranteed to have those methods called before the bean is put into service, and only after all dependencies within its graph has been satisfied.

Beans are also guaranteed to have their @PreDestroy annotated methods called before they are destroyed by the bean manager.

Beans under management of Errai IOC, of any scope, can be explicitly destroyed through the client bean manager. Destruction of a managed bean is accomplished by passing a reference to the destroyBean() method of the bean manager.


When the bean manager "destroys" the bean, any pre-destroy methods the bean declares are called, it is taken out of service and no longer tracked by the bean manager. If there are references on the bean by other objects, the bean will continue to be accessible to those objects.

Important

Container managed resources that are dependent on the bean such as bus service endpoints or CDI event observers will also be automatically destroyed when the bean is destroyed.

Another important consideration is the rule, "all beans created together are destroyed together." Consider the following example:



In this example we pass the instance of AnotherBean, created as a dependency of SimpleBean, to the bean manager for destruction. Because this bean was created at the same time as its parent, its destruction will also result in the destruction of SimpleBean ; thus, this action will result in the @PreDestroy cleanUp() method of SimpleBean being invoked.

CDI (Contexts and Dependency Injection) is the Jave EE standard (JSR-299) for handling dependency injection. In addition to dependency injection, the standard encompasses component lifecycle, application configuration, call-interception and a decoupled, type-safe eventing specification.

The Errai CDI extension implements a subset of the specification for use inside of client-side applications within Errai, as well as additional capabilities such as distributed eventing.

Errai CDI does not currently implement all life cycles specified in JSR-299 or interceptors. These deficiencies may be addressed in future versions.

Important

Errai CDI is implemented as an extension on top of the Errai IOC Framework (see Chapter 3, Dependency Injection ), which itself implements JSR-330. Inclusion of the CDI module your GWT project will result in the extensions automatically being loaded and made available to your application.

Classpath Scanning and ErraiApp.properties

Errai CDI only scans the contents of classpath locations (JARs and directories) that have a file called ErraiApp.properties at their root. If CDI features such as dependency injection, event observation, and @PostConstruct are not working for your classes, double-check that you have an ErraiApp.properties at the root of every JAR and directory tree that contains classes Errai should know about.

Any CDI managed component may produce and consume events . This allows beans to interact in a completely decoupled fashion. Beans consume events by registering for a particular event type and optional qualifiers. The Errai CDI extension simply extends this concept into the client tier. A GWT client application can simply register an Observer for a particular event type and thus receive events that are produced on the server-side. Likewise and using the same API, GWT clients can produce events that are consumed by a server-side observer.

Let's take a look at an example.


Two things are noteworthy in this example:

  1. Injection of an Event dispatcher proxy

  2. Creation of an Observer method for a particular event type

The event dispatcher is responsible for sending events created on the client-side to the server-side event subsystem (CDI container). This means any event that is fired through a dispatcher will eventually be consumed by a CDI managed bean, if there is an corresponding Observer registered for it on the server side.

In order to consume events that are created on the server-side you need to declare an client-side observer method for a particular event type. In case an event is fired on the server this method will be invoked with an event instance of type you declared.

To complete the example, let's look at the corresponding server-side CDI bean:


A key feature of the Errai CDI framework is the ability to federate the CDI eventing bus between the client and the server. This permits the observation of server produced events on the client, and vice-versa.

Example server code:


Domain-model:



Client application logic:


If you do not care about the deployment details for now and just want to get started take a look at the Quickstart Guide .

The CDI integration is a plugin to the Errai core framework and represents a CDI portable extension. Which means it is discovered automatically by both Errai and the CDI container. In order to use it, you first need to understand the different runtime models involved when working GWT, Errai and CDI.

Typically a GWT application lifecycle begins in Development Mode and finally a web application containing the GWT client code will be deployed to a target container (Servlet Engine, Application Server). This is no way different when working with CDI components to back your application.

What's different however is availability of the CDI container across the different runtimes. In GWT development mode and in a pure servlet environment you need to provide and bootstrap the CDI environment on your own. While any Java EE 6 Application Server already provides a preconfigured CDI container. To accomodate these differences, we need to do a little trickery when executing the GWT Development Mode and packaging our application for deployment.

In development mode we need to bootstrap the CDI environment on our own and make both Errai and CDI available through JNDI (common denominator across all runtimes). Since GWT uses Jetty, that only supports read only JNDI, we need to replace the default Jetty launcher with a custom one that will setup the JNDI bindings:

Once this is set up correctly, we can bootstrap the CDI container through a servlet listener:

We provide integration with the JBoss Application Server , but the requirements are basically the same for other vendors. When running a GWT client app that leverages CDI beans on a Java EE 6 application server, CDI is already part of the container and accessible through JNDI ( java:/BeanManager ).

Errai includes a comprehensive marshalling framework which permits the serialization of domain objects between the browser and the server. From the perspective of GWT, this is a complete replacement for the provided GWT serialization facilities and offers a great deal more flexibility. You are be able to map both application-specific domain model, as well as preexisting model, including model from third-party libraries using the custom definitions API.

All classes that you intend to be marshalled between the client and the server must be exposed to the marshalling framework. There are several ways you can do it and this section will take you through the different approaches you can take to fit your needs.

To make a Java class eligible for serialization with Errai Marshalling, mark it with the org.jboss.errai.common.client.api.annotations.Portable annotation. This tells the marshalling system to generate marshalling and demarshalling code for the annotated class and all of its nested classes.

The mapping strategy that will be used depends on how much information you provide about your model up-front. If you simply annotate a domain type with @Portable and do nothing else, the marshalling system will use and exhaustive strategy to determine how to construct and deconstruct instances of that type and its nested types.

The Errai marshalling system works by enumerating all of the Portable types it can find (by any of the three methods discussed in this section of the reference guide), eliminating all the non-portable types it can find (via @NonPortable annotations and entries in ErraiApp.properties ), then enumerating the marshallable properties that make up each remaining portable entity type. The rules that Errai uses for enumerating the properties of a portable entity type are as follows:

Note that the existence of methods called getFoo() , setFoo() , or both, does not mean that the entity has a property called foo . Errai Marshalling always works from fields when discovering properties.

When reading a field foo , Errai Marshalling will call the method getFoo() in preference to direct field access if the getFoo() method exists.

Similarly, when writing a field foo , Errai Marshalling will call the method setFoo() in preference to direct field access if the setFoo() method exists.

The above rules are sufficient for marshalling an existing entity to a JSON representation, but for de-marshalling, Errai must also know how to obtain an instance of a type. The rules that Errai uses for deciding how to create an instance of a @Portable type are as follows:

Now let's take a look at some common examples of how this works.

For types with a large number of optional attributes, a builder is often the best approach.

In this example, we have a nested Builder class that implements the Builder Pattern and calls the private Person constructor. Hand-written code will always use the builder to create Person instances, but the @MapsTo annotations on the private Person constructor tell Errai Marshalling to bypass the builder and construct instances of Person directly.

One final note: as a nested type of Person (which is marked @Portable ), the builder itself would normally be portable. However, we do not intend to move instances of Person.Builder across the network, so we mark Person.Builder as @NonPortable .

Some classes may be out of your control, making it impossible to annotate them for auto-discovery by the marshalling framework. For cases such as this, there are two approaches which can be undertaken to include these classes in your application.

The first approach is the easiest, but is contingent on whether or not the class is directly exposed to the GWT compiler. That means, the classes must be part of a GWT module and within the GWT client packages. See the GWT documentation on Client-Side Code for information on this.

The marshalling framework supports and promotes the concept of marshalling by interface contract, where possible. For instance, the framework ships with a marshaller which can marshall data to and from the java.util.List interface. Instead of having custom marshallers for classes such as ArrayList and LinkedList , by default, these implementations are merely aliased to the java.util.List marshaller.

There are two distinct ways to go about doing this. The most straightforward is to specify which marshaller to alias when declaring your class is @Portable .

In the case of this example, the marshaller will not attempt to comprehend your class. Instead, it will merely rely on the java.util.List marshaller to dematerialize and serialize instances of this type onto the wire.

If for some reason it is not feasible to annotate the class, directly, you may specify the mapping in the ErraiApp.properties file using the errai.marshalling.mappingAliases attribute.

The list of classes is whitespace-separated so that it may be split across lines.

The example above shows the equivalent mapping for the MyListImpl class from the previous example, as well as a mapping of a class to the java.util.Map marshaller.

The syntax of the mapping is as follows: <class_to_map> -> <contract_to_map_to> .

Although the default marshalling strategies in Errai Marshalling will suit the vast majority of use cases, there may be situations where it is necessary to manually map your classes into the marshalling framework to teach it how to construct and deconstruct your objects.

This is accomplished by specifying MappingDefinition classes which inform the framework exactly how to read and write state in the process of constructing and deconstructing objects.

All manual mappings should extend the org.jboss.errai.marshalling.rebind.api.model.MappingDefinition class. This is base metadata class which contains data on exactly how the marshaller can deconstruct and construct objects.

Consider the following class:

Let us construct this object like so:

It is clear that we may rely on this object's two getter methods to extract the totality of its state. But due to the fact that the mySuperName field is final, the only way to properly construct this object is to call its only public constructor and pass in the desired value of mySuperName .

Let us consider how we could go about telling the marshalling framework to pull this off:

And that's it. This describes to the marshalling framework how it should go about constructing and deconstructing MySuperCustomEntity .

Paying attention to our annotating comments, let's describe what we've done here.

There is another approach to extending the marshalling functionality that doesn't involve mapping rules, and that is to implement your own Marshaller class. This gives you complete control over the parsing and emission of the JSON structure.

The implementation of marshallers is made relatively straight forward by the fact that both the server and the client share the same JSON parsing API.

Consider the included java.util.Date marshaller that comes built-in to the marshalling framework:


The class is annotated with both @ClientMarshaller and @ServerMarshaller indicating that this class should be used for both marshalling on the client and on the server.

The demarshall() method does what its name implies: it is responsible for demarshalling the object from JSON and turning it back into a Java object.

The marshall() method does the opposite, and encodes the object into JSON for transmission on the wire.

ErraiBus supports a high-level RPC layer to make typical client-server RPC communication easy on top of the bus. While it is possible to use ErraiBus without ever using this API, you may find it to be a more useful and concise approach for exposing services to the clients.

Please note that this API has changed since version 1.0. RPC services provide a way of creating type-safe mechanisms to make client-to-server calls. Currently, this mechanism only support client-to-server calls, and not vice-versa.

Creating a service is straight forward. It requires the definition of a remote interface, and a service class which implements it. See the following:



@Remote
public interface MyRemoteService {
  public boolean isEveryoneHappy();
}

The @Remote annotation tells Errai that we'd like to use this interface as a remote interface. The remote interface must be part of of the GWT client code. It cannot be part of the server-side code, since the interface will need to be referenced from both the client and server side code. That said, the implementation of a service is relatively simple to the point:



@Service
public class MyRemoteServiceImpl implements MyRemoteService {
  public boolean isEveryoneHappy() {
    // blatently lie and say everyone's happy.
    return true;
  }
}

That's all there is to it. You use the same @Service annotation as described in Section 2.4. The presence of the remote interface tips Errai off as to what you want to do with the class.

Calling a remote service involves use of the MessageBuilder API. Since all messages are asynchronous, the actual code for calling the remote service involves the use of a callback, which we use to receive the response from the remote method. Let's see how it works:

In the above example, we declare a remote callback that receives a Boolean, to correspond to the return value of the method on the server. We also reference the remote interface we are calling, and directly call the method. However, don't be tempted to write code like this :

The above code will never return a valid result. In fact, it will always return null, false, or 0 depending on the type. This is due to the fact that the method is dispatched asynchronously, as in, it does not wait for a server response before returning control. The reason we chose to do this, as opposed to emulate the native GWT-approach, which requires the implementation of remote and async interfaces, was purely a function of a tradeoff for simplicity.

Client-side remote call interceptors provide the ability to manipulate or bypass the remote call before it's being sent. This is useful for implementing crosscutting concerns like caching, for example when the remote call should be avoided if the data is already cached locally.

To have a remote call intercepted, either an interface method or the remote interface type has to be annotated with @InterceptedCall . If the type is annotated, all interface methods will be intercepted.

Note that an ordered list of interceptors can be used for specifying an interceptor chain e.g.

Implementing an interceptor is easy:

The RemoteCallContext passed to the aroundInvoke method provides access to the intercepted method's name and read/write access to the parameter values provided at the call site.

Calling proceed executes the next interceptor in the chain or the actual remote call if all interceptors have already been executed. If access to the result of the (asynchronous) remote call is needed in the interceptor, one of the overloaded versions of proceed accepting a RemoteCallback has to be used instead.

The result of the remote call can be manipulated by calling RemoteCallContext.setResult()

Not calling proceed in the interceptor bypasses the actual remote call, passing RestCallContext.getResult() to the RemoteCallBack provided at the call site.

JAX-RS (Java API for RESTful Web Services) is a Java EE standard (JSR-311) for implementing REST-based Web services in Java. Errai JAX-RS brings this standard to the browser and simplifies the integration of REST-based services in GWT client applications. Errai can generate proxies based on JAX-RS interfaces which will handle all the underlying communication and serialization logic. All that's left to do is to invoke a Java method.

Errai's JAX-RS support consists of the following:

  • The Caller<T> interface (the same interface used in Errai RPC)

  • A client-side API to communicate with JAX-RS endpoints

  • A code generator that runs at your project's build time, providing proxy implementations for each JAX-RS resource class visible within the GWT module

  • Errai IoC and CDI providers that allow you to @Inject instances of Caller<T>

  • Integration with either Errai Marshalling or Jackson to translate request and response data between Java object and a string-based wire format

If you want to get started right away with a working Errai JAX-RS CRUD application, use our Maven archetype to get started. See the Quickstart Guide for details.

For Errai's JAX-RS support to work, an interface that bears the JAX-RS annotations must be contained within a GWT module in your project. You will also want these interfaces visible to server-side code so that your JAX-RS resource classes can implement them. This keeps the whole setup typesafe, and reduces duplication to the bare minimum. The natural solution, then is to put the JAX-RS interfaces under the client.shared package within your GWT module:

The contents of the server-side files would be as follows:


The above interface is visible both to server-side code and to client-side code. It is used by client-side code to describe the available operations, their parameter types, and their return types. If you use your IDE's refactoring tools to modify this interface, both the server-side and client-side code will be updated automatically.


The above class implements the shared interface. Since it performs database and/or filesystem operations to manipulate the persistent data store, it is not GWT translatable, and it's therefore kept in a package that is not part of the GWT module.

Save typing and reduce duplication

Note that all JAX-RS annotations ( @Path , @GET , @Consumes , and so on) can be inherited from the interface. You do not need to repeat these annotations in your resource implementation classes.

An instance of Errai's RemoteCallback<T> has to be passed to the RestClient.create() call, which will provide access to the JAX-RS resource method's result. T is the return type of the JAX-RS resource method. In the example below it's just a Long representing a customer ID, but it can be any serializable type (see Chapter 5, Marshalling ).



RemoteCallback<Long> callback = new RemoteCallback<Long>() {
  public void callback(Long id) {
    Window.alert("Customer created with ID: " + id);
  }
};

A special case of this RemoteCallback is the ResponseCallback which can be used as an alternative. It provides access to the Response object representing the underlying HTTP response. This is useful when more details of the HTTP response are needed, such as headers, the status code, etc. The ResponseCallback can also be used for JAX-RS interface methods that return a javax.ws.rs.core.Response type. The MarshallingWrapper class can be used to demarshall the response body to an entity of the desired type.



ResponseCallback callback = new ResponseCallback() {
  public void callback(Response response) {
    Window.alert("HTTP status code: " + response.getStatusCode());
    Window.alert("HTTP response body: " + response.getText());
  }
};

For handling errors, Errai's error callback mechanism can be reused and an instance of ErrorCallback can optionally be passed to the RestClient.create() call. In case of an HTTP error, the ResponseException provides access to the Response object. All other Throwables indicate a communication problem.



ErrorCallback errorCallback = new ErrorCallback() {
  public boolean error(Message message, Throwable throwable) {
    try {
      throw throwable;
    }
    catch (ResponseException e) {
      Response response = e.getResponse();
      // process unexpected response
      response.getStatusCode();
    }
    catch (Throwable t) {
      // process unexpected error (e.g. a network problem)
    }
    return false;
  }
};

Client-side remote call interceptors provide the ability to manipulate or bypass the request before it's being sent. This is useful for implementing crosscutting concerns like caching or security features e.g:

To have a JAX-RS remote call intercepted, either an interface method or the remote interface type has to be annotated with @InterceptedCall . If the type is annotated, all interface methods will be intercepted.

Note that an ordered list of interceptors can be used for specifying an interceptor chain e.g.

Implementing an interceptor is easy:

The RestCallContext passed to the aroundInvoke method provides access to the context of the intercepted JAX-RS (REST) remote call. It allows to read and write the parameter values provided at the call site and provides read/write access to the RequestBuilder instance which has the URL, HTTP headers and parameters set.

Calling proceed executes the next interceptor in the chain or the actual remote call if all interceptors have already been executed. If access to the result of the (asynchronous) remote call is needed in the interceptor, one of the overloaded versions of proceed accepting a RemoteCallback has to be used instead.

The result of the remote call can be manipulated by calling RestCallContext.setResult()

Not calling proceed in the interceptor bypasses the actual remote call, passing RestCallContext.getResult() to the RemoteCallBack provided at the call site.

Errai's JSON format will be used to serialize/deserialize your custom types. See Chapter 5, Marshalling for details.

Alternatively, a Jackson compatible JSON format can be used on the wire. See Configuration for details on how to enable Jackson marshalling.

Starting with Errai 2.1, Errai implements a subset of JPA 2.0. With Errai JPA, you can store and retrieve entity objects on the client side, in the browser's local storage. This allows the reuse of JPA-related code (both entity class definitions and procedural logic that uses the EntityManager) between client and server.

Errai JPA implements the following subset of JPA 2.0:

  • Annotation-based configuration

  • Entity Types with

    • Identifiers of any numeric type (int, long, short, etc.)

      • Generated identifiers

    • Regular attributes of any JPA Basic type (Java primitive types, boxed primitives, enums, BigInteger, BigDecimal, String, Date, Time, and Timestamp)

    • Singular and Plural (collection-valued) attributes of other entity types

      • All association types (one-to-one, one-to-many, many-to-one, many-to-many)

      • All association cascade rules (ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH)

      • Circular and self references work properly

    • Property access by field or get/set methods

  • Named, typed JPQL queries that select exactly one entity type

    • With cascading fetch of related entities

    • With or without WHERE clause

      • All boolean, arithmetic, and string operators supported

      • All String manipulation functions supported

    • With or without ORDER BY clause

  • Lifecycle events and entity lifecycle listeners

  • Much of the Metamodel API ( Metamodel , EntityType , SingularAttribute , PluralAttribute , etc.)

It's all client-side

Errai JPA is a declarative, typesafe interface to the web browser's localStorage object. As such it is a client-side implementation of JPA. Objects are stored and fetched from the browser's local storage, not from the JPA provider on the server side.

Classes whose instances can be stored and retrieved by JPA are called entities . To declare a class as a JPA entity, annotate it with @Entity .

JPA requires that entity classes conform to a set of rules. These are:

Here is an example of a valid entity class with an ID attribute ( id ) and a String-valued persistent attribute ( name ):

When an entity changes state (more on this later), that state change can be cascaded automatically to related entity instances. By default, no state changes are cascaded to related entities. To request cascading of entity state changes, use the cascade attribute on any of the relationship quantifiers @OneToOne , @ManyToOne , @OneToMany , and @ManyToMany .

CascadeType value

Description

PERSIST

Persist the related entity object(s) when this entity is persisted

MERGE

Merge the attributes of the related entity object(s) when this entity is merged

REMOVE

Remove the related entity object(s) from persistent storage when this one is removed

REFRESH

Not applicable in Errai JPA

DETACH

Detach the related entity object(s) from the entity manager when this object is detached

ALL

Equivalent to specifying all of the above

For an example of specifying cascade rules, refer to the Artist example above. In that example, the cascade type on albums is ALL . When a particular Artist is persisted or removed, detached, etc., all of that artist's albums will also be persisted or removed, or detached correspondingly. However, the cascade rules for genres are different: we only specify PERSIST and MERGE . Because a Genre instance is reusable and potentially shared between many artists, we do not want to remove or detach these when one artist that references them is removed or detached. However, we still want the convenience of automatic cascading persistence in case we persist an Artist which references a new, unmanaged Genre .

The entity manager provides the means for storing, retrieving, removing, and otherwise affecting the lifecycle state of entity instances.

To obtain an instance of EntityManager on the client side, use Errai IoC (or CDI) to inject it into any client-side bean:

To retrieve one or more entities that match a set of criteria, Errai JPA allows the use of JPA named queries . Named queries are declared in annotations on entity classes.

To receive a notification when an entity instance transitions from one lifecycle state to another, use an entity lifecycle listener.

These annotations can be applied to methods in order to receive notifications at certain points in an entity's lifecycle. These events are delivered for direct operations initiated on the EntityManager as well as operations that happen due to cascade rules.

Annotation

Meaning

@PrePersist

The entity is about to be persisted or merged into the entity manager.

@PostPersist

The entity has just been persisted or merged into the entity manager.

@PreUpdate

The entity's state is about to be captured into the browser's localStorage.

@PostUpdate

The entity's state has just been captured into the browser's localStorage.

@PreRemove

The entity is about to be removed from persistent storage.

@PostRemove

The entity has just been removed from persistent storage.

@PostLoad

The entity's state has just been retrieved from the browser's localStorage.

JPA lifecycle event annotations can be placed on methods in the entity type itself, or on a method of any type with a public no-args constructor.

To receive lifecycle event notifications directly on the affected entity instance, create a no-args method on the entity class and annotate it with one or more of the lifecycle annotations in the above table.

For example, here is a variant of the Album class where instances receive notification right after they are loaded from persistent storage:

To receive lifecycle methods in a different class, declare a method that takes one parameter of the entity type and annotate it with the desired lifecycle annotations. Then name that class in the @EntityListeners annotation on the entity type.

The following example produces the same results as the previous example:

Errai captures structural information about entity types at compile time and makes them available in the GWT runtime environment. The JPA metamodel includes methods for enumerating all known entity types and enumerating the singular and plural attributes of those types. Errai extends the JPA 2.0 Metamodel by providing methods that can create new instances of entity classes, and read and write attribute values of existing entity instances.

As an example of what is possible, this functionality could be used to create a reusable UI widget that can present an editable table of any JPA entity type.

To access the JPA Metamodel, call the EntityManager.getMetamodel() method. For details on what can be done with the stock JPA metamodel, see the API's javadoc or consult the JPA specification.

The following features are not yet implemented, but could conceivably be implemented in a future Errai JPA release:

The following may never be implemented due to limitations and restrictions in the GWT client-side environment:

Errai's data binding module provides the ability to bind model objects to UI fields/widgets. The bound properties of the model and the UI components will automatically be kept in sync for as long as they are bound. So, there is no need to write code for UI updates in response to model changes and no need to register listeners to update the model in response to UI changes.

The data binding module is directly integrated with Chapter 10, Errai UI and Chapter 8, Errai JPA but can also be used as a standalone project in any GWT client application by simply inheriting the Data Binding GWT module:


Bindings can be created by calling the bind method on a DataBinder instance, thereby specifying which widgets should be bound to which properties of the model. It is possible to use property chains for bindings, given that all nested properties are of bindable types. When binding to customer.address.streetName , for example, both customer and address have to be of a type annotated with @Bindable .

After the call to dataBinder.bind() in the example above, the customer object's name property and the nameTextBox are kept in sync until either the dataBinder.unbind() method is called or the CustomerView bean is destroyed.

That means that a call to customer.setName() will automatically update the value of the TextBox and any change to the TextBox's value in the browser will update the customer object's name property. So, customer.getName() will always reflect the currently displayed value of the TextBox .

Errai has built-in conversion support for all Number types as well as Boolean and Date to java.lang.String and vice versa. However, in some cases it will be necessary to provide custom converters (e.g. if a custom date format is desired). This can be done on two levels.

One of the primary complaints of GWT to date has been that it is difficult to use "pure HTML" when building and skinning widgets. Inevitably one must turn to Java-based configuration in order to finish the job. Errai, however, strives to remove the need for Java styling. HTML template files are placed in the project source tree, and referenced from custom "Composite components" (Errai UI Widgets) in Java. Since Errai UI depends on Errai IOC and Errai CDI, dependency injection is supported in all custom components. Errai UI provides rapid prototyping and HTML5 templating for GWT.

The Errai UI module is directly integrated with Chapter 9, Data Binding and Errai JPA but can also be used as a standalone project in any GWT client application by simply inheriting the Errai UI GWT module, and ensuring that you have properly using Errai CDI's @Inject to instantiate your widgets:

Templates in Errai UI may be designed either as an HTML snippit, or as a full HTML document. You may even take an existing HTML page and use it as a template. With either approach, the "data-field" annotation is used to identify fragments (by name) in the template, which are used in the Composite component to add behavior, and use additional components to add functionality to the template. There is no limit to how many component classes may share a given HTML template.

We will begin by creating a simple HTML login form to accompany our @Templated LoginForm composite component.

Or as a full HTML document which may be more easily previewed during design without running the application; however, in this case we must also specify the location of our root component DOM Element using a "data-field" matching the value of the @Templated annotation. There is no limit to how many component classes may share a given HTML template.

Notice the corresponding HTML data-field attribute in the form Element below, and also note that multiple components may use the same template provided that they specify a corresponding data-field attribute. Also note that two or more components may share the same template data-field DOM elements; there is no conflict since components each receive a unique copy of the template DOM from the designated data-field at runtime (or from the root element if a fragment is not specified.)

For example's sake, the component below could also use the same template. All it needs to do is reference the template name, and specify a fragment.

Now that we have created the @Templated Composite component and an HTML template, we can start wiring in functionality and behavior; this is done by annotating fields and methods to replace specific sub-elements of the template DOM with other Widgets. We can even replace portions of the template with other Errai UI Widgets!

Three things are merged or modified when Errai UI creates a new Composite component instance:

Dealing with User and DOM Events is a reality in rich web development, and Errai UI provides several approaches for dealing with all types of browser events using its "quick handler" functionality. It is possible to handle:

A recurring implementation task in rich web development is writing event handler code for updating model objects to reflect input field changes in the user interface. The requirement to update user interface fields in response to changed model values is just as common. These tasks require a significant amount of boilerplate code which can be alleviated by Errai. Errai's data binding module provides the ability to bind model objects to user interface fields, so they will be kept in sync automatically. While the module can be used on its own, it can cut even more boilerplate when integrated with Errai UI.

In the following example, all @DataFields annotated with @Bound have their contents bound to properties of the data model (a User object). The model object is provided by an injected DataBinder instance annotated with @AutoBound , which indicates automatic binding should be carried out. This works whether the DataBinder is injected into a field or a constructor.



@Templated
public class LoginForm extends Composite {
   @Inject
   @Bound
   @DataField
   private TextBox username;
   @Inject
   @Bound
   @DataField
   private PasswordTextBox password;
   @DataField
   private Button submit = new Button();
   private User user;
   @Inject
   public LoginForm(@AutoBound DataBinder<User> userBinder) {
     this.user = userBinder.getModel();
   }
}

Now the user object and the username and password fields are automatically kept in sync. No event handling code needs to be written for updating the user object in response to input field changes and no code needs to be written for updating the user interface fields when the model object changes (when setUsername or setPassword is called).

By default, bindings are determined by matching @DataField names to property names on the model object. In the example above, the @DataField username was automatically bound to the JavaBeans property username of the model object. If the @DataField name does not match the model property name, you can use the property attribute of the @Bound annotation to specify the name of the property. The property can be a simple name (for example, "name") or a property chain (for example, user.address.streetName ). When binding to a property chain, all properties but the last in the chain must refer to @Bindable values.

The following example illustrates all three scenarios:

In UserWidget above, the name text box is bound to user.name using the default name matching; the dateOfBirth date picker is bound to user.dob using a simple property name mapping; finally, the city text box is bound to user.address.city using a property chain. Note that the Address class is required to be @Bindable in this case.

The @Bound annotation further allows to specify a converter to use for the binding (see Specifying Converters for details). This is how a binding specific converter can be specified on a data field:



@Inject
@Bound(converter=MyDateConverter.class)
@DataField
private TextBox date;

Errai's DataBinder also allows to register PropertyChangeHandlers for the cases where keeping the model and UI in sync is not enough and additional logic needs to be executed (see Property Change Handlers for details).

Templating would not be complete without the ability to inherit from parent templates, and Errai UI also makes this possible using simple Java inheritance. The only additional requirement is that Composite components extending from a parent Composite component must also be annotated with @Templated, and the path to the template file must also be specified in the child component's annotation. Child components may specify @DataField references that were omitted in the parent class, and they may also override @DataField references (by using the same data-field name) that were already specified in the parent component.

Starting in version 2.1, Errai offers a system for creating applications that have multiple bookmarkable pages. This navigation system has the following features:

  • Declarative, statically-analyzable configuration of pages and links

    • Compile time referential safety (i.e. “no broken links”)

    • Generates a storyboard of the application’s navigation flow at compile time

  • Decentralized configuration

    • Create a new page by creating a new annotated class. No need to edit a second file.

    • Make navigational changes in the natural place in the code.

  • Integrates cleanly with Errai UI templates, but also works well with other view technologies.

  • Builds on Errai IoC & CDI

Errai Navigation has three main parts: the @Page annotation marks any widget as a page; the TransitionTo<P> interface is an injectable type that provides a link to another page; and the Navigation singleton offers control over the navigation system as a whole.

The Navigation singleton owns a GWT Panel called the navigation panel . This panel always contains a widget corresponding to the the fragment ID (the part after the # symbol) in the browser's location bar. Whenever the fragment ID changes for any reason (for example, because the user pressed the back button, navigated to a bookmarked URL, or simply typed a fragment ID by hand), the widget in the navigation panel is replaced by the widget associated with that fragment ID. Likewise, when the application asks the navigation system to follow a link, the fragment ID in the browser's location bar is updated to reflect the new current page.

To declare a page, annotate any subclass of Widget with the @Page annotation:

By default, the name of a page is the simple name of the class that declares it. In the above example, the ItemListPage will fill the navigation panel whenever the browser's location bar ends with #ItemListPage . If you prefer a different page name, use the @Page annotation's path attribute:

A page widget will often represent a view on on instance of a class of things. For example, there might be an ItemPage that displays a particular item available at a store. In cases like this, it's important that the bookmarkable navigation URL includes not only the name of the page but also an identifier for the particular item being displayed.

This is where page state parameters come in. Consider the following page widget:

This page would be reachable at a URL like http://www.company.com/store/#ItemPage;itemId=4 . Before the page was displayed, the Errai UI Navigation framework would write the int value 4 into the itemId field.

There are three ways to pass state information to a page: by passing a Multimap to TransitionTo.go() ; by passing a Multimap to Navigation.goTo() , or by including the state information in the fragment identifier of a hyperlink as illustrated in the previous paragraph (use the HistoryToken class to construct such a fragment ID properly.)

A page widget can have any number of @PageState fields. The fields can be of any primitive or boxed primitive type (except char or Character ), String , or a Collection , List , or Set of the allowable scalar types. Nested collections are not supported.

@PageState fields can be private, protected, default access, or public. They are always updated by direct field access; never via a setter method. The updates occur just before the @PageShowing method is invoked.

In addition to receiving page state information via direct writes to @PageState fields, you can also receive the whole Multimap in the @PageShowing method through a parameter of type HistoryToken . Whether or not the @PageShowing method has such a parameter, the @PageState fields will still be written as usual.

Page state values are represented in the URL much like HTML form parameters: as key=value pairs separated by the ampersand ( & ) character. Multi-valued page state fields are represented by repeated occurrences of the same key. If a key corresponding to a @PageState field is absent from the state information passed to the page, the framework writes a default value: null for scalar Object fields, the JVM default (0 or false) for primitives, and an empty collection for collection-valued fields. To construct and parse state tokens programmatically, use the HistoryToken class.

Now that you've created several pages and injected some links between them, there is one last step to seeing the results in the user interface: you must add the navigation panel somewhere in the document. The best time to do this is during application startup, for example in the @PostConstruct method of your @EntryPoint class. You can allow Errai Navigation to control the full contents of the page, or you can opt to keep some parts of the page (headers, footers, and sidebars, for example) away from Errai Navigation.

This example code gives the Navigation system control of the full page contents:

The following example reserves space for header and footer content that is not affected by the navigation system:

This last example demonstrates a simple approach to defining the page structure with an Errai UI template. The final product is identical to the above example, but in this case the overall page structure is declared in an HTML template rather than being defined programmatically in procedural logic:

This section contains information on configuring Errai.

Depending on what application server you are deploying on, you must provide an appropriate servlet implementation if you wish to use true, asynchronous I/O. See Section 12.6, “Servlet Implementations” for information on the available servlet implementations.

Here's a sample web.xml file:



<web-app 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-app_2_5.xsd"
  version="2.5">

  <servlet>
    <servlet-name>ErraiServlet</servlet-name>
    <servlet-class>org.jboss.errai.bus.server.servlet.DefaultBlockingServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>ErraiServlet</servlet-name>
    <url-pattern>*.erraiBus</url-pattern>
  </servlet-mapping>

  <context-param>
    <param-name>errai.properties</param-name>
    <param-value>/WEB-INF/errai.properties</param-value>
  </context-param>

  <context-param>
    <param-name>login.config</param-name>
    <param-value>/WEB-INF/login.config</param-value>
  </context-param>

  <context-param>
    <param-name>users.properties</param-name>
    <param-value>/WEB-INF/users.properties</param-value>
  </context-param>

</web-app>

ErraiApp.properties acts both as a marker file for JARs that contain Errai-enabled GWT modules, and as a place to put configuration settings for those modules in the rare case that non-default configuration is necessary.

ErraiApp.properties is usually left empty, but it can contain configuration settings for both the core of Errai and any of its extensions. Configuration properties defined and used by Errai components have keys that start with " errai. ". Third party extensions should each choose their own prefix for keys in ErraiApp.properties.

The ErraiService.properties file contains basic configuration for the bus itself. Unlike ErraiApp.properties, there should be at most one ErraiService.properties file on the classpath of a deployed application. If you do not need to set any properties to their non-default values, this file can be omitted from the deployment entirely.

  • errai.async_thread_pool_size specifies the total number of worker threads in the worker pool for handling and delivering messages. Adjusting this value does not have any effect if you are using the SimpleDispatcher.

  • errai.async.worker_timeout specifies the total amount of time (in seconds) that a service is given to finish processing an incoming message before the pool interrupts the thread and returns an error. Adjusting this value has no effect if you are using the SimpleDispatcher.

  • errai.bus.buffer_size The total size of the transmission buffer, in megabytes. If this attribute is specified along with errai.bus.buffer_segment_count , then the segment count is inferred by the calculation buffer_segment_count / buffer_size}. If {{errai.bus.buffer_segment_count is also defined, it will be ignored in the presence of this property. Default value: 32.

  • errai.bus.buffer_segment_size The transmission buffer segment size in bytes. This is the minimum amount of memory each message will consume while stored within the buffer. Defualt value: 8.

  • errai.bus.buffer_segment_count The number of segments in absolute terms. If this attribute is specified in the absence of errai.bus.buffer_size , the buffer size is inferred by the calculation buffer_segment_size / buffer_segment_count .

  • errai.bus.buffer_allocation_mode Buffer allocation mode. Allowed values are direct and heap . Direct allocation puts buffer memory outside of the JVM heap, while heap allocation uses buffer memory inside the Java heap. For most situations, heap allocation is preferable. However, if the application is data intensive and requires a substantially large buffer, it is preferable to use a direct buffer. From a throughput perspective, current JVM implementations pay about a 20% performance penalty for direct-allocated memory access. However, your application may show better scaling characteristics with direct buffers. Benchmarking under real load conditions is the only way to know the optimal setting for your use case and expected load. Default value: direct .

Errai has several different implementations for HTTP traffic to and from the bus. We provide a universally-compatible blocking implementation that provides fully synchronous communication to/from the server-side bus. Where this introduces scalability problems, we have implemented many webserver-specific implementations that take advantage of the various proprietary APIs to provide true asynchrony.

These included implementations are packaged at: org.jboss.errai.bus.server.servlet .

Errai includes a bus monitoring application, which allows you to monitor all of the message exchange activity on the bus in order to help track down any potential problems It allows you to inspect individual messages to examine their state and structure.

To utilize the bus monitor, you'll need to include the _errai-tools _ package as part of your application's dependencies. When you run your application in development mode, you will simply need to add the following JVM options to your run configuration in order to launch the monitor: -Derrai.tools.bus_monitor_attach=true


The monitor provides you a real-time perspective on what's going on inside the bus. The left side of the main screen lists the services that are currently available, and the right side is the service-explorer, which will show details about the service.

To see what's going on with a specific service, simply double-click on the service or highlight the service, then click "Monitor Service...". This will bring up the service activity monitor.


The service activity monitor will display a list of all the messages that were transmitted on the bus since the monitor became active. You do not need to actually have each specific monitor window open in order to actively monitor the bus activity. All activity on the bus is recorded.

The monitor allows you select individual messages, an view their individual parts. Clicking on a message part will bring up the object inspector, which will allow you to explore the state of any objects contained within the message, not unlike the object inspectors provided by debuggers in your favorite IDE. This can be a powerful tool for looking under the covers of your application.

This section explains the cause of and solution to some common problems that people encounter when building applications with Errai.

Of course, when lots of people trip over the same problem, it's probably because there is a deficiency in the framework! A FAQ list like this is just a band-aid solution. If you have suggestions for permanent fixes to these problems, please get in touch with us: file an issue in our issue tracker, chat with us on IRC, or post a suggestion on our forum.

But for now, on to the FAQ:

Possible symptoms:

Answer: Make sure the Section 12.3, “ErraiApp.properties” file is actually making it into your runtime classpath.

One common cause of this problem is a <resources> section in pom.xml that includes src/main/java (to expose .java sources to the GWT compiler) that does not also include src/main/resources as a resource path. You must include both explicitly:



<resources>
  <resource>
    <directory>src/main/java</directory>
  </resource>
  <resource>
    <directory>src/main/resources</directory>
  </resource>
</resources>

This chapter contains important information for migrating to newer versions of Errai. If you experience any problems, don't hesitate to get in touch with us. See Chapter 18, Reporting problems .

The first issues that will arise after replacing the jars or after changing the version numbers in the pom.xml are unresolved package imports. This is due to refactorings that became necessary when the project grew. Most of these import problems can be resolved automatically by modern IDEs (Organize Imports). So, this should replace org.jboss.errai.bus.client.protocols.* with org.jboss.errai.common.client.protocols.* for example.

The following is a list of manual steps that have to be carried out when upgrading:

  • The @Conversational annotation must now target the event objects themselves, not the observer methods of the events. So an event type is either conversational or not; you no longer specify that listeners receive arbitrary events in a conversational context. See the Conversational Events section of the CDI chapter for details.

  • The bootstrap listener (configured in WEB-INF/web.xml ) for Errai CDI has changed ( org.jboss.errai.container.DevModeCDIBootstrap is now org.jboss.errai.container.CDIServletStateListener ).

  • gwt 2.3.0 or newer must be used and replace older versions.

  • mvel2 2.1.Beta8 or newer must be used and replace older versions.

  • weld 1.1.5.Final or newer must be used and replace older versions.

  • slf4j 1.6.1 or newer must be used and replace older versions.

  • This step can be skipped if Maven is used to build the project. If the project is NOT built using Maven, the following jar files have to be added manually to project's build/class path: errai-common-2.x.jar, errai-marshalling-2.x.jar, errai-codegen-2.x.jar, netty-4.0.0.Alpha1.errai.r1.jar.

  • If the project was built using an early version of an Errai archetype the configuration of the maven-gwt-plugin has to be modified to contain the <hostedWebapp>path-to-your-standard-webapp-folder</hostedWebapp> . This is usually either war or src/main/webapp .

The distribution packages can be downloaded from jboss.org http://jboss.org/errai/Downloads.html

Errai is currently managed using Github. You can clone our repositories from http://github.com/errai .

If you run into trouble don't hesitate to get in touch with us:

Errai is distributed under the terms of the Apache License, Version 2.0. See the full Apache license text .

Revision History
Revision