JBoss.orgCommunity Documentation

Errai

Errai Reference Guide

Legal Notice

Abstract

This is the Errai Reference Guide.


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

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

Launching maven the first time

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

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

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

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

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


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


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

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

Part

Required

JSON Type

Description

ToSubject

Yes

String

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

CommandType

No

String

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

ReplyTo

No

String

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

Value

No

Any

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

PriorityProcessing

No

Number

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

ErrorMessage

No

String

An accompanying error message with any serialized exception

Throwable

No

Object

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

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

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


Part

Required

JSON Type

Description

CapabilitiesFlags

Yes

String

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

Subject

Yes

String

The subject to subscribe or unsubscribe from

SubjectsList

Yes

Array

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

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

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

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

to:

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

Add the following to the web.xml :

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

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

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


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

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


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

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

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

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

Classpath Scanning and ErraiApp.properties

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

A simple example:



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

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



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

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



@ApplicationScoped
public class TimeService {
}

Best Practices

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

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

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

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

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

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

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

  • InitBallotProvider : Makes instances of InitBallot available for injection.

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

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

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

  • RootPanelProvider : Makes GWT's RootPanel singleton injectable.

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

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

TimeService.java



public interface TimeService {
  public String getTime();
}

TimeServiceProvider.java



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

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



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

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

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

Important

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

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

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

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.

For example:

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:

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 :

These Sender<?> features are just convenient wrappers around the full-featured programmatic ErraiBus API. See Section 2.2, “Messaging API Basics” and Section 2.14, “Conversations” for full information about low-level ErraiBus communication.

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.

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.



@Timed(type = TimerType.REPEATING, interval = 1, timeUnit = TimeUnit.SECONDS)
private void updateTime() {
  timeWidget.setTime(System.currentTimeMillis);
}

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

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.


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

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

Consider the following example:

and

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

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

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

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

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

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

Consider the following:

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

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

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



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

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

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

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

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


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

Important

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

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



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

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

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

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

Important

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

Classpath Scanning and ErraiApp.properties

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

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

Let's take a look at an example.


Two things are noteworthy in this example:

  1. Injection of an Event dispatcher proxy

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

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

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

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


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

Example server code:


Domain-model:



Client application logic:


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

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:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Consider the following class:

Let us construct this object like so:

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

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

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

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

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

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

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

Example 5.3. DataMarshaller.java from the built-in marshallers



@ClientMarshaller(Date.class)
@ServerMarshaller(Date.class)
public class DateMarshaller extends AbstractNullableMarshaller<Date> {
  @Override
  public Date[] getEmptyArray() {
    return new Date[0];
  }
  @Override
  public Date doNotNullDemarshall(final EJValue o, final MarshallingSession ctx) {
    if (o.isObject() != null) {
      EJValue qualifiedValue = o.isObject().get(SerializationParts.QUALIFIED_VALUE);
      if (!qualifiedValue.isNull() && qualifiedValue.isString() != null) {
        return new Date(Long.parseLong(qualifiedValue.isString().stringValue()));
      }
      EJValue numericValue = o.isObject().get(SerializationParts.NUMERIC_VALUE);
      if (!numericValue.isNull() && numericValue.isNumber() != null) {
        return new Date(new Double(numericValue.isNumber().doubleValue()).longValue());
      }
      if (!numericValue.isNull() && numericValue.isString() != null) {
        return new Date(Long.parseLong(numericValue.isString().stringValue()));
      }
    }
    return null;
  }
  @Override
  public String doNotNullMarshall(final Date o, final MarshallingSession ctx) {
    return "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + Date.class.getName() + "\"," +
            "\"" + SerializationParts.OBJECT_ID + "\":\"" + o.hashCode() + "\"," +
            "\"" + SerializationParts.QUALIFIED_VALUE + "\":\"" + o.getTime() + "\"}";
  }
}

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

The doNotNullDemarshall() method is responsible for converting the given JSON object (which has already been parsed and verified non-null) into a Java object.

The doNotNullMarshall() method does roughly the inverse: it converts the given Java object into a String (which must be parseable as a JSON object) for transmission on the wire.

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

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

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



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

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



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

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

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:


<servlet>
  <servlet-name>ErraiServlet</servlet-name>
  <servlet-class>org.jboss.errai.bus.server.servlet.DefaultBlockingServlet</servlet-class>
  <init-param>
    <param-name>auto-discover-services</param-name>
    <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

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

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

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

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

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

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

Implementing an interceptor is easy:

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

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

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

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

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

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

  • 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


.

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 contents of the server-side files would be as follows:


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


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

Save typing and reduce duplication

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

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:


For details on the callback mechanism see 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 ).



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

A special case of this RemoteCallback is the ResponseCallback which can be used as an alternative. It provides access to the Response object representing the underlying HTTP response. This is useful when more details of the HTTP response are needed, such as headers 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.



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

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



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

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

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

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

Implementing an interceptor is easy:

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

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

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

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

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

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

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

Errai JPA implements the following subset of JPA 2.0:

  • Annotation-based configuration

  • Entity Types with

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

      • Generated identifiers

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

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

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

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

      • Circular and self references work properly

    • Property access by field or get/set methods

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

    • With cascading fetch of related entities

    • With or without WHERE clause

      • All boolean, arithmetic, and string operators supported

      • All String manipulation functions supported

    • With or without ORDER BY clause

  • Lifecycle events and entity lifecycle listeners

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

It's all client-side

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

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

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

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

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

CascadeType value

Description

PERSIST

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

MERGE

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

REMOVE

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

REFRESH

Not applicable in Errai JPA

DETACH

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

ALL

Equivalent to specifying all of the above

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

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

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

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

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

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

Annotation

Meaning

@PrePersist

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

@PostPersist

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

@PreUpdate

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

@PostUpdate

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

@PreRemove

The entity is about to be removed from persistent storage.

@PostRemove

The entity has just been removed from persistent storage.

@PostLoad

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

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

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

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

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

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

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

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

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

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

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

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.

For the rest of this chapter, we will refer to the following Entity classes, which are defined in a shared package that's visible to client and server code:

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

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.

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:

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

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



@Stateless @org.jboss.errai.bus.server.annotations.Service
public class DataSyncServiceImpl implements DataSyncService {
  @PersistenceContext
  private EntityManager em;
  private final JpaAttributeAccessor attributeAccessor = new JavaReflectionAttributeAccessor();
  @Inject private LoginService loginService;
  @Override
  public <X> List<SyncResponse<X>> coldSync(SyncableDataSet<X> dataSet, List<SyncRequestOperation<X>> remoteResults) {
    // Ensure a user is logged in
    User currentUser = loginService.whoAmI();
    if (currentUser == null) {
      throw new IllegalStateException("Nobody is logged in!");
    }
    // Ensure user is accessing their own data!
    if (dataSet.getQueryName().equals("groceryListsForUser")) {
      User requestedUser = (User) dataSet.getParameters().get("user");
      if (!currentUser.getId().equals(requestedUser.getId())) {
        throw new AccessDeniedException("You don't have permission to sync user " + requestedUser.getId());
      }
    }
    else {
      throw new IllegalArgumentException("You don't have permission to sync dataset " + dataSet.getQueryName());
    }
    DataSyncService dss = new org.jboss.errai.jpa.sync.server.DataSyncServiceImpl(em, attributeAccessor);
    return dss.coldSync(dataSet, remoteResults);
  }
}

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.

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 .

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

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

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 .

Tip

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

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.

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



@Dependent
public class CustomerView {
  @Inject @Model
  private Customer customer;
  @Inject @Bound
  private TextBox name;
  @Bound
  private Label id = new Label();
  ....
}

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.



@Dependent
public class CustomerView {
  @Inject @AutoBound
  private DataBinder<Customer> customerBinder;
  @Inject @Bound
  private TextBox name;
  @Bound
  private Label id = new Label();
  ...
}

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.

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.

The following example illustrates all three scenarios:

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

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



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

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:



    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-validation</artifactId>
      <version>${errai.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <classifier>sources</classifier>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>4.2.0.Final</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>4.2.0.Final</version>
      <scope>provided</scope>
      <classifier>sources</classifier>
    </dependency>

Now it is as simple as injecting a Validator instance into an Errai IOC managed bean and calling the validate method.



@Inject
private Validator validator;


Set<ConstraintViolation<Customer>> violations  = validator.validate(customer);
// display violations

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.

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

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

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

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

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

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

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

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

A recurring implementation task in rich web development is writing event handler code for updating model objects to reflect input field changes in the user interface. The requirement to update user interface fields in response to changed model values is just as common. These tasks require a significant amount of boilerplate code which can be alleviated by Errai. Errai's data binding module provides the ability to bind model objects to user interface fields, so they will 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.



@Templated
public class LoginForm extends Composite {
   @Inject
   @Model
   private User user;
   @Inject
   @Bound
   @DataField
   private TextBox name;
   @Inject
   @Bound
   @DataField
   private PasswordTextBox password;
   @DataField
   private Button submit = new Button();
}

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

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.

The following example illustrates all three scenarios:

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

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 .

Now we can use UserWidget to display items in a list.

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.

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



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

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

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

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.

This defines Adim as a stylebinding now we can use it like this:

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.

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:

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:

By adding this attribute in the template you can translate it with the following:

Because your templates are designer templates and can contain some mock data that doesn't need to be translated, Errai has the ability to indicate that with an attribute data-role=dummy :

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:

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:



public class MyComponent extends Component {
� �@Inject
� �private LessStyle lessStyle;
...
� �@PostCreate
� �private void init() {
� � � �textBox.setStyleName(lessStyle.get("input"));
� �}
}

Finally it will also add any deferred binding properties to the top of your LESS stylesheet, so for example you could use the user.agent in LESS like this:



.mixin (@a) when (@a = "safari") {
  background-color: black;
}
.mixin (@a) when (@a = "gecko1_8") {
  background-color: white;
}
.class1 { .mixin(@user_agent) }

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.

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

  • Declarative, statically-analyzable configuration of pages and links

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

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

  • Decentralized configuration

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

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

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

  • Builds on Errai IoC & CDI

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

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

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

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

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:

Page Lifecycle:

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.

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

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

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

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

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

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

In addition to receiving page state information via direct writes to @PageState fields, you can also receive the whole Multimap in the @PageShowing 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.

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:

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.

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

The components that are supported come from the gwt-phonegap project have a look there form more documentation.

Here are the native hardware components you can inject:

  • Camera

  • Accelerometer

  • Contacts

  • Capture (Provides access to the audio, image, and video capture capabilities of the device).

  • Compass

  • Notification ( see documentation on phonegap site )

  • File create a native file

  • Device Get general information about the device.

So to integrate with these things all we have to do is @Inject these classes. There are also a couple of CDI events one can observe to be informed about hardware state:

  • BackButtonEvent

  • BatteryCriticalEvent

  • BatteryEvent

  • BatteryLowEvent

  • BatteryStatusEvent

  • EndCallButtonEvent

  • MenuButtonEvent

  • OffLineEvent

  • OnlineEvent

  • PauseEvent

  • ResumeEvent

  • SearchButtonEvent

  • StartCallButtonEvent

  • VolumeDownButtonEvent

  • VolumeUpButtonEvent

Example of how to use these events:



  private void batteryIsLow(@Observes BatteryLowEvent event) {
    //mission accomplished. we can stop the infinite loop now.
  }

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:



<replace-with class="com.company.application.Config">
   <when-type-is class="org.jboss.errai.bus.client.framework.Configuration" />
</replace-with>

This class must implement org.jboss.errai.bus.client.framework.Configuration and return the url where the server is configured.



import org.jboss.errai.bus.client.framework.Configuration;
public class Config implements Configuration {
    @Override
    public String getRemoteLocation() {
        // you probably want to do something environment specify here instead of something like this:
        return "https://grocery-edewit.rhcloud.com/errai-jpa-demo-grocery-list";
    }
}

Now all that is left is to add the plugin to the pom.xml like so:



<build>
 ...
    <plugins>
      <plugin>
        <groupId>org.jboss.errai</groupId>
        <artifactId>cordova-maven-plugin</artifactId>
        <version>${errai.version}</version>
      </plugin>

Now you can execute a native build with the following maven command:

#will build all supported platforms for now only ios and android
mvn cordova:build-project

#only build android
mvn cordova:build-project -Dplatform=android

#start the ios emulator with the deployed application
mvn cordova:emulator -Dplatform=ios

Important

For these to work you'll need to have the SDK's installed and on your path! In case of android you will additionally have to have ANDROID_HOME environment variable set.

These wrappers allow your Errai client to talk to an AeroGear server. Also have a look at the documentation of the AeroGear project.

This section contains information on configuring Errai.

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

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

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

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.

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 .

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

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

But for now, on to the FAQ:

Possible symptoms:

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Revision History
Revision