JBoss.orgCommunity Documentation

Errai User Guide


1. Introduction
1.1. What is it
1.2. License and EULA
1.3. Downloads
1.4. Sources
1.5. Reporting problems
2. Installation
2.1. Required software
2.2. Distribution Package
3. Errai Bus
3.1. What is Errai Bus?
3.2. Messaging
3.2.1. MessageBuilder and MessageListener API
3.2.2. Receiving messages on the server side
3.2.3. Sending messages from a client
3.2.4. Sending messages to a client
3.2.5. Receiving messages on the client side
3.2.6. Conversations
3.2.7. Broadcasting
3.2.8. Client-to-Client Communication
3.3. Remote Procedure Calls (RPC)
3.3.1. Creating callable endpoints
3.3.2. Making calls
3.4. Serialization
3.5. Wiring server side components
3.6. Bus configuration
3.6.1. web.xml and app server configuration
3.6.2. ErraiService.properties
3.6.3. ErraiApp.properties
4. Errai Workspaces
4.1. What is workspaces?
4.1.1. Basic concepts
4.1.2. Sandbox
4.2. Workspace API
4.2.1. Declaring and implementing tools
4.2.2. Authorization and access to tools
4.2.3. Common coding pattern
4.3. Core features
4.3.1. Workspace Registry
4.3.2. Authentication and Authorization
4.3.3. LoginClient
4.3.4. History management and perma links
4.3.5. Preferences
4.4. Building a workspaces application
4.4.1. Check the prerequisites
4.4.2. Setup a build environent
4.4.3. Verify the application configuration
4.4.4. Launch the hosted mode and start developing
5. Appendix A: Quickstart
5.1. Using the maven archetype

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

Launching maven the first time

Please note, that when launching maven the first time on your machine, it will fetch all dependecies 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 will start off with some solid code examples and describe the different messaging patterns that are employed by ErraiBus. In later sections, we'll delve into the different percularities of the API, implications, and more complex cases.

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

    public class HelloWorld implements EntryPoint {

        // Get an instance of the MessageBus
        private MessageBus bus = ErraiBus.get();

        public void onModuleLoad() {
            Button button = new Button("Send message");

            button.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                // Send a message to the 'HelloWorldService'.
                MessageBuilder.createMessage()
                    .toSubject("HelloWorldService")             // (1)
                    .signalling()                               // (2)
                    .noErrorHandling()                          // (3)
                    .sendNowWith(bus);                          // (4)
            });

            [...]
         }
    }

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

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

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

   @Service
    public class HelloWorldService implements MessageCallback {

        private MessageBus bus;

        @Inject
        public HelloWorldService(MessageBus bus) {
            this.bus = bus;
        }

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

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

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

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

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

While you can probably imagine simply creating a broadcast-like service which accepts a message from one client and broadcasts it to the rest of the world, it may be less clear how to go about routing from one particular client to another particualr client, so we'll focus on that problem.

Message Routing Information

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

The utility class org.jboss.errai.bus.server.util.ServerBusUtils contains a utility method for extracting the String-based SessionID which is used to identify the message queue associated with any particular client. You may use this method to extract the SessionID from a message so that you may use it for routing. For example:

...
public void callback(Message message) {
    String sessionId = ServerBusUtils.getSessionId(message);

    // Record this sessionId somewhere.
    ...
}
...

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

MessageBuilder.createMessage()
    .toSubject("ClientMessageListener")
    .signalling()
    .with(MessageParts.SessionID, sessionId)
    .with("Message", "We're relaying a message!")
    .noErrorHandling().sendNowWith(bus);

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

Now you're routing from client-to-client!

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 to exposing services to the clients.

ErraiBus provides facility to making asynchronous RPC calls on-top of the bus archhitecture without the need to explicitly declare services or any specific mapping or boilerplate code. This method of communicating with the server is straight-forward and utilizes the simple RemoteCall API.

Remote procedure calls can be be performed against against service class which has been annoted with the @Service annotation and the accompanying method which is being called has been annotated with the @Endpoint annotation, and the method has public access.

@Service
public class QueryService {
   private Map<String, String[]> dataMap;

   public QueryService() {
      setupMap();
   }

   private void setupMap() {
      dataMap = new HashMap<String, String[]>();
      dataMap.put("beer", new String[]{"Heineken", "Budweiser", "Hoogaarden"});
      dataMap.put("fruit", new String[]{"Apples", "Oranges", "Grapes"});
      dataMap.put("animals", new String[]{"Monkeys", "Giraffes", "Lions"});
   }

   @Endpoint
   public String[] getQuery(String queryString) {
      return dataMap.get(queryString.toLowerCase());
   }
}

Notice the @Endpoint annotation on the getQuery() method in the above figure. In this example, the method simply accepts a single String parameter and returns an array of Strings. The method can accept and return any serializable types that have been exposed to the bus within the rules of serializability as laid out in the section on Object Serialization.

Also note that in this example, the service class is not required to implement the MessageCallback interface and is a simple POJO class.

Note: The details in this section are currently subject to change. Please consult this section if you are working off pre-release versions of ErraiBus.

The ErraiService.properties file contains basic configuration for the bus itself.

Example Configuration:

##
## Request dispatcher implementation (default is SimpleDispatcher)
##
#errai.dispatcher_implementation=org.jboss.errai.bus.server.SimpleDispatcher
errai.dispatcher_implementation=org.jboss.errai.bus.server.AsyncDispatcher


#
## Worker pool size.  This is the number of threads the asynchronous worker pool should provide for processing
## incoming messages. This option is only valid when using the AsyncDispatcher implementation.
##
errai.async.thread_pool_size=5

##
## Worker timeout (in seconds).  This defines the time that a single asychronous process may run, before the worker pool
## terminates it and reclaims the thread.   This option is only valid when using the AsyncDispatcher implementation.
##
errai.async.worker.timeout=5

##
## Specify the Authentication/Authorization Adapter to use
##
#errai.authentication_adapter=org.jboss.errai.persistence.server.security.HibernateAuthenticationAdapter
#errai.authentication_adapter=org.jboss.errai.bus.server.security.auth.JAASAdapter

##
## This property indicates whether or not authentication is required for all communication with the bus.  Set this
## to 'true' if all access to your application should be secure.
##
#errai.require_authentication_for_all=true



ErraiWorkspaces provides a fully managed working UI enviroment for which to deploy your console and tooling. Put more succinctly: we provide you the places. All you need to do is put stuff there.

Workspaces goes beyond simple API. It's not just another GWT module. It was designed to get you started quickly, without getting in your way. This includes the environment to build, deploy and test your tools. We've decided to use maven to provide these capabilities. It allows you to quickly get started (see Maven archetype), but more importantly, maven repositories are used to share tool implementations across workspace assemblies. This way you can easily combine your own and 3rd party tools as part of a custom workspace compilation.

Note

The GWT SDK is already part of the sandbox bootstrap. You get everything to get going within minutes: GWT, Errai and 3rd party libraries.

To begin with, we'll look at some examples how to declare tool sets and launch them in a workspace.

It's common to use the WidgetProvider API in a way that GWT 2.0 code splitting can kick in. This allows true lazy loading of tools upon demand, including all .js and resources necessary to run your tools:

@LoadTool(name = "Group Tasks", group = "Tasks")
public class OpenTasksModule implements WidgetProvider
{
    static OpenTasksView instance = null;

    public void provideWidget(final ProvisioningCallback callback)
    {
        GWT.runAsync(
            new RunAsyncCallback()
            {
              public void onFailure(Throwable err)
              {
                GWT.log("Failed to load tool", err);
              }

              public void onSuccess()
              {
                if (instance == null) {
                  instance = new OpenTasksView();  // your tool here
                }
                callback.onSuccess(instance);
              }
            }

        );
    }
}

The workspace itself doesn't require any attention apart from the common API that is decribed in the chapter "Workspace API". Still, in some cases you may need to go beyond the out-of-the-box functionlity. In this chapter we are going to explain the building blocks used in the workspace implementation and how they can be used to replace or extend the default workspace behaviour.

The workspace itself doesn't provide an authentication component. Instead it relies on the Authentication provided by errai bus. When the workspace is loaded two thing happen: The workspace checks if authentication is required and, after authentication if needed, loads the tool sets.

The bus component in charge is the SecurityService (org.jboss.errai.bus.client.security.SecurityService). It is available through workspace Registry. For people extending the workspace functionality it offers two intersting options:

  • Obtain access to the authentication context (username, roles, etc)

  • Deferred workspace assembly

The later is important of you want to provide your own way of authenticating users, but still use the role based authorization build into workspaces.

Note

Don't mess with the authentication unless you now what you are doing. In many cases it might be better to extend the server side authentication adapters instead of overriding the client behaviour. However for the sake of completeness, this mechanism should be mentioned here.

The workspace allows you to store simple key-value pairs as preferences. Like with other common API, you obtain the Preferences through the workspace Registry. The default implementation uses a cookie based approach, but it's easy to replace that one with a custom implementation in the module decriptor:

    
   <module>
    [...]
    <replace-with class="org.jboss.errai.workspaces.client.framework.CookiePreferences">
           <when-type-is class="org.jboss.errai.workspaces.client.framework.Preferences"/>
       </replace-with>
    </module>
    

In this section we go through the steps necessary to create a workspace application. As mentioned before, workspaces is more then just another GWT library. It's intended to get you started quickly. This includes GWT installation, creating a build environment and prepapring your IDE.

The most simple (and least error prone) way to get started is using the maven archetype that we ship as part of errai. Simply follow the instructions in the quickstart section and return here when you are done.

Once you've created a project using the maven archetype, make yourself familiar with the directory structure:

Laika:gwt-app hbraun$ lstree
| pom.xml    
|-src
|---main
|-----java
|-------foo
|---------bar
|-----------client
|-----------server
|-war
|---WEB-INF

It basically follows the default GWT guidelines for breaking up code between client and server. Simply put tools (@LoadToolSet) into the client subpackage and services (@Service) into the server subpackages. Make sure you are familiar with the Workspace API before you continue.

If you followed the steps above, and did build your application stub using the maven archetype, then you should be launch the GWT hosted mode with the following commands:

  mvn gwt:run

 (alternatively)   
  mvn gwt:debug

Launching maven the first time

Please note, that when launching maven the first time on your machine, it will fetch all dependecies 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.

If you have taken a look at the examples that ship with the distribution, you realized that we use maven to build them. The way it is setup, the maven build has several benefits:

In order to get you going quickly, we've provided a project archetype, that allows you to create a project skeleton similiar to the one we use for building the examples. It's based on the maven archetype plugin [1] and needs to be invoked from the command line:

  mvn archetype:generate \
        -DarchetypeGroupId=org.jboss.errai \
        -DarchetypeArtifactId=sandbox-archetype \
        -DarchetypeVersion=1.0.0 \
        -DarchetypeRepository=http://repository.jboss.com/maven2
            

When invoking the archetype build it ask you about the maven groupId, artifactId and package name your GWT application should use:

    Define value for groupId: : foo.bar
    Define value for artifactId: : gwt-app
    Define value for version:  1.0-SNAPSHOT: :
    Define value for package:  foo.bar: : foo.bar.ui
    Confirm properties configuration:
    groupId: foo.bar
    artifactId: gwt-app
    version: 1.0-SNAPSHOT
    package: foo.bar.ui
    Y: : Y
            

What will be created for you, is a maven build structure, including references to the GWT SDK and the Errai dependencies necessary to launch a simple application:

    Laika:test hbraun$ cd gwt-app/
    Laika:gwt-app hbraun$ lstree
    |-src
    |---main
    |-----java
    |-------foo
    |---------bar
    |-----------client
    |-----------server
    |-war
    |---WEB-INF
            

In order launch the GWT hosted mode, change into the project directory and type:

    mvn gwt:run
            

The default project includes both a HelloWorld client (GWT), and a HelloWorld service.



[1] http://maven.apache.org/plugins/maven-archetype-plugin/