Preface

1. Document Conventions

2. Feedback

Chapter 1. Introduction

1.1. What is it?

Errai is a GWT-based framework for building rich web applications using next-generation web technologies. Built on-top of ErraiBus, the framework provides a unified federation and RPC infrastructure with true, uniform, asynchronous messaging across the client and server.

1.2. Required software

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 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.

2.1. Messaging Overview

It's important to understand the concept of how messaging works in ErraiBus. Service endpoints are given string-based names that are referenced by message senders. There is no difference between sending a message to a client-based service, or sending a message to a server-based service. In fact, a service of the same name may co-exist on both the client and the server and both will receive all messages bound for that service name, whether they are sent from the client or from the server.

Services are lightweight in ErraiBus, and can be declared liberally and extensively within your application to provide a message-based infrastructure for your web application. It can be tempting to think of ErraiBus simply as a client-server communication platform, but there is a plethora of possibilities for using ErraiBus purely with the GWT client context, such as a way to advertise and expose components dynamically, to get around the lack of reflection in GWT.

In fact, ErraiBus was originally designed to run completely within the client but quickly evolved into having the capabilities it now has today. So keep that in mind when you run up against problems in the client space that could benefit from runtime federation.

2.2. Messaging API Basics

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's look at some use cases first.

2.2.1. Sending Messages with the Client Bus

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'.

publicclassHelloWorldimplementsEntryPoint{//Get an instance of the RequestDispatcherprivateRequestDispatcher dispatcher =ErraiBus.getDispatcher();publicvoid onModuleLoad(){Button button =newButton("Send message"); button.addClickHandler(newClickHandler(){publicvoid onClick(ClickEvent event){//Send a message to the 'HelloWorldService'.MessageBuilder.createMessage().toSubject("HelloWorldService")//(1).signalling()//(2).noErrorHandling()//(3).sendNowWith(dispatcher);//(4)});[...]}}}

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:

We specify the subject we wish to send a message to. In this case, "
HelloWorldService
".

We indicate that we wish to only signal the service, meaning, that we're not sending a qualifying command to the service. For information on this, read the section on
Protocols
.

We indicate that we do not want to provide an
ErrorCallback
to deal with errors for this message.

We transmit the message by providing an instance to the
RequestDispatcher

Important

An astute observer will note that access to the
RequestDispatcher
differs within client code and server code. Because the client code does not run within a container, access to the
RequestDispatcher
and
MessageBus
is statically accessed using the
ErraiBus.get()
and
ErraiBus.getDispatcher()
methods. The server-side code, conversely, runs inside a dependency container for managing components. See the section on Errai IOC and Errai CDI for using ErraiBus from a client-side container.

When using Errai IOC or CDI, you can also use the Sender<T> interface to send messages.

2.2.2. Receiving Messages on the Server Bus / Server Services

Every message has a sender and at least one receiver. A receiver is as it sounds--it receives the message and does something with it. Implementing a receiver (also referred to as a service) is as simple as implementing our standard MessageCallback interface, which is used pervasively across, both client and server code. Let's begin with server side component that receives messages:

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

We specify the subject we wish to send a message to. In this case, "
HelloWorldClient
". We are sending this message to all clients which are listening in on this subject. For information on how to communicate with a single client, see Section 2.6.

We indicate that we wish to only signal the service, meaning that we're not sending a qualifying command to the service. For information on this, read the section on Protocols.

We add a message part called "text" which contains the value "Hi there".

We indicate that we do not want to provide an
ErrorCallback
to deal with errors for this message.

We transmit the message by providing an instance of the
RequestDispatcher
.

2.2.4. Receiving Messages on the Client Bus/ Client Services

Messages can be received asynchronously and arbitriraily by declaring callback services within the client bus. As ErraiBus maintains an open COMET channel at all times, these messages are delivered in real time to the client as they are sent. This provides built-in push messaging for all client services.

publicclassHelloWorldimplementsEntryPoint{privateMessageBus bus =ErraiBus.get();publicvoid onModuleLoad(){[...]/* * Declare a service to receive messages on the subject * "BroadcastReceiver". */ bus.subscribe("BroadcastReceiver",newMessageCallback(){publicvoid callback(CommandMessage message){/* * When a message arrives, extract the "text" field and * do something with it */String messageText = message.get(String.class,"text");}});[...]}}

In the above example, we declare a new client service called
"BroadcastReceiver"
which can now accept both local messages and remote messages from the server bus. The service will be available in the client to receive messages as long the client bus is and the service is not explicitly de-registered.

2.2.5. Local Services

On the client or the server, you can create a local receiver which only receives messages that originated on the local bus. A local server-side service only receives messages that originate on that server, and a local client-side service only receives messages that originated on that client.

To create a local receiver using the declarative API, use the
@Local
annotation in conjunction with
@Service
:

2.3. Single-Response Conversations & Pseudo-Synchronous Messaging

It is possible to contruct a message and a default response handler as part of the
MessageBuilder
API. It should be noted, that multiple replies will not be possible and will result an exception if attempted. Using this aspect of the API is very useful for doing simple psuedo-synchronous conversive things.

You can do this by specifying a
MessageCallback
using the
repliesTo()
method in the
MessageBuilder
API after specifying the error handling of the message.

See the next section on how to build conversational services that can respond to such messages.

2.4. Sender Inferred Subjects

It is possible for the sender to infer, to whatever conversational service it is calling, what subject it would like the reply to go to. This is accomplished by utilizing the standard
MessageParts.ReplyTo
message part. Using this methodology for building conversations is generally encouraged.

In the above examples, assuming that the latter example is inside a service called "
ObjectService
" and is referencing the incoming message that was sent in the former example, the message created will automatically reference the
ReplyTo
subject that was provided by the sender, and send the message back to the subject desired by the client on the client that sent the message.

2.5. Broadcasting

Broadcasting messages to all clients listening on a specific subject is quite simple and involves nothing more than forgoing use of the reply API. For instance:

MessageBuilder.createMessage()..toSubject("MessageListener").with("Text","Hello, from your overlords in the cloud").noErrorHandling().sendGlobalWith(dispatcher);

If sent from the server, all clients currently connected, who are listening to the subject
"MessageListener"
will receive the message. It's as simple as that.

2.6. Client-to-Client Communication

Communication from one client to another client is not directly possible within the bus federation, by design. This isn't to say that it's not possible. But one client cannot see a service within the federation of another client. We institute this limitation as a matter of basic security. But many software engineers will likely find the prospects of such communication appealing, so this section will provide some basic pointers on how to go about accomplishing it.

2.6.1. Relay Services

The essential architectural thing you'll need to do is create a relay service that runs on the server. Since a service advertised on the server is visible to all clients and all clients are visible to the server, you might already see where we're going with this.

By creating a service on the server which accepts messages from clients, you can create a simple protocol on-top of the bus to enable quasi peer-to-peer communication. (We say quasi, because it still needs to be routed through the server)

While you can probably imagine simply creating a broadcast-like service which accepts a message from one client and broadcasts it to the rest of the world, it may be less clear how to go about routing from one particular client to another particular client, so we'll focus on that problem. This is covered in
Section 2.7, “Message Routing Information”

2.7. Message Routing Information

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:

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.

2.8. Handling Errors

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.

2.8.1. Handling global message transport errors

You may need to detect problems which occur on the bus at runtime. The client bus API provides a facility for doing this in the
org.jboss.errai.bus.client.framework.ClientMessageBus
using the
addTransportErrorHandler()
method.

A
TransportErrorHandler
is an interface which you can use to define error handling behavior in the event of a transport problem.

The
TransportError
interface represents the details of an an error from the bus. It contains a set of methods which can be used for determining information on the initial request which triggered the error, if the error occurred over HTTP or WebSockets, status code information, etc. See the JavaDoc for more information.

2.9. Asynchronous Message Tasks

In some applications, it may be necessary or desirable to delay transmission of, or continually stream data to a remote client or group of clients (or from a client to the server). In cases like this, you can utilize the
replyRepeating()
,
replyDelayed()
,
sendRepeating()
and
sendDelayed()
methods in the
MessageBuilder
.

Delayed TasksSending a task with a delay is straight forward. Simply utilize the appropriate method (either
replyDelayed()
or
sendDelayed()
).

2.10. Repeating Tasks

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

MessageBuilder.createMessage().toSubject("FunSubject").signalling().withProvided("time",newResourceProvider<String>(){SimpleDateFormat fmt =newSimpleDateFormat("hh:mm:ss");publicString get(){return fmt.format(newDate(System.currentTimeMillis());}}.noErrorHandling().sendRepeatingWith(requestDispatcher,TimeUnit.SECONDS,1);//sends a message every 1 second

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.

2.11. Queue Sessions

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.

2.11.1. Lifecycle

The lifescyle of a session is bound by the underlying HTTP session. It is also bound by activity thresholds. Clients are required to send heartbeat messages every once in a while to maintain their sessions with the server. If a heartbeat message is not received after a certain period of time, the session is terminated and any resources are deallocated.

2.11.2. Scopes

One of the things Errai offers is the concept of session and local scopes.

2.11.2.1. Session Scope

A session scope is scoped across all instances of the same session. When a session scope is used, any parameters stored will be accessible and visible by all browser instances and tabs.

The SessionContext helper class is used for accessing the session scope.

publicclassTestServiceimplementsMessageCallback{publicvoid callback(finalMessage message){// obtain a reference to the session context by referencing the incoming message.SessionContext injectionContext =SessionContext.get(message);// set an attribute. injectionContext.setAttribute("MyAttribute","Foo");}}

2.11.2.2. Local Scope

A local scope is scoped to a single browser instance. But not to a single session.

In a browser a local scope would be confined to a tab or a window within a browser. You can store parameters inside a local scope just like with a session by using the
LocalContext
helper class.

publicclassTestServiceimplementsMessageCallback{publicvoid callback(finalMessage message){// obtain a reference to the local context by referencing the incoming message.LocalContext injectionContext =LocalContext.get(message);// set an attribute. injectionContext.setAttribute("MyAttribute","Foo");}}

2.12. Client Logging and Error Handling

2.13. Wire Protocol (J.REP)

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.

2.13.1. Payload Structure

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

2.13.1.1. Built-in Subjects

The table contains a list of reserved subject names used for facilitating things like bus management and error handling. A bus should never allow clients to subscribe to these subjects directly.

Subject

Description

ClientBus

The self-hosted message bus endpoint on the client

ServerBus

The self-hosted message bus endpoint on the server

ClientBusErrors

The standard error receiving service for clients

As this table indicates, the bus management protocols in J.REP are accomplished using self-hosted services. See the section on
Bus Management and Handshaking Protocols
for details.

2.13.2. Message Routing

There is no real distinction in the J.REP protocol between communication with the server, versus communication with the client. In fact, it assumed from an architectural standpoint that there is no real distinction between a client and a server. Each bus participates in a flat-namespaced federation. Therefore, it is possible that a subject may be observed on both the server and the client.

One in-built assumption of a J.REP-compliant bus however, is that messages are routed within the auspices of session isolation. Consider the following diagram:

Figure 2.1. Figure 3 - Topology of a J.REP Messaging Federation

In
Figure 3
, is is possible for
Client A
to send messages to the subjects
ServiceA
and
ServiceB
. But it is not possible to address messages to
ServiceC
. Conversely,
Client B
can address messages to
ServiceC
and
ServiceB
, but not
ServiceA
.

2.13.3. Bus Management and Handshaking Protocols

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.

2.13.3.1. ServerBus and ClientBus commands

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:

Table 2.1. Message Parts for Bus Commands:

Command / Verb

Message Parts

Description

ConnectToQueue

N/A

The first message sent by a connecting client to begin the handshaking process.

CapabilitiesNotice

CapabilitiesFlags

A message sent by one bus to another to notify it of its capabilities during handshake (for instance long polling or websockets)

FinishStateSync

N/A

A message sent from one bus to another to indicate that it has now provided all necessary information to the counter-party bus to establish the federation. When both buses have sent this message to each other, the federation is considered active.

RemoteSubscribe

SubjectorSubjectsList

A message sent to the remote bus to notify it of a service or set of services which it is capable of routing to.

RemoteUnsubscribe

Subject

A message sent to the remote bus to notify it that a service is no longer available.

Disconnect

Reason

A message sent to a server bus from a client bus to indicate that it wishes to disconnect and defederate. Or, when sent from the client to server, indicates that the session has been terminated.

SessionExpired

N/A

A message sent to a client bus to indicate that its messages are no longer being routed because it no longer has an active session

Heartbeat

N/A

A message sent from one bus to another periodically to indicate it is still active.

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

2.14. Conversations

Conversations are message exchanges which are between a single client and a service. They are a fundmentally important concept in ErraiBus, since by default, a message will be broadcast to all client services listening on a particular channel.

When you create a reply with an incoming message, you ensure that the message you are sending back is received by the same client which sent the incoming message. A simple example:

@ServicepublicclassHelloWorldServiceimplementsMessageCallback{publicvoid callback(CommandMessage message){//Send a message to the 'HelloWorldClient' on the client that sent us the// the message.MessageBuilder.createConversation(message).toSubject("HelloWorldClient").signalling().with("text","Hi There! We're having a reply!").noErrorHandling().reply();});}}

Note that the only difference between the example in the previous section and this is the use of the
createConversation()
method with
MessageBuilder
.

2.15. WebSockets

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.

2.15.1. Configuring the sideband server

Activating the sideband server is as simple as adding the following to the
ErraiService.properties
file:

errai.bus.enable_web_socket_server=true

The default port for the sideband server is
8085
. You can change this by specifying a port with the
errai.bus.web_socket_port
property in the
ErraiService.properties
file.

2.15.2. Deploying with JBoss AS 7

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:

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:

Do not remove the regular ErraiBus servlet mappings!

When configuring ErraiBus to use WebSockets on JBoss AS, you
do not
remove the existing servlet mappings for the bus. The WebSocket servlet is in
addition to
your current bus servlet. This is because ErraiBus
always
negotiates WebSocket sessions over the COMET channel.

2.16. Bus Lifecycle

2.16.1. Turning Server Communication On and Off

By default, Errai's client-side message bus attempts to connect to the server as soon as the ErraiBus module has been loaded. The bus will stay connected until a lengthy (about 45 seconds) communication failure occurs, or the web page is unloaded.

The application can affect bus communication through two mechanisms:

By setting a global JavaScript variable
erraiBusRemoteCommunicationEnabled = false
before the GWT scripts load, bus communication with the server is permanently disabled

By calling
((ClientMessageBus) ErraiBus.get()).stop()
, the bus disconnects from the server

To resume server communication after a call to
ClientMessageBus.stop()
or after communication with the server has exceeded the bus' retry timeout, call
((ClientMessageBus) ErraiBus.get()).init()
. You can use a
BusLifecycleListener
to monitor the success or failure of this attempt. See the next section for details.

2.16.2. Observing Bus Lifecycle State and Communication Status

In a perfect world, the client message bus would always be able to communicate with the server message bus. But in the real world, there's a whole array of reasons why the communication link between the server and the client might be interrupted.

On its own, the client message bus will attempt to reconnect with the server whenever communication has been disrupted. Errai applications can monitor the status of the bus' communication link (whether it is disconnected, attempting to connect, or fully connected) through the
BusLifecycleListener
interface:

2.17. Shadow Services

Shadow Services is a Service that will get invoked when there is no longer a connection with the server. This is particular helpful when developing an application for mobile. To create a Shadow Service for a specific Services all you have to do is annotate a new client side implementation with the @ShadowService:

In this shadow service we can create logic that will deal with the temporary connection loss. For instance you could save the data that needs to get send to the server with JPA on the client and then when the bus get online again sent the data to the server.

2.18. Debugging Messaging Problems

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

Figure 2.2. TODO InformalFigure image title empty

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.

Figure 2.3. TODO InformalFigure image title empty

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.

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.

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:

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

@ApplicationScopedpublicclassTimeService{}

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.

3.1. Container Wiring

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:

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.

3.2. Wiring server side components

By default, Errai uses Google Guice to wire server-side components. When deploying services on the server-side, it is currently possible to obtain references to the
MessageBus
,
RequestDispatcher
, the
ErraiServiceConfigurator
, and
ErraiService
by declaring them as injection dependencies in Service classes, extension components, and session providers.

Alternatively, supports CDI based wiring of server-side components. See the chapter on Errai CDI for more information.

3.3. Scopes

Out of the box, the IOC container supports three bean scopes,
@Dependent
,
@Singleton
and
@EntryPoint
. The singleton and entry-point scopes are roughly the same semantics.

3.3.1. Dependent Scope

In Errai IOC, all client types are valid bean types if they are default constructable or can have construction dependencies satisfied. These unqualified beans belong to the dependent pseudo-scope. See:
Dependent Psuedo-Scope from CDI Documentation

Additionally, beans may be qualified as
@ApplicationScoped
,
@Singleton
or
@EntryPoint
. Although
@ApplicationScoped
and
@Singleton
are supported for completeness and conformance, within the client they effectively result in behavior that is identical.

Availability of dependent beans in the client-side BeanManager

As is mentioned in the
bean manager documentation
, only beans that are
explicitly
scoped will be made available to the bean manager for lookup. So while it is not necessary for regular injection, you must annotate your dependent scoped beans with
@Dependent
if you wish to dynamically lookup these beans at runtime.

3.4. Built-in Extensions

3.4.1. Bus Services

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.

3.4.1.1. @Service

The
org.jboss.errai.bus.server.annotations.Service
annotation is used for binding service endpoints to the bus. Within the Errai IOC container you can annotate services and have them published to the bus on the client (or on the server) in a very straight-forward manner:

As with server-side use of the annotation, if a service name is not explicitly specified, the underlying class name or field name being annotated will be used as the service name.

3.4.1.2. @Local

The
org.jboss.errai.bus.server.api.Local
annotation is used in conjunction with the
@Service
annotation to advertise a service only for visibility on the local bus and thus, cannot receive messages across the wire for the service.

3.4.1.3. Lifecycle Impact of Services

Services which are registered with ErraiBus via the bean manager through use of the
@Service
annotation, have de-registration hooks tied implicitly to the destruction of the bean. Thus,
destruction of the bean
implies that these associated services are to be dereferenced.

3.4.2. Client Components

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.

3.4.2.1. MessageBus

The type
org.jboss.errai.bus.client.framework.MessageBus
is globally injectable into any bean. Injecting this type will provide the instance of the active message bus running in the client.

Example 3.5. Injecting a MessageBus

@InjectMessageBus bus;

3.4.2.2. RequestDispatcher

The type
org.jboss.errai.bus.client.framework.RequestDispatcher
is globally injectable into any bean. Injecting this type will provide a
RequestDispatcher
instance capable of delivering any messages provided to it, to the the
MessageBus
.

Example 3.6. Injecting a RequestDispatcher

@InjectRequestDispatcher dispatcher;

3.4.2.3. Caller<?>

The type
org.jboss.errai.common.client.api.Caller<?>
is a globally injectable RPC proxy. RPC proxies may be provided by various components. For example, JAX-RS or Errai RPC. The proxy itself is agnostic to the underlying RPC mechanism and is qualified by it's type parameterization.

The above code shows the injection of a proxy for the RPC remote interface,
MyRpcInterface
. For more information on defining RPC proxies see
Chapter 6, Remote Procedure Calls (RPC)
and Creating Requests in Errai JAX-RS.

3.4.2.4. Sender<?>

The
org.jboss.errai.ioc.support.bus.client.Sender<?>
interface is the lower-level counterpart to the
Caller<?>
interface described above. You can inject a
Sender
to send low-level ErraiBus messages directly to subscribers on any subject.

The
Sender.send()
method is overloaded. The variant demonstrated above takes a value and a MessageCallback to reply receive a reply (assuming the subscriber sends a conversational reply). The following variants are available:

send(T)

send(T, ErrorCallback)

send(T, MessageCallback)

send(T, MessageCallback, ErrorCallback)

The reply-to service can also be specified declaratively using the
@ReplyTo
annotation. This allows the app to receive conversational replies even when using the
send()
variants that do not take a
MessageCallback
:

3.4.3. Lifecycle Tools

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.

3.4.3.1. Controlling Startup

In order to prevent initialization of the the bus and it's services so that you can do necessary configuration, especially if you are writing extensions to the Errai framework itself, you can create an implicit startup dependency on your bean by injecting an
org.jboss.errai.ioc.client.api.InitBallot<?>
.

3.4.3.2. Performing Tasks After Initialization

Sending RPC calls to the server from inside constructors and
@PostConstruct
methods in Errai is not always reliable due to the fact that the bus and RPC proxies initialize asynchronously with the rest of the application. Therefore it is often desirable to have such things happen in a post-initialization task, which is exposed in the
ClientMessageBus
API. However, it is much cleaner to use the
@AfterInitialization
annotation on one of your bean methods.

Example 3.9. Using @AfterInitialization to do something after startup

@SingletonpublicclassMyClientBean{ @AfterInitializationpublicvoid doStuffAfterInit(){//...do some work ...}}

3.4.4. Timed Methods

The
@Timed
annotation allows scheduling method executions on managed client-side beans. Timers are automatically scoped to the scope of the corresponding managed bean and participate in the same lifecycle (see
Section 3.7, “Bean Lifecycle”
for details).

In the following example the
updateTime
method is invoked repeatedly every second.

For delayed one-time execution of methods
type = TimerType.DELAYED
can be used instead.

3.5. Client-Side Bean Manager

It may be necessary at times to manually 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.ClientBeanManager
.

As you might expect, you can inject a bean manager instance into any of your managed beans. If you use Errai IOC in its default mode you will need to inject the synchronous bean manager (
org.jboss.errai.ioc.client.container.SyncBeanManager
).

If you have asynchronous IOC mode enabled simply inject the asynchronous bean manager (
org.jboss.errai.ioc.client.container.async.AsyncBeanManager
) instead. Asynchronous IOC brings support for
code splitting
. That means that any bean annotated with
@LoadAsync
can be compiled into a separate JavaScript file that's downloaded when the bean is first needed on the client.

Example 3.10. Injecting the client-side bean manager

publicMyManagedBean{ @InjectSyncBeanManager manager;//class body}

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()

3.5.1. Looking up beans

Looking up beans can be done through the use of the
lookupBeans()
method. Here's a basic example:

In this example we lookup a bean class named
SimpleBean
. This example will succeed assuming that
SimpleBean
is unambiguous. If the bean is ambiguous and requires qualification, you can do a qualified lookup like so:

In this example we manually construct instances of qualifier annotations in order to pass it to the bean manager for lookup. This is a necessary step since there's currently no support for annotation literals in Errai client code.

3.5.2. Availability of beans

Not all beans that are available for injection are available for lookup from the bean manager by default. Only beans which are
explicitly
scoped are available for dynamic lookup. This is an intentional feature to keep the size of the generated code down in the browser.

3.6. Alternatives and Mocks

3.6.1. Alternatives

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:

@Singleton @AlternativepublicclassMobileViewimplementsView{//...//}

and

@Singleton @AlternativepublicclassDesktopViewimplementsView{//...//

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

@EntryPointpublicclassMyApp{ @InjectView view;//...//}

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 only have one enabled alternative for a matching set of alternatives, otherwise you will get ambiguous resolution errors from the container.

3.6.2. Test Mocks

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.

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”
.

3.7. Bean Lifecycle

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.

Important

This cannot be guaranteed when the browser DOM is destroyed prematurely due to: closing the browser window; closing a tab; refreshing the page, etc.

3.7.1. Destruction of Beans

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.

Example 3.13. Destruction of bean

publicMyManagedBean{ @InjectSyncBeanManager manager;publicvoid createABeanThenDestroyIt(){// get a new bean.SimpleBean bean = manager.lookupBean(SimpleBean.class).getInstance(); bean.sendMessage("Sorry, I need to dispose of you now");// destroy the bean! manager.destroyBean(bean);}}

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:

publicMyManagedBean{ @InjectSyncBeanManager manager;publicvoid createABeanThenDestroyIt(){// get a new bean.SimpleBean bean = manager.lookupBean(SimpleBean.class).getInstance();// destroy the AnotherBean reference from inside the bean manager.destroyBean(bean.getAnotherBean());}}

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
@PreDestroycleanUp()
method of
SimpleBean
being invoked.

3.7.1.1. Disposers

Another way which beans can be destroyed is through the use of the injectable
org.jboss.errai.ioc.client.api.Disposer<T>
class. The class provides a straight forward way of disposing of bean type.

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.

4.1. Features and Limitations

Beans that are deployed to a CDI container will automatically be registered with Errai and exposed to your GWT client application. So, you can use Errai to communicate between your GWT client components and your CDI backend beans.

Errai CDI based applications use the same annotation-driven programming model as server-side CDI components, with some notable limitations. Many of these limitations will be addressed in future releases.

There is no support for CDI interceptors in the client. Although this is planned in a future release.

Passivating scopes are not supported.

The JSR-299 SPI is not supported for client side code. Although writing extensions for the client side container is possible via the Errai IOC Extensions API.

The
@Typed
annotation is unsupported.

The
@Interceptor
annotation is unsupported.

The
@Decorator
annotation is unsupported.

4.1.1. Other features

The CDI container in Errai is built around the
Errai IOC module
, and thus is a superset of the existing functionality in Errai IOC. Thus, all features and APIs documented in Errai IOC are accessible and usable with this Errai CDI programming model.

4.2. Events

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.

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:

As such, when
Document
events are fired, they will be limited in scope to the initiating conversational contents – which are implicitly inferred by the caller. So only the client which fired the
Subscription
event will receive the fired
Document
event.

4.2.2. Client-Server Event Example

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.

4.3. Producers

Producer methods and fields act as sources of objects to be injected. They are useful when additional control over object creation is needed before injections can take place e.g. when you need to make a decision at runtime before an object can be created and injected.

Producers can also be scoped themselves. By default, producer methods are dependent-scoped, meaning they get called every time an injection for their provided type is requested. If a producer method is scoped
@Singleton
for instance, the method will only be called once, and the bean manager will inject the instance from the first invokation of the producer into every matching injection point.

In this example, calling
barInstance.get()
returns a new instance of the dependent-scoped bean
Bar
.

4.5. Deploying Errai CDI

If you do not care about the deployment details for now and just want to get started take a look at the ERRAI: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.

4.5.1. Deployment in Development Mode

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:

Starting Development Mode from within your IDE

Consequently, when starting Development Mode from within your IDE the following program argument has to be provided: -server org.jboss.errai.cdi.server.gwt.JettyLauncher

4.5.1.1. Special-case Classloading

JettyLauncher uses different class loaders to load classes that belongs to the web application, the Jetty server, and the Java standard library itself. In the majority of cases, you can simply put all dependencies into your web application's
WEB-INF/lib
folder. However, there are cases where putting a dependency in
WEB-INF/lib
will cause troubles such as
ClassCastException
when same class is also loaded by a different classloader. To mitigate this problem, JettyLauncher can be instructed that certain classes (or packages) shall be loaded only by the system class loader. To do so, set the Java system property
jetty.custom.sys.classes
when launching Dev Mode.

4.5.2. Deployment to a Servlet Engine

Deployment to servlet engine has basically the same requirements as running in development mode. You need to include the servlet listener that bootstraps the CDI container and make sure both Errai and CDI are accessible through JNDI. For Jetty you can re-use the artefacts we ship with the archetype. In case you want to run on tomcat, please consult the
Apache Tomcat Documentation
.

4.5.3. Deployment to an Application Server

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
).

Chapter 5. Marshalling

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.

5.1. Mapping Your Domain

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.

5.1.1. @Portable and @NonPortable

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:

If an entity type has a field called
foo
, then that entity has a property called
foo
unless the field is marked
static
or
transient
.

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:

If the entity has a public constructor where every argument is annotated with
@MapsTo
, and those parameters cover all properties of the entity type, then Errai uses this constructor to create the object, passing in all of the property values.

Otherwise, if the entity has a public static method where every argument is annotated with
@MapsTo
, and those parameters cover all properties of the entity type, then Errai uses this method to create the object. Note that when using this mechanism you are free to create and return a subtype of the marshalled type, or resolve one from a cache.

If the entity has a public no-arguments constructor (or no explicit constructors at all), it will be created via that constructor, and the properties will be written to the new object one at a time. Each property will be written by its setter method, or by direct field access if a setter method is not available.

This is a pretty vanilla domain object. Note the default, public, no-argument constructor. In this case, it will be necessary to have one explicitly declared. But notice we have no setters. In this case, the marshaler will rely on private field access to write the values on each side of the marshalling transaction. For simple domain objects, this is both nice and convenient. But you may want to make the class immutable and have a constructor enforce invariance. See the next section for that.

5.1.1.2. Example: An Immutable Entity with a Public Constructor

Immutability is almost always a good practice, and the marshalling system provides you a straight forward way to tell it how to marshal and de-marshal objects which enforce an immutable contract. Let's modify our example from the previous section.

Here we have set both of the class fields final. By doing so, we had to remove our default constructor. But that's okay, because we have annotated the remaining constructor's parameters using the
org.jboss.errai.marshalling.client.api.annotations.MapsTo
annotation.

By doing this, we have told the marshaling system, for instance, that the first parameter of the constructor maps to the property
name
. Which in this case, defaults to the name of the corresponding field. This may not always be the case – as will be explored in the section on custom definitions. But for now that's a safe assumption.

5.1.1.3. Example: An Immutable Entity with a Factory Method

Another good practice is to use a factory pattern to enforce invariance. Once again, let's modify our example.

Here we have made our only declared constructor private, and created a static factory method. Notice that we've simply used the same
@MapsTo
annotation in the same way we did on the constructor from our previous example. The marshaller will see this method and know that it should use it to construct the object.

5.1.1.4. Example: An Immutable Entity with a Builder

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
.

5.1.2. Manual Mapping

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.

5.1.2.1. Mapping Existing Client Classes

If you have client-exposed classes that cannot be annotated with the
@Portable
annotation, you may manually map these classes so that the marshaller framework will comprehend and produce marshallers for them and their nested types.

To do this, specify them in
ErraiApp.properties
, using the
errai.marshalling.serializableTypes
attribute with a whitespace separated list of classes to make portable.

5.1.2.2. Aliased Mappings of Existing Interface Contracts

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>
.

Aliases do not inherit functionality!

When you alias a class to another marshalling contract, extended functionality of the aliased class will not be available upon deserialization. For this you must provide custom marshallers for those classes.

5.1.3. Manual Class Mapping

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.

5.1.3.1. MappingDefinition

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.

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:

Call the constructor in
MappingDefinition
passing our reference to the class we are mapping.

Using the
SimpleConstructorMapping
class, we have indicated that a custom constructor will be needed to instantiate this class. We have called the
mapParmToIndex
method with three parameters. The first,
"mySupername"
describes the class field that we are targeting. The second parameter, the integer
0
indicates the parameter index of the constructor arguments that we'll be providing the value for the aforementioned field – in this case the first and only, and the final parameter
String.class
tells the marshalling framework which marshalling contract to use in order to de-marshall the value.

Using the
WriteMapping
class, we have indicated to the marshaller framework how to write the
"mySuperNickname"
field, using the
String.class
marshaller, and using the setter method
setMySuperNickname
.

Using the
ReadMapping
class, we have indicated to the marshaller framework how to read the
"mySuperName"
field, using the
String.class
marshaller, and using the getter method
getMySuperName
.

Using the
ReadMapping
class, we have indicated to the marshaller framework how to read the
"mySuperNickname"
field, using the
String.class
marshaller, and using the getter method
getMySuperNickname
.

5.1.4. Custom Marshallers

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:

Chapter 6. Remote Procedure Calls (RPC)

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:

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:

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.

Warning

Beginning with Errai 2.0.CR1, the default for automatic service discovery has changed in favour of CDI based applications, meaning RPC service discovery must be explicitly turned on in case Errai CDI is not used (the
weld-integration.jar
is not on the classpath). This can be done using an init-param in the servlet config of your web.xml:

6.1. Making calls

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.

6.1.1. Proxy Injection

An alternative to using the
MessageBuilder
API is to have a proxy of the service injected.

@InjectprivateCaller<MyRemoteService> remoteService;

For calling the remote service, the callback objects need to be provided to the
call
method before the corresponding interface method is invoked.

remoteService.call(callback).isEveryoneHappy();

The Errai IOC GWT module needs to be inherited to make use of caller injection. To do this, the following line needs to be added to the application's
*.gwt.xml
file. It is important that this line comes
after
the Errai Bus module:

<inheritsname="org.jboss.errai.ioc.Container"/>

6.2. Handling exceptions

Handling remote exceptions can be done by providing an
ErrorCallback
on the client:

As remote exceptions need to be serialized to be sent to the client, the
@Portable
annotation needs to be present on the corresponding exception class (see
Chapter 5, Marshalling
). Further the exception class needs to be part of the client-side code. For more details on
ErrorCallbacks
see
Section 2.8, “Handling Errors”
.

6.3. Client-side Interceptors

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.

publicclassMyCacheInterceptorimplementsRpcInterceptor{ @Overridepublicvoid aroundInvoke(finalRemoteCallContext context){// e.g check if the result is cached and carry out the actual call only in case it's not. context.proceed()// executes the next interceptor in the chain or the actual remote call.// context.setResult()// sets the result directly without carrying out the remote call.}}

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.

6.4. Session and request objects in RPC endpoints

Before invoking an endpoint method Errai sets up an
RpcContext
that provides access to message resources that are otherwise not visible to RPC endpoints.

6.5. Batching remote calls

Some use cases require multiple interactions with the server to complete. Errai's RPC mechanism allows for batched invocations of remote methods that will be executed using a single server round-trip. This is useful for reducing the number of simultaneous HTTP connections and at the same time allows for reusing and combining fine-grained remote services.

Injecting a BatchCaller instead of a Caller<T> is all it takes to make use of batched remote procedure calls.

The remote methods will get executed only after
sendBatch()
was called. The method
sendBatch
accepts an additional
RemoteCallback
instance as a parameter which will we invoked when all remote calls have completed in success. Consequently, an
ErrorCallback
can also be provided which will get executed for all remote calls that have completed in failure.

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:

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 interfaces visible within the GWT module

Errai IoC and CDI providers that allow you to
@Inject
instances of {{Caller<T>} (the same API used in Errai RPC)}

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

To get started with a working demo that makes use of Errai JAX-RS you can either download and unzip the
Errai tutorial project
or check out the CRUD demo part of our
demo collection
. If you prefer getting started from scratch keep reading

Figure 7.1. TODO Gliffy image title empty

.

7.1. Getting Started

7.1.1. Dependencies

To use Errai JAX-RS, you must include it on the compile-time classpath. If you are using Maven for your build, add this dependency:

or manually add
errai-jaxrs-provider-version.jar
in case you're not using Maven. If your REST service returns Jackson generated JSON you do not need the errai-jaxrs-provider (see
Configuration
) .

7.1.2. GWT Module

Once you have Errai JAX-RS on your classpath, ensure your application inherits the GWT module as well. Add this line to your application's
*.gwt.xml
file:

<inheritsname="org.jboss.errai.enterprise.Jaxrs"/>

7.1.3. Server-Side JAX-RS Implementation

Errai's JAX-RS support consists mostly of features that make the client side easier and more reliable to maintain. You will need to use an existing third-party JAX-RS implementation on the server side. All Java EE 6 application servers include such a module out-of-the-box. If you are developing an application that you intend to deploy on a plain servlet container, you will have to choose a JAX-RS implementation (for example, RestEasy) and configure it properly in your web.xml.

Alternatively, you could keep your REST resource layer in a completely separate web application hosted on the same server (perhaps build an Errai JAX-RS client against an existing REST service you developed previously). In this case, you could factor out the shared JAX-RS interface into a shared library, leaving the implementation in the non-Errai application.

Finally, you can take advantage of the cross-origin resource sharing (CoRS) feature in modern browsers and use Errai JAX-RS to send requests to a third-party server. The third-party server would have to be configured to allow cross-domain requests. In this case, you would write a JAX-RS-Annotated interface describing the remote REST resources, but you would not create an implementation of that interface.

7.1.4. Shared JAX-RS Interface

Errai JAX-RS works by leveraging standard Java interfaces that bear JAX-RS annotations. You will also want these interfaces visible to server-side code so that your JAX-RS resource classes can implement them (and inherit the annotations). 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 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.

7.2. Creating Requests

This section assumes you have already set up the CustomerService JAX-RS endpoint as described in the previous section.

To create a request on the client, all that needs to be done is to invoke
RestClient.create()
, thereby providing the JAX-RS interface, a response callback and to invoke the corresponding interface method:

7.2.1. Proxy Injection

Injectable proxies can be used as an alternative to calling
RestClient.create()
.

@InjectprivateCaller<CustomerService> customerService;

To create a request, the callback objects need to be provided to the
call
method before the corresponding interface method is invoked.

customerService.call(callback).listAllCustomers();

To use caller injection, your application needs to inherit the Errai IOC GWT module. To do this, just add this line to your application's
*.gwt.xml
file and make sure it comes
after
the Errai JAX-RS module (see
Getting Started
):

<inheritsname="org.jboss.errai.ioc.Container"/>

Note

The JAX-RS interfaces need to be visible to the GWT compiler and must therefore reside within the client packages (e.g. client.shared).

7.3. Handling Responses

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
).

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 and the status code. The
ResponseCallback
can also be used for JAX-RS interface methods that return a
javax.ws.rs.core.Response
type. In this case, the
MarshallingWrapper
class can be used to manually demarshall the response body to an entity of the desired type.

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.

7.4. Client-side Interceptors

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:

avoiding the request when the data is cached locally

adding special HTTP headers or parameters to the request

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.

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.

7.5. Wire Format

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.

7.6. Configuration

7.6.1. Configuring the default root path of JAX-RS endpoints

All paths specified using the
@Path
annotation on JAX-RS interfaces are by definition relative paths. Therefore, by default, it is assumed that the JAX-RS endpoints can be found at the specified paths relative to the GWT client application's context path.

To configure a relative or absolute root path, the following JavaScript variable can be set in either

The root path will be prepended to all paths specified on the JAX-RS interfaces. It serves as the base URL for all requests sent from the client.

7.6.2. Enabling Jackson marshalling

The following options are available for activating Jackson marshalling on the client. Note that this is a client-side configuration, the JAX-RS endpoint is assumed to already return a Jackson representation (Jackson is supported by all JAX-RS implementations). The
errai-jaxrs-provider.jar
does not have to be deployed on the server in this case!

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.

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.

8.1. Getting Started

8.1.1. Compile-time dependency

To use Errai JPA, you must include it on the compile-time classpath. If you are using Maven for your build, add this dependency:

If you are not using Maven for dependency management, add
errai-jpa-client-version.jar
, Hibernate 4.1.1, and Google Guava for GWT 12.0 to your compile-time classpath.

8.1.2. GWT Module Descriptor

Once you have Errai JPA on your classpath, ensure your application inherits the GWT module as well. Add this line to your application's
*.gwt.xml
file:

<inheritsname="org.jboss.errai.jpa.JPA"/>

8.1.3. INF/persistence.xml

Errai ignores META-INF/persistence.xml for purposes of client-side JPA. Instead, Errai scans all Java packages that are part of your GWT modules for classes annotated with
@Entity
. This allows you the freedom of defining a persistence.xml that includes both shared entity classes that you use on the client and the server, plus server-only entities that are defined in a server-only package.

8.1.4. Declaring an Entity Class

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:

The class must have an ID attribute

The class must have a public or protected constructor that takes no arguments

The class must be public and nonfinal

No methods or persistent fields of the class may be final

The class must be a top-level type (not a nested or inner class)

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

8.1.4.1. Entity Attributes

The state of fields and JavaBeans properties of entities are generally persisted with the entity instance. These persistent things are called
attributes
.

JPA Attributes are subdivided into two main types:
singular
and
plural
. Singular attributes are scalar types like
Integer
or
String
. Plural attributes are collection values, such as
List<Integer>
or
Set<String>
.

The values of singular attributes (and the elements of plural attributes) can be of any application-defined entity type or a JPA Basic type. The JPA basic types are all of the Java primitive types, all boxed primitives, enums, BigInteger, BigDecimal, String, Date (
java.util.Date
or
java.sql.Date
), Time, and Timestamp.

You can direct JPA to read and write your entity's attributes by direct field access or via JavaBeans property access methods (that is, "getters and setters"). Direct field access is the default. To request property access, annotate the class with
@Access(AccessType.PROPERTY)
. If using direct field access, attribute-specific JPA annotations should be on the fields themselves; when using property access, the attribute-specific annotations should be on the getter method for that property.

8.1.4.2. ID Attributes and Auto-Generated Identifiers

Each entity class must have exactly one ID attribute. The value of this attribute together with the fully-qualified class name uniquely identifies an instance to the entity manager.

ID values can be assigned by the application, or they can be generated by the JPA entity manager. To declare a generated identifier, annotate the field with
@GeneratedValue
. To declare an application-assigned identifier, leave off the
@GeneratedValue
annotation.

Generated identifier fields must not be initialized or modified by application code. Application-assigned identifier fields must be initialized to a unique value before the entity is persisted by the entity manager, but must not be modified afterward.

8.1.4.3. Single-valued Attributes

By default, every field of a JPA basic type is a persistent attribute. If a basic type field should not be presistent, mark it with
transient
or annotate it with
@Transient
.

Single-valued attributes of entity types must be annotated with
@OneToOne
or
@ManyToOne
.

Single-valued types that are neither entity types nor JPA Basic types are not presently supported by Errai JPA. Such attributes must be marked transient.

Here is an example of an entity with single-valued basic attributes and a single-valued relation to another entity type:

8.1.4.4. Plural (collection-valued) Attributes

Collection-valued types
Collection<T>
,
Set<T>
, and
List<T>
are supported. JPA rules require that all access to the collections are done through the collection interface method; never by specific methods on an implementation.

The element type of a collection attribute can be a JPA basic type or an entity type. If it is an entity type, the attribute must be annotated with
@OneToMany
or
@ManyToMany
.

8.1.5. Entity Lifecycle States

8.1.5.1. Cascade Rules

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
.

8.1.6. Obtaining an instance of EntityManager

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:

@EntryPointpublicclassMain{ @InjectEntityManager em;}

8.1.6.1. Storing and Updating Entities

To store an entity object in persistent storage, pass that object to the
EntityManager.persist()
method. Once this is done, the entity instance transitions from the
new
state to the
managed
state.

If the entity references any related entities, these entities must be in the managed state already, or have cascade-on-persist enabled. If neither of these criteria are met, an
IllegalStateException
will be thrown.

See an example in the following section.

8.1.6.2. Fetching Entities by ID

If you know the unique ID of an entity object, you can use the
EntityManager.find()
method to retrieve it from persistent storage. The object returned from the
find()
method will be in the managed state.

8.1.6.4. Detaching Entity Instances from the Entity Manager

For every entity instance in the managed state, changes to the attribute values of that entity are persisted to local storage whenever the entity manager is flushed. To prevent this automatic updating from happening, you can
detach
an entity from the entity manager. When an instance is detached, it is not deleted. All information about it remains in persistent storage. The next time that entity is retrieved, the entity manager will create a new and separate managed instance for it.

To detach one particular object along with all related objects whose cascade rules say so, call
EntityManager.detach()
and pass in that object.

To detach all objects from the entity manager at once, call
EntityManager.detachAll()
.

8.1.6.5. Testing if an Entity is in the Managed State

To check if a given object is presently managed by the entity manager, call
EntityManager.contains()
and pass in the object of interest.

8.1.7. Named Queries

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.

8.1.7.1. Declaring Named Queries

Queries in JPA are written in the JPQL language. As of Errai 2.1, Errai JPA does not support all JPQL features. Most importantly, implicit and explicit joins in queries are not yet supported. Queries of the following form generally work:

SELECT et FROM EntityType et WHERE [expression with constants, named parameters and attributes of et] ORDER BY et.attr1 [ASC|DESC], et.attr2 [ASC|DESC]

Here is how to declare a JPQL query on an entity:

@NamedQuery(name="selectAlbumByName", query="SELECT a FROM Album a WHERE a.name=:name")@EntitypublicclassAlbum{... same as before ...}

To declare more than one query on the same entity, wrap the
@NamedQuery
annotations in
@NamedQueries
like this:

@NamedQueries({ @NamedQuery(name="selectAlbumByName", query="SELECT a FROM Album a WHERE a.name = :name"), @NamedQuery(name="selectAlbumsAfter", query="SELECT a FROM Album a WHERE a.releaseDate >= :startDate")})@EntitypublicclassAlbum{... same as before ...}

8.1.7.2. Executing Named Queries

To execute a named query, retrieve it by name and result type from the entity manager, set the values of its parameters (if any), and then call one of the execution methods
getSingleResult()
or
getResultList()
.

8.1.8. Entity Lifecycle Events

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:

@EntitypublicclassAlbum{... same as before ... @PostLoadpublicvoid postLoad(){System.out.println("Album "+ getName()+" was just loaded into the entity manager");}}

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:

@Entity@EntityListeners(StandaloneLifecycleListener.class)publicclassAlbum{... same as always ...}publicclassStandaloneLifecycleListener{ @PostLoadpublicvoid albumLoaded(Album a){publicvoid postLoad(){System.out.println("Album "+ a.getName()+" was just loaded into the entity manager");}}

8.1.9. JPA Metamodel

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.

8.1.9.1. Errai Extensions to JPA Metamodel API

Wherever you obtain an instance of
SingularAttribute
from the metamodel API, you can down-cast it to
ErraiSingularAttribute
. Likewise, you can down-cast any
PluralAttribute
to
ErraiPluralAttribute
.

In either case, you can read the value of an arbitrary attribute by calling
ErraiAttribute.get()
and passing in the entity instance. You can set any attribute's value by calling
ErraiAttribute.set()
, passing in the entity instance and the new value.

In addition to
get()
and
set()
,
ErraiPluralAttribute
also has the
createEmptyCollection()
method, which creates an empty collection of the correct interface type for the given attribute.

8.1.10. JPA Features Not Implemented in Errai 2.1

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

Polymorphic relations (eg. relationship to a collection of a base entity type)

EntityManager.merge()

EntityManager.refresh()
to pick up changes made in localStorage from a different browser window/tab.

Criteria Queries

The generated static Metamodel

The
@PersistenceContext
annotation currently has no effect in client-side code (use
@Inject
instead)

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

EntityManager.createQuery(String, ...)
(that is, unnamed queries) are impractical because JPQL queries are parsed at compile time, not in the browser.

EntityManager.createNativeQuery(String, ...)
don't make sense because the underlying database is just a hash table. It does not have a query language.

Persistent attributes of type
java.util.Calendar
because the
Calendar
class is not in GWT's JRE emulation library.

8.1.11. Other Caveats for Errai 2.1 JPA

We hope to remedy these shortcomings in a future release.

In Dev Mode, changes to entity classes are not discovered on page refresh. You need to restart Dev Mode.

The local data stored in the browser is not encrypted

8.2. Errai JPA Data Sync

Traditional JPA implementations allow you to store and retrieve entity objects on the server side. Errai's JPA implementation allows you to store and retrieve entity objects in the web browser using the same APIs. All that's missing is the ability to synchronize the stored data between the server side and the client side.

This is where Errai JPA Data Sync comes in: it provides an easy mechanism for two-way synchronization of data sets between the client and the server.

8.2.1. How To Use It

8.2.1.1. Dependencies

First, ensure your
pom.xml
includes a dependency on the Data Sync module. This module must be packaged in your application's WAR file, so include it with the default scope (compile):

To summarize: there are three entity types:
User
,
GroceryList
, and
Item
. Each
GroceryList
belongs to a
User
and has a list of
Item
objects.

Note

All the entities involved in the data synchronization request must be marshallable via Errai Marshalling. This is normally accomplished by adding the
@Portable
annotation to each JPA entity class, but it is also acceptable to list them in
ErraiApp.properties
. See the
Chapter 5, Marshalling
section for more details.

Now let's say we want to synchronize the data for all of a user's grocery lists. This will make them available for offline use through Errai JPA, and at the same time it will update the server with the latest changes made on the client. Ultimately, the sync operation is accomplished in one asynchronous call, but first we have to prepare a few things on the client and the server.

Important

The
onCompletion
and
onError
callbacks are optional. In the unlikely case that your application doesn't care if a data sync request completed successfully, you can pass
null
for either callback.

Once your
onCompletion
callback has been notified, the server and client will have the same entities stored in their respective databases for all entities reachable from the given query result.

8.2.1.4. Server Side – DataSyncServiceImpl

During the
coldSync()
call, the client-side sync manager sends an
Errai RPC
request to the server. Although a server-side implementation of the remote interface is provided, you are responsible for implementing a thin wrapper around it. This wrapper serves two purposes:

It allows you to determine how to obtain a reference to the JPA EntityManager (and to choose which persistence context the server-side data sync will operate on)

It allows you to inspect the contents of each sync request and make security decisions about access to particular entities

If you are deploying to a container that supports CDI and EJB 3, you can use this DataSyncServiceImpl as a template for your own:

If you are not using EJB 3, you will not be able to use the
@PersistenceContext
annotation. In this case, obtain a reference to your EntityManager the same way you would anywhere else in your application.

8.2.1.5. Dealing With Conflicts

When the client sends the sync request to the server, it includes information about the state it expects each entity to be in. If an entity's state on the server does not match this expected state on the client, the server ignores the client's change request and includes a
ConflictResponse
object in the sync reply.

When the client processes the sync responses from the server, it applies the new state from the server to the local data store. This overwrites the change that was initially requested from the client. In short, you could call this the "server wins" conflict resolution policy.

In some cases, your application may be able to do something smarter: apply domain-specific knowledge to merge the conflict automatically, or prompt the user to perform a manual merge. In order to do this, you will have to examine the server response from inside the
onCompletion
callback you provided to the
coldSync()
method:

Remember, because of Errai's default "server wins" resolution policy, the call to
em.find(GroceryList.class, cr.getActualNew().getId())
will return a GroceryList object that has already been updated to match the state present in
serverItems
.

Note

Searching for ConflictResponse objects in the
onCompletion
callback is the only way to recover client data that was clobbered in a conflict. If you do not merge this data back into local storage, or at least retain a reference to the
cr.getRequestedNew()
object, this conflicting client data will be lost forever.

In a future release of Errai JPA, we plan to provide a client-side callback mechanism for custom conflict handling. If such a callback is registered, it will override the default behaviour.

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.

Important

If you cannot or prefer not to annotate your classes with
@Bindable
, you can alternatively specify bindable types in your ErraiApp.properties using a whitespace-separated list of fully qualified class names:
errai.ui.bindableTypes=org.example.Model1 org.example.Model2

9.1.4. Initializing a DataBinder

An instance of
DataBinder
is required to create bindings. It can either be

In case there is existing state in either the model object or the UI components before the they are bound, initial state synchronization can be carried out to align the model and the corresponding UI fields.

For using the model object's state to set the initial values in the UI:

9.2. Creating Bindings

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
.

Note

It's important to retrieve the model instance using dataBinder.getModel() before making changes to it as the data binder will provide a proxy to the model to ensure that changes will update the corresponding UI components.

Tip

Errai also provides a
declarative binding API
that can be used to create bindings automatically based on matching field and model property names.

9.3. Specifying Converters

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.

All converters annotated with
@DefaultConverter
will be registered as global defaults calling
Convert.registerDefaultConverter()
. Note that the
Converter
interface specifies two type parameters. The first one represents the type of the model field, the second one the type held by the widget (e.g.
String
for widgets implementing
HasValue<String>
). These default converters will be used for all bindings with matching model and widget types.

9.3.2. Providing a binding-specific converter

Alternatively, converter instances can be passed to the
dataBinder.bind()
calls.

dataBinder.bind(textBox,"name", customConverter);

Converters specified on the binding level take precedence over global default converters with matching types.

9.4. Property Change Handlers

In some cases keeping the model and the UI in sync is not enough. Errai's
DataBinder
allows for the registration of
PropertyChangeHandlers
for specific properties, property expressions or all properties of a bound model. A property expression can be a property chain such as customer.address.street. It can end in a wildcard to indicate that changes of any property of the corresponding bean should be observed (e.g
"customer.address.*"
). A double wildcard can be used at the end of a property expression to register a cascading change handler for any nested property (e.g
"customer.**"
).

This provides a uniform notification mechanism for model and UI value changes.
PropertyChangeHandlers
can be used to carry out any additional logic that might be necessary after a model or UI value has changed.

9.5. Declarative Binding

Programmatic binding as described above (see
Creating Bindings
) can be tedious when working with UI components that contain a large number of input fields. Errai provides an annotation-driven binding API that can be used to create bindings automatically which cuts a lot of boilerplate code. The declarative API will work in any
Errai IOC
managed bean (including
Chapter 10, Errai UI
templates). Simply inject a data binder or model object and declare the bindings using
@Bound
.

Here is a simple example using an injected model object provided by the
@Model
annotation (field injection is used here, but constructor and method injection are supported as well):

Here is the same example injecting a
DataBinder
instead of the model object. This is useful when more control is needed (e.g. the ability to register property change handlers). The
@AutoBound
annotation specifies that this
DataBinder
should be used to bind the model to all enclosing widgets annotated with
@Bound
. This example uses field injection again but constructor and method injection are supported as well.

In both examples above an instance of the
Customer
model is automatically bound to the corresponding UI widgets based on matching field names. The model object and the UI fields will automatically be kept in sync. The widgets are inferred from all enclosing fields and methods annotated with
@Bound
of the class that defines the
@AutoBound DataBinder
or
@Model
and all its super classes.

9.5.1. Default, Simple, and Chained Property Bindings

By default, bindings are determined by matching field names to property names on the model object. In the examples above, the field
name
was automatically bound to the JavaBeans property
name
of the model (
user
object). If the field 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.

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.

9.5.2. Data Converters

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:

9.5.3. Replacing a model object

The injected model objects in the examples above are always proxies to the actual model since method invocations on these objects need to trigger additional logic for updating the UI. Special care needs to be taken in case a model object should be replaced.

When working with an
@AutoBound DataBinder
, simply calling
setModel()
on the
DataBinder
will be enough to replace the underlying model instance. However, when working with
@Model
the instance cannot be replaced directly. Errai provides a special method level annotation
@ModelSetter
that will allow replacing the model instance. Here's an example:

The
@ModelSetter
method is required to have a single parameter. The parameter type needs to correspond to the type of the managed model.

9.6. Bean validation

Java bean validation (JSR 303) provides a declarative programming model for validating entities. More details and examples can be found
here
. Errai provides a bean validation module that makes
Validator
instances injectable and work well with Errai's data binding module. The following line needs to be added to the GWT module descriptor to inherit Errai's bean validation module:

To use Errai's bean validation module, you must add the module, the javax.validation API and an implementation such as hibernate validator to your classpath. If you are using Maven for your build, add these dependencies:

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.

10.1. Get started

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:

10.1.1. App.gwt.xml

<inheritsname="org.jboss.errai.ui.UI"/>

10.1.2. pom.xml

The easiest way to get Errai UI on your classpath is to depend on the special
errai-javaee-all
artifact, which brings in most Errai modules:

10.1.3. Working Demo

10.2. Use Errai UI Composite components

Before explaining how to create Errai UI components, it should be noted that these components behave no differently from any other GWT Widget once built. The primary difference is in A) their construction, and B) their instantiation. As with most other features of Errai, dependency injection with CDI is the programming model of choice, so when interacting with components defined using Errai UI, you should always
@Inject
references to your Composite components.

10.3.1. Basic component

10.3.2. Custom template names

With default values, @Templated informs Errai UI to look in the current package for a parallel
".html"
template next to the Composite component Class; however, the template name may be overridden by passing a String into the @Templated annotation, like so:

10.4. Create an HTML template

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.

<form><legend>Log in to your account</legend><labelfor="username">Username</label><inputid="username"type="text"placeholder="Username"><labelfor="password">Password</label><inputid="password"type="password"placeholder="Password"><button>Log in</button><button>Cancel</button></form>

10.4.1. Select a template from a larger HTML file

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.

@Templated("my-template.html#login-form")publicclassLoginFormextendsComposite{/* Specifies that <... data-field="login-form"> be used as the root Element of this Widget */}

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.)

<!DOCTYPEhtml><htmllang="en"><head><title>A full HTML snippit</title></head><body><div><formdata-field="login-form"><legend>Log in to your account</legend><labelfor="username">Username</label><inputid="username"type="text"placeholder="Username"><labelfor="username">Password</label><inputid="password"type="password"placeholder="Password"><button>Log in</button><button>Cancel</button></form></div><hr><footerdata-field="theme-footer"><p>(c) Company 2012</p></footer></body></html>

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.

@Templated("my-template.html#theme-footer")publicclassFooterextendsComposite{/* Specifies that <... data-field="theme-footer"> be used as the root Element of this Widget */}

10.5. Use other Widgets in a composite component

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!

10.5.1. Annotate Widgets in the template with @DataField

In order to composite Widgets into the template DOM, you must annotate fields in your @Templated Composite component with @DataField, and mark the HTML template Element with a corresponding
data-field
attribute. This informs Errai UI that the contents of the field should replace the element marked by data-field in the template; thus, fields annotated with @DataField must either be @Inject or initialize valid Widget or Element instances.

@TemplatedpublicclassLoginFormextendsComposite{//This element must be initialized manually because Element is not @Inject-able*/ @DataFieldprivateElement form = DOM.createForm();//If not otherwise specified, the data-field name defaults to the name of the field; in thiscase, the data-field name would be "username" @Inject @DataFieldprivateTextBox username;//The data-field name may also be specified manually @Inject @DataField("pass")privatePasswordTextBox password;//We can also choose to instantiate our own Widgets.Injection is not required. @DataFieldprivateButton submit =newButton();}

Important

Note: Field, method, and constructor injection are all supported by @DataField.

10.5.2. Add corresponding data-field attributes

We must also add data-field attributes to the corresponding locations in our template HTML file. This, combined with the @DataField annotation in our Composite component allow Errai UI to determine where and what should be composited when creating component instances.

<formdata-field="form"><legend>Log in to your account</legend><labelfor="username">Username</label><inputdata-field="username"id="username"type="text"placeholder="Username"><labelfor="password">Password</label><inputdata-field="pass"id="password"type="password"placeholder="Password"><buttondata-field="submit">Log in</button><button>Cancel</button></form>

Now, when we run our application, we will be able to interact with these fields in our Widget.

10.6. How HTML templates are merged with Components

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

Element attributes are merged from the template to the component

DOM Elements are merged from the component to the template

Template element inner text and inner HTML are preserved when the given
@DataFieldWidget
implements
HasText
or
HasHTML

10.6.1.2. Template:

<form><spandata-field="field-1"style="display:inline;"> This element will become a div </span></form>This text will be ignored.

10.6.1.3. Output / result:

<formid="outer-id"><divdata-field="field-1"style="display:inline;"> This element will become a div </div></form>

But why does the output look the way it does? Some things happened that may be unsettling at first, but we find that once you understand why these things occur, you'll find the mechanisms extremely powerful.

10.6.2. Element attributes (template wins)

When styling your templates, you should keep in mind that all attributes defined in the template file will take precedence over any preset attributes in your Widgets. This "attribute merge" occurs only when the components are instantiated; subsequent changes to any attributes after Widget construction will function normally. In the example we defined a Composite component that applied several styles to a child Widget in its constructor, but we can see from the output that the styles from the template have overridden them. If styles must be applied in Java, instead of the template,
@PostConstruct
or other methods should be favored over constructors to apply styles to fully-constructed Composite components.

10.6.3. DOM Elements (component field wins)

Element composition, however, functions inversely from attribute merging, and the
<span>
defined in our template was actually be replaced by the
<div>
Label in our Composite component field. This does not, however, change the behavior of the attribute merge - the new
<div>
was still be rendered inline, because we have specified this style in our template, and the template always wins in competition with attributes set programatically before composition occurs. In short, whatever is in the
@DataField
in your class will replace the
data-field
in your template.

Additionally, because
Label
implements both
HasText
and
HasHTML
(only one is required,) the contents of this <span> "field-1" Element in the template were preserved; however, this would not have been the case if the
@DataField
specified for the element did not implement
HasText
or
HasHTML
. In short, if you wish to preserve text or HTML contents of an element in your template, you can do one of two things: do not composite that Element with a
@DataField
reference, or ensure that the Widget being composited implements
HasText
or
HasHTML
.

10.7. Event handlers

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:

GWT events on Widgets

GWT events on DOM Elements

Native DOM events on Elements

Important

It is not possible to handle Native DOM events on Widgets because GWT overrides native event handlers when Widgets are added to the DOM. You must programatically configure such handlers after the Widget has been added to the DOM.

10.7.1. Concepts

Each of the three scenarios mentioned above use the same basic programming model for event handling: Errai UI wires methods annotated with
@EventHandler("my-data-field")
(
event handler methods
) to handle events on the corresponding
@DataField("my-data-field")
in the same component. Event handler methods annotated with a bare
@EventHandler
annotation (no annotation parameter) are wired to receive events on the @Templated component itself.

10.7.2. GWT events on Widgets

Probably the simplest and most common use-case, this approach handles GWT Event classes for Widgets that explicitly handle the given event type. If a Widget does not handle the Event type given in the
@EventHandler
method's signature, the application will fail to compile and appropriate errors will be displayed.

10.7.3. GWT events on DOM Elements

Errai UI also makes it possible to handle GWT events on native Elements which are specified as a
@DataField
in the component class. This is useful when a full GWT Widget is not available for a given Element, or for GWT events that might not normally be available on a given Element type. This could occur, for instance, when clicking on a
<div>
, which would normally not have the ability to receive the GWT
ClickEvent
, and would otherwise require creating a custom DIV Widget to handle such an event.

10.7.4. Native DOM events on Elements

The last approach is handles the case where native DOM events must be handled, but no such GWT event handler exists for the given event type. Alternatively, it can also be used for situations where Elements in the template should receive events, but no handle to the Element the component class is necessary (aside from the event handling itself.) Native DOM events do not require a corresponding
@DataField
be configured in the class; only the HTML
data-field
template attribute is required.

The
@SinkNative
annotation specifies (as a bit mask) which native events the method should handle; this sink behaves the same in Errai UI as it would with
DOM.sinkEvents(Element e, int bits)
. Note that a
@DataField
reference in the component class is optional.

Important

Only one @EventHandler may be specified for a given data-field when @SinkNative is used to handle native DOM events.

10.8. Data Binding

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 automatically be kept in sync. While the module can be used on its own, it can cut even more boilerplate when used together 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 injected and annotated with
@Model
, which indicates automatic binding should be carried out. Alternatively, the model object could be provided by an injected
DataBinder
instance annotated with
@AutoBound
, see
Declarative Binding
for details.

Now the user object and the
username
and
password
fields in the UI are automatically kept in sync. No event handling code needs to be written to update the user object in response to input field changes and no code needs to be written to update the UI fields when the model object changes. So, with the above annotations in place, it will always be true that
user.getUsername().equals(username.getText())
and
user.getPassword().equals(password.getText())
.

10.8.1. Default, Simple, and Chained Property Bindings

By default, bindings are determined by matching field names to property names on the model object. In the example above, the field
name
was automatically bound to the JavaBeans property
name
of the model (
user
object). If the field 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.

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.

10.8.2. Binding of Lists

Often you will need to bind a list of model objects so that every object in the list is bound to a corresponding widget. This task can be accomplished using Errai UI's
ListWidget
class. Here's an example of binding a list of users using the
UserWidget
class from the previous example. First, we need to enhance
UserWidget
to implement
HasModel
.

Calling
setItems
on the
userListWidget
causes an instance of
UserWidget
to be displayed for each user in the list. The
UserWidget
is then bound to the corresponding user object. By default, the widgets are arranged in a vertical panel. However,
ListWidget
can also be subclassed to provide alternative behaviour. In the following example, we use a horizontal panel to display the widgets.

10.8.2.1. Binding lists with @Bound

An instance of
ListWidget
can also participate in automatic bindings using
@Bound
. In this case,
setItems
never needs to be called manually. The bound list property and displayed items will automatically be kept in sync. In the example below a list of user roles is bound to a
ListWidget
that displays and manages a
RoleWidget
for each role in the list. Every change to the list returned by
user.getRoles()
will now trigger a corresponding update in the UI.

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).

10.9. Nest Composite components

Using Composite components to build up a hierarchy of widgets functions exactly the same as when building hierarchies of GWT widgets. The only distinction might be that with Errai UI,
@Inject
is preferred to manual instantiation.

10.10. Extend Composite components

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.

10.10.1. Template

Extension templating is particularly useful for creating reusable page layouts with some shared content (navigation menus, side-bars, footers, etc...,) where certain sections will be filled with unique content for each page that extends from the base template; this is commonly seen when combined with the MVP design pattern traditionally used in GWT applications.

10.10.2. Parent component

This component provides the common features of our page layout, including header and footer, but does not specify any content. The missing data-field will be supplied with unique content by the individual page components extending from this parent component.

We could also have chosen to override one or more
@DataField
references defined in the parent component, simply by specifying a
@DataField
with the same name in the child component, as is done with the "footer"
data-field
below.

10.11. Stylesheet binding

When developing moderately-complex web applications with Errai, you may find yourself needing to do quite a bit of programmatic style changes. A common case being: showing or enabling controls only if a user has the necessary permissions to use them. One part of the problem is securing those features from being used, and the other part – which is an important usability consideration – is communicating that state to the user.

Let's start with the example case I just described. We have a control that we only want to be visible if the user is an admin. So the first thing we do is create a style binding annotation.

Now before the form is shown to the user the
applyAdminStyling
method will be executed where the
sessionManager
is queried to see if the user is an admin if not the delete button that is also annotated with
@Admin
will be hidden from the view.

In addition when using this in conjunction with Errai Databinding. Any Errai UI component which uses @AutoBound, will get live updating of the style rules for free, anytime the model changes. Allowing dynamic styling based on user input and other state changes.

10.12. Internationalization (i18n)

User interfaces often need to be available in multiple languages. To get started with Errai's internationalization support, simply put the
@Bundle("bundle.json")
annotation on your entry point and add an empty
bundle.json
file to your classpath (e.g. to src/main/java or src/main/resources). Of course, you can name it differently.

Errai will scan your HTML templates and process all text elements to generate key/value pairs for translation. It will generate a file called
errai-bundle-all.json
and put it in your
.errai
directory. You can copy this generated file and use it as a starting point for your custom translation bundles. If the text value is longer than 128 characters the key will get cut off and a hash appended at the end.

The translation bundle files use the same naming scheme as Java (e.g.
bundle_nl_BE.json
for Belgian Dutch and
bundle_nl.json
for plain Dutch). Errai will also generate a file called
errai-bundle-missing.json
in the
.errai
folder containing all template values for which no translations have been defined. You can copy the key/value pairs out of this file to create our own translations:

{"StoresPage.Stores!":"Stores!","WelcomePage.As_you_move_toward_a_more_and_more_declarative_style,_you_allow_the_compiler_and_the_framework_to_catch_more_mistakes_up_front._-734987445":"As you move toward a more and more declarative style, you allow the compiler and the framework to catch more mistakes up front. Broken links? A thing of the past!"}

If you want to use your own keys instead of these generated ones you can specify them in your templates using the
data-i18n-key
attribute:

Here the template fills out a navbar with dummy elements, useful for creating a design, adding
data-role=dummy
will not only exclude it form being translated it will also strip the children nodes from the template that will be used by the application.

When you have setup a translation of your application Errai will look at the browser locale and select the locale, if it's available, if not it will use the default (
bundle.json
). If the users of your application need to be able to switch the language manually, Errai offers a pre build component you can easily add to your page:
LocaleListBox
will render a Listbox with all available languages. If you want more control of what this language selector looks like there is also a
LocaleSelector
that you can use to query and select the locale for example:

10.13. Extended styling with LESS

Errai also supports
LESS
stylesheets. To get started using these you'll have to create a LESS stylesheet and place it on the classpath of your project. Errai will convert the LESS stylesheet to css preform optimisations on it and ensure that is get injected into the pages of your application. It will also obfuscate the class selectors and replace the use of those in your templates. To be able to use the selectors in your code you can use:

Because a dot is not allowed in LESS variables it's replaced with an underscore, so in the example above class1 will have a black background on Safari and Chrome and white on Firefox. On the top of this LESS stylesheet @user_agent: "safari" will get generated.

If you are not using Maven for dependency management, add
errai-navigation-version.jar
to the compile-time classpath of a project that's already set up for Errai UI templating.

11.1.2. GWT Module Descriptor

Once you have Errai UI Navigation on your classpath, ensure your application inherits the GWT module as well. Add this line to your application's
*.gwt.xml
file:

<inheritsname="org.jboss.errai.ui.nav.Navigation"/>

11.2. How it Works

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.

11.2.1. Declaring a Page

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

@PagepublicclassItemListPageextendsComposite{//Anything goes...}

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:

Pages are looked up as CDI beans, so you can inject other CDI beans into fields or a constructor. Pages can also have
@PostConstruct
and
@PreDestroy
CDI methods.

11.2.1.2. Page Lifecycle

There are four annotations related to page lifecycle events:
@PageShowing
,
@PageShown
,
@PageHiding
, and
@PageHidden
. These annotations designate methods so a page widget can be notified when it is displayed or hidden:

The
@PageHiding
method on the current (about-to-be-navigated-away-from) page is invoked

The current page is removed from the browser's DOM

The
@PageHidden
method on the just-removed page is invoked

The navigation system looks up the corresponding
@Page
bean in the client-side bean manager (we'll call this bean "the new page")

The navigation system writes to all
@PageState
fields in the new page bean (more on this in the next section)

The
@PageShowing
method of the new page is invoked

The new page widget is added to the DOM (as a direct child of the navigation content panel)

The
@PageShown
method of the new page is invoked.

The
@PageShowing
and
@PageShown
methods are permitted one optional parameter of type
HistoryToken
---more on this in the next section.

The lifespan of a Page instance is governed by CDI scope: Dependent and implict-scoped page beans are instantiated each time the user navigates to them, whereas Singleton and ApplicationScoped beans are created only once over the lifetime of the application. If a particular page is slow to appear because its UI takes a lot of effort to build, try marking it as a singleton.

11.2.1.3. Page State Parameters

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:

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
and
@PageShown
methods through a parameter of type
HistoryToken
. Whether or not a lifecycle 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.

11.2.2. Declaring a Link with TransitionAnchor

The easiest way to declare a link between pages is to inject an instance of
TransitionAnchor<P>
, where
P
is the class of the target page.

Here is an example declaring an anchor link from the templated welcome page to the item list page. The first code sample would go in WelcomePage.java while the second would go in the WelcomePage.html, the associated html template.

You can inject any number of links into a page. The only restriction is that the target of the link must be a Widget type that is annotated with
@Page
. When the user clicks the link Errai will transition to the item list page.

11.2.3. Declaring a Manual Link

Sometimes it is necessary to manually transition between pages (such as in response to an event being fired). To declare a manual link from one page to another, inject an instance of
TransitionTo<P>
, where
P
is the class of the target page.

This code declares a manual transition from the welcome page to the item list page:

11.2.5. Installing the Navigation Panel into the User Interface

Beginning in version 2.4, Errai will automatically attach the Navigation Panel to the Root Panel, but it is possible to override this behaviour by simply adding the Navigation Panel to another component manually. The best time to do this is during application startup, for example in the
@PostConstruct
method of your
@EntryPoint
class. By using the default behaviour 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 by choosing an alternate location for the Navigation Panel.

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:

11.2.6. Viewing the Generated Navigation Graph

Because the pages and links in an Errai Navigation application are declared structurally, the framework gets a complete picture of the app's navigation structure at compile time. This knowledge is saved out during compilation (and at page reload when in Dev Mode) to the file
.errai/navgraph.gv
. You can view the navigation graph using any tool that understands the GraphViz (also known as DOT) file format.

One popular open source tool that can display GraphViz/DOT files is
GraphViz
. Free downloads are available for all major operating systems.

When rendered, a navigation graph looks like this:

Figure 11.1. TODO InformalFigure image title empty

In the rendered graph, the pages are nodes (text surrounded by an ellipse). The starting page is drawn with a heavier stroke. The links are drawn as arrows from one page to another. The labels on these arrows come from the Java field names the TransitionTo objects were injected into.

Chapter 12. Errai Cordova (Mobile Support)

Starting with version 2.4.0, Errai now supports mobile development. One of the modules that makes this feasible is the Cordova module. It offers a way to integrate with native hardware in an Errai way.

12.1. Get started

Add the following to your application's .gwt.xml module file:

12.1.1. App.gwt.xml

<inheritsname="org.jboss.errai.ui.Cordova"/>

12.2. Integrate with native hardware

When the Cordova module is included you can integrate with native hardware by injecting the native components into your code:

12.3. Maven build

All that is left to do is build this and put it on a actual device. In order to make this as easy as possible we have a maven plugin that will create a native binary that you can install on a device. It will put the html and javascript of you application in a
cordova
application, because by doing so the client is no longer servered by the server the client will need to know how it can reach the server to do that place the following in your gwt.xml:

12.4.2. Stores

Another concept that comes with AeroGear is Stores. Currently there are 2 Store types supported: Memory and SessionLocal. Memory is just a big javascript array to hold your data. Here is how you create and configure a Store:

13.1. ErraiApp.properties

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.

13.1.1. As a Marker File

AnErraiApp.propertiesfile must appear at the root of each classpath location that contains an Errai module.
The contents of JAR and directory classpath entries that do not contain an
ErraiApp.properties
are effectively invisible to Errai's classpath scanner.

13.1.2. As a Configuration File

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.

13.1.2.1. Configuration Merging

In a non-trivial application, there will be several instances of ErraiApp.properties on the classpath (one per JAR file that contains Errai modules, beans, or portable classes).

Before using the configuration information from ErraiApp.properties, Errai reads the contents of every ErraiApp.properties on the classpath. The configuration information in all these files is merged together to form one set of key=value pairs.

If the same key appears in more than one ErraiApp.properties file, only one of the values will be associated with that key. The other values will be ignored. In future versions of Errai, this condition may be made into an error. It's best to avoid specifying the same configuration key in multiple ErraiApp.properties files.

13.1.2.2. Errai Marshalling Configuration

errai.marshalling.use_static_marshallers
when set to
false
, Errai will not use the precompiled server-side marshallers even if the generated
ServerMarshallingFactoryImpl
class is found on the classpath. This is useful when using Dev Mode in conjunction with an external server such as JBoss AS 7 or EAP 6.

errai.marshalling.force_static_marshallers
when set to
true
, Errai will not use dynamic marshallers. If the generated
ServerMarshallingFactoryImpl
cannot be loaded (possibly after an attempt to generate it on-the-fly), the Errai web app will fail to start.

13.1.3.

13.2. Messaging (Errai Bus) Configuration

13.2.1. Disabling remote communication

In some cases it might be desirable to prevent the client bus from communicating with the server. One use case for this is when all communication with the server is handled using JAX-RS and the constant long polling requests for message exchange are not needed.

To turn off remote communication in the client bus the following JavaScript variable can be set in the HTML host page:

13.2.2. Configuring an alternative remote remote bus endpoint

By default the remote bus is expected at the GWT web application's context path. In case the remote bus is part of a different web application or deployed on a different server, the following configuration can be used in the HTML host page to configure the remote bus endpoint used on the client.

13.2.3. ErraiService.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.

13.2.3.1. Message Dispatching

Dispatchers encapsulate the strategy for taking messages that need to be delivered somewhere and seeing that they are delivered to where they need to go. There are two primary implementations that are provided with Errai, depending on your needs.

13.2.3.1.1. SimpleDispatcher

SimpleDispatcher is basic implementation that provides no asychronous delivery mechanism. Rather, when you configure the Errai to use this implementation, messages are delivered to their endpoints synchronously. The incoming HTTP thread will be held open until the messages are delivered.

While this sounds like it has almost no advantages, especially in terms of scalablity. Using the SimpleDispatcher can be far preferable when you're developing your application, as any errors and stack traces will be far more easily traced and some cloud services may not permit the use of threads in any case.

13.2.3.1.2. AsyncDispatcher

The AsyncDispatcher provides full asynchronous delivery of messages. When this dispatcher is used, HTTP threads will have control immediately returned upon dispatch of the message. This dispatcher provides far more efficient use of resources in high-load applications, and will significantly decrease memory and thread usage overall.

errai.dispatcher.implementation
specifies the dispatcher implementation to be used by the bus. There are two implementations which come with Errai out of the box: the
SimpleDispatcher
and the
AsyncDispatcher
. See ERRAI:Dispatcher Implementations for more information about the differences between the two.

13.2.3.2. Threading

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.

13.2.3.3. Buffering

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
.

13.2.3.4. Security

errai.authentication_adapter
specifies the authentication modelAdapter the bus should use for determining whether calls should be serviced based on authentication and security principals.

errai.require_authentication_for_all
indicates whether or not the bus should always require the use of authentication for all requests inbound for the bus. If this is turned on, an authentication model adapter must be defined, and any user must be authenticated before the bus will deliver any messages from the client to any service.

13.2.3.5. Clustering

errai.bus.enable_clustering
A boolean indicating whether or not Errai's server side bus should attempt to orchestrate with its peers. The orchestration mechanism is dependent on the configured clustering provider (e.g. UDP based multicast discovery in case of the default JGroups provider). The default value is
false
.

errai.bus.clustering_provider
The fully qualified class name of the clustering provider implementation. A class that implements
org.jboss.errai.bus.server.cluster.ClusteringProvider
. Currently the only build-in provider is the
org.jboss.errai.bus.server.cluster.jgroups.JGroupsClusteringProvider
.

13.2.3.6. Startup Configuration

errai.auto_discover_services
A boolean indicating whether or not the Errai bootstrapper should automatically scan for services.
This property must be set to
true
if and only if Errai CDI is not on the classpath
. The default value is
false
.

errai.auto_load_extensions
A boolean indicating whether or not the Errai bootstrapper should automatically scan for extensions. The default value is
true
.

13.2.3.7. Example Configuration

##
## Request dispatcher implementation (default is SimpleDispatcher)
##
#errai.dispatcher_implementation=org.jboss.errai.bus.server.SimpleDispatcher
errai.dispatcher_implementation=org.jboss.errai.bus.server.AsyncDispatcher
#
## Worker pool size. This is the number of threads the asynchronous worker pool should provide for
processing
## incoming messages. This option is only valid when using the AsyncDispatcher implementation.
##
errai.async.thread_pool_size=5
##
## Worker timeout (in seconds). This defines the time that a single asychronous process may run,
before the worker pool
## terminates it and reclaims the thread. This option is only valid when using the AsyncDispatcher
implementation.
##
errai.async.worker.timeout=5
##
## Specify the Authentication/Authorization Adapter to use
##
#errai.authentication_adapter=org.jboss.errai.persistence.server.security.HibernateAuthenticationAdapter
#errai.authentication_adapter=org.jboss.errai.bus.server.security.auth.JAASAdapter
##
## This property indicates whether or not authentication is required for all communication with the
bus. Set this
## to 'true' if all access to your application should be secure.
##
#errai.require_authentication_for_all=true

13.2.4. Servlet Configuration

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
.

One is Enough!

You should use just one of the options below. Configuring multiple ErraiServlet implementations in the same application will lead to unpredictable behaviour!

Remember that all Errai demos and archetypes are preconfigured with DefaultBlockingServlet as a servlet. You will need to remove this default setup if you choose to use a different ErraiServlet implementation in your app.

13.2.4.1. DefaultBlockingServlet

This ErraiServlet implementation should work in virtually any servlet container that supports Java Servlets 2.0 or higher. It provides purely synchronous request handling. The one scenario where this servlet will not work is in servers that put restrictions on putting threads into sleep states.

The default DefaultBlockingServlet which provides the HTTP-protocol gateway between the server bus and the client buses.

As its name suggests, DefaultBlockingServlet is normally configured as an HTTP Servlet in the
web.xml
file:

13.2.4.2. DefaultBlockingServlet configured as Filter

Alternatively, the DefaultBlockingServlet can be deployed as a Servlet Filter. This may be necessary in cases where an existing filter is configured in the web application, and that filter interferes with the Errai Bus
requests. In this case, configuring DefaultBlockingServlet to handle
*.erraiBus
requests ahead of other filters in web.xml will solve the problem:

13.2.4.3. JettyContinuationsServlet

The Jetty implementation leverages Jetty's continuations support, which allows for threadless pausing of port connections. This servlet implementation should work without any special configuration of Jetty.

13.2.4.4. StandardAsyncServlet

This implementation leverages asynchronous support in Servlet 3.0 to allow for threadless pausing of port connections. Note that
<async-supported>true</async-supported>
has to be added to the servlet definition in
web.xml
.

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:

14.1. Why does it seem that Errai can't see my class at compile time?

Possible symptoms:

uncaught exception: java.lang.RuntimeException: No proxy provider found for type:
my.fully.qualified.ServiceName

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:

Answer:
This error message means that your project has a (direct or indirect) subclass of JavaScriptObject that lacks a protected no-args constructor. All subtypes of JavaScriptObject (also known as
overlay types
) must declare a protected no-args constructor, but the error message could be much clearer. There is an issue filed in the GWT project's bug tracker for improving the error message:
GWT issue 3383
.

Answer:
You can't invoke RPC methods via
Caller<?>
or by other means until after the Errai Bus has finished its initial handshake. Try changing your
@PostConstruct
annotation to
@AfterInitialization
. This will cause your method to be invoked later—after the bus handshake has completed.

If this doesn't help, it is also possible that the proxies were never generated in the first place. Check in
.errai/RpcProxyLoaderImpl.java
to see if proxy code exists for the
@Remote
and/or
@Path
interface in question. If not, your
@Remote
interfaces were not present on the GWT compiler's classpath when your application module was compiled. Double-check your GWT compilation classpath: all
@Remote
interfaces must be visible to (in or inherited by) the GWT module that contains the
Caller<?>
types. Pay special attention that your
@Remote
and
@Path
interfaces are not in a package excluded from the GWT module (by default, every subpackage other than
client
and
shared
is invisible to the GWT compiler).

Chapter 15. Upgrade Guide

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
.

15.1. Upgrading from 1.* to 2.0

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
.

15.2. Upgrading from 2.0.Beta to 2.0.*.Final

The following is a list of manual steps that have to be carried out when upgrading from a 2.0.Beta version to 2.0.CR1 or 2.0.Final:

Starting with 2.0.CR1 the default for automatic service discovery has been changed in favour of CDI based applications. That means it has to be explicitly turned on for plain bus applications (Errai applications that do not use Errai-CDI). Not doing so will result in
NoSubscribersToDeliverTo
exceptions. The snippet below shows how to activate automatic service discovery:

The
jboss7-support
module was deleted and is no longer needed as a dependency.

15.3. Upgrading from Errai 2.2.x to 2.4 or 3.0

There are some breaking API changes in the update from Errai 2.2.x to Errai 2.4.x and 3.0.x.

Here are the steps you'll need to take to get your project compiling after you update:

Starting with Errai 2.3.0, GWT 2.5.0 or higher is required.

Use your IDE to organize imports at the top level. In eclipse, you'd click in the Project Explorer, press Ctrl-A (select all) and then Ctrl-O (Organize Imports). Other IDEs have similar features.

The
ErrorCallback
interface has been made more general so the same type can be shared between Errai modules. This allows you reuse your own generic error handler class for, eg, Errai JAX-RS and ErraiBus callbacks. If you want to use a generic error handler throughout your app, change your
ErrorCallback
implementations to
ErrorCallback<?>
and change the first argument type of your error() method to Object. Otherwise, if you have use-case-specific error callbacks, implement the interfaces
RestErrorCallback
or
BusErrorCallback
as appropriate.