Errai: The browser as a platform

Thursday, November 7, 2013

Errai and GWT: State of the Union

If you've seen our recent blog posts, you know that work on Errai 3 is progressing quickly with even more additions to our declarative programming model, performance improvements and a number of simplifications that aim to make getting started a lot easier. All details can be found in our roadmap. Please take a few minutes to review our plan. We're always looking for feedback. At Red Hat we innovate together with our open source communities and we rely on your input and collaboration!

As you know, Errai is based on GWT which itself is a healthy open source project with a large and active community. GWT is a fantastic technology that not only boosts developer productivity, especially in complex browser-based applications, its extensibility also allows for building frameworks like Errai on top of it. Since 2006 I have been using GWT successfully in a number of different projects and I am happy to announce that I got the opportunity to join the GWT Steering Committee. I am honored to represent Red Hat and continue the work that Mike Brock has led in regards to Errai and GWT. I look forward to contributing to one of the best ecosystems in the Java open source landscape.

Red Hat's investment in GWT is not only based on Errai but also on a number of customer facing applications as well as new project called UberFire, a web-based workbench framework implemented with GWT and Errai, led by Jonathan Fuerth.

Errai will also be represented at the GWT.create conference, the biggest GWT community event happening in San Francisco and Frankfurt this December. Jonathan and myself will be presenting in San Francisco, Erik Jan de Wit in Frankfurt. We hope to meet many of you at these events and discuss the future of Errai and GWT or engage in other technology debates :).

GWT and Errai are both mature technologies with a bright future ahead!

We hope to meet many of you at these eventsWe
We hope to meet many of you at these events

Wednesday, November 6, 2013

New Development Mode Setup in Errai 3.0 Milestone 2

One of the new features in our latest 3.0 release is a new development mode setup using JBoss 7 (or Wildfly 8). Until this point, our demos have either:
  1. used an embedded Jetty server, or
  2. have required you to manually run your own JBoss AS instance.
But both of these setups have drawbacks. Having an embedded server makes the development process much more convenient, but it is often necessary to develop with an enterprise capable application server.

The newest development mode setup brings us one step closer to having our cake and eating it too. Using the JBoss CLI interface, we now control an external JBoss or Wildfly instance with the GWT-Maven plugin.

The Setup

All it takes to get started is two new Errai dependencies and some minor changes to the gwt-maven-plugin configurations.

The Workflow

Want to run your app in development mode? Just run mvn gwt:run .

Need to update the server-side code? Run mvn compile and then press "Restart Server".

How Can I Get In On This?

You can check out this feature on errai-tutorial. In our new tutorial guide you can get a thorough introduction on how to setup your environment to run and develop with Errai. (But you can skip to here to get straight to the development mode instructions).

But What If I'm Still On Errai 2.4.x?

Don't worry, you're invited too! The two new dependencies (errai-cdi-jboss and errai-client-local-class-hider) have no other Errai dependencies themselves. That means you can add these artifacts to your maven project without any conflicts. Just add the following to your pom:
And make sure that your gwt-maven-plugin configuration is consistent with the following (specifically the extraJvmArgs, noServer, server properties):
Hope you enjoy it.

Friday, November 1, 2013

Milestone 2 of Errai 3.0 and Errai 2.4.2.Final released!

We've just released the second milestone of Errai 3.0 with a long list of fixes and enhancements. The exact version number is 3.0.0.20131101-M2. The high level roadmap for Errai 3 can be found here. We're always looking for feedback! What features/improvements would you like to see and what is most important to you and your applications? Feel free to leave a comment on this blog, create a forum post or file a JIRA for us.

Watch this space for a follow up post by Max Barkley showing the new development mode support for JBoss AS 7 or WildFly 8 in Errai 3. This will greatly simplify the getting started experience and allow you to develop and test an Errai/GWT application in your actual runtime container.

Errai 2.4.2.Final was also just released and contains a small number of fixes. Most importantly it makes sure applications built with Errai 2.4 can be deployed to WildFly 8.0.0.Beta1.

Happy coding!

Monday, October 7, 2013

More Errai Basics -- Climb on the Magic Message Bus!

In my last post, I talked about Errai CDI Events and began showing how they can be used to implement part of a typical lobby page for a multiplayer web-game. Near the end we encountered a typical use case that could not be handled by Events. As promised, I will now discuss how the Errai Message Bus can be used by the server to target a subset of the connected clients.

The Problem

To quickly recap: we have a set of clients in a game room lobby. We want Client A to invite Client B to a game. We've already figured out how to send an invitation event from Client A to the server, but we need a way to relay this invitation to Client B without broadcasting it to all the other clients.

Some Message Bus Basics

Service Endpoints

The Errai Message Bus is used to send messages between service endpoints. Defining a service endpoint requires only two things:
  1. Subject: A string (not necessarily unique), used by senders to address messages to this endpoint
  2. Callback: A method to be invoked by Errai when a message to this endpoint is received
When an endpoint is created we say that code has subscribed to the given subject. It is possible to dynamically define service endpoints, but as with most features of the framework the declarative syntax is preferable. Here is an example declaring a service in Errai.

It is also possible to annotate methods, such that a class may offer multiple services.

Sending a Message

To send a message we construct it with the MessageBuilder and then send it with the MessageBus like so.


It is possible to send objects with a message by adding parts. In the following example we will send a Greeting object to everyone subscribed to the subject "LonelyPeople".


Message Visibility

As with Errai CDI Events, there is only one degree of visibility of message. If the server sends a message to the subject "ErraiLovers", every subscriber to this subject will receive the message. But if a client sends a message to "ErraiLovers", only subscribers on that same client and the server will receive it.

Back to the Lobby

As you may have already guessed, a simple way to deliver messages to a single client is to dynamically subscribe them to a unique service endpoint.

Using Unique Ids

Here is the simple model used in Errai Block Drop that can be used to establish a direct line of communication to a single client.
  1. When a client first joins the lobby in Block Drop, they fire a CDI Event to the server
  2. The server generates a unique id and adds the client to the lobby
  3. The server fires back the unique id using a Conversational Event (which will only be observed by the original client)
  4. The client observes the event and subscribes to the subject "clientid" where id is the unique id received from the server
(For those who prefer the concrete, here are the implementations of this pattern in block-drop: server sideclient side, and shared code. You'll note that the client side code uses dynamic subscription, since the client's unique id cannot be known at compile time.)

Finishing the Invitation

With services based on unique ids setup for each player, it is now possible for server to target individual players in an invitation by accessing their unique ids. The relayed invitations are sent using the MessageBuilder as previously demonstrated. (Once again, here is the Block Drop implementation.)

Final Note

I hope this helps you to understand the power and flexibility that the Errai Bus provides. This is just one example out of the plethora of potential use cases that the Message Bus could fulfill. When you want the loose-coupling of CDI Events, but need a more fine-grained (or dynamic) control over recipients, Errai Messaging might be the right fit for the job.

Monday, August 26, 2013

Mobile design with Errai

Recently we had quite some discussions on our IRC channel about mobile user interface design with Errai. I think that what we've discussed will be interesting for a larger audience.

The question that came up was: Should hybrid applications be designed and behave like native mobile applications?

The mobile applications you develop with Errai are so called "hybrid apps", basically a native “shell” that executes HTML and Javascript. So, the UI will look and feel more or less the same on all supported devices (factoring out rendering differences) and will not be geared towards a specific platform.

We could try and emulate native behaviour but this could lead to what is know as the Uncanny valley, a term from robotics and animation that refers to the problem of an interaction or feature designed to mimic human behaviour that just doesn’t feel right to actual human observers. So, rather than providing a good user experience it causes a repulsive effect that occurs when you get very close to real human behaviour, but not quite there.

Have a look at the scary android, to 'feel' exactly what I'm talking about!

Simulating the native look and feel in hybrid applications could lead to that same negative effect. This is one of the reasons why jquery mobile is designed independently of specific platforms, although some fork it and make it look native again.

One way to easily create something that feels mobile without trying to look native is to use a CSS framework. The latest Twitter bootstrap and Foundation 4 embrace what they call "Mobile First" where you first build your user interface for mobile and then add more "complexity" later on. Errai UI is great when it comes to use CSS frameworks like these because you can quickly create your mockups and then reuse these in your app.

Here is one I've created with Twitter bootstrap for example. I'm not a designer and found it easy to build this mobile UI. I am sure anyone can create something in plain HTML and CSS that “feels” like a mobile app using these tools.

On the other hand, if you want to build a quick prototype of an mobile app you might want to combine Errai with something like mgwt. One of the reasons for frameworks to start emulate the native UIs is that users will automatically know how your app works.

There are also some popular applications that are avoiding these issues altogether by relying on their own custom look and feel (e.g. Skype and GMail). They focus on having their own brand identity aligned on all devices. If you work with good designers you can have a brand that looks great on all platforms.

So, what do you think? Should we support both hybrid and native applications with Errai? Even though there is this uncanny valley your app might fall into? Do you still want to create a mobile app that looks native? We would love to hear what you think!

Friday, August 9, 2013

Block Drop -- A fun demo and tool for learning the fundamentals of Errai

Three months ago I became the Red Hat intern for Errai. Shortly afterwards I embarked on a modest task: to make a demo showing the world how awesome Errai is. I am now happy to present Block Drop, a simple multi-player, Tetris-like web game for the desktop or touch screen browsers.

If you're new to Errai, Block Drop is a great example of how Errai can be used to simplify the task of making rich and interactive web applications. In particular, Block Drop made use of the following elements of Errai:
  • CDI Events
  • Message Bus
  • Errai UI
  • Data Binding
In this post I will cover some basic use cases of CDI Events with examples from Block Drop. (Note that code snippets below may be slightly modified for readability and clarity. You can check out the full source here.)

CDI Events

Making a Simple Game Lobby

In Block Drop players must log into a lobby page before they can begin playing. From this page we want players to be able to do the following tasks:
  1. See other idle players
  2. See current games being played
  3. Start new games, possibly inviting other players to them
  4. Join currently existing games
Furthermore, the lobby state will frequently be changing, and we want all clients to have up-to-date information.

CDI Events to the Rescue

In order to satisfy (1) and (2) above, we need a way to broadcast a list of players and a list of games to all connected clients. Thankfully this task is a piece of cake with Errai. First we need an object to store the information we need for transit. For the sake of simplicity, I have chosen to send the entire lobby state on each update, but in a real-world application one might prefer to send an incremental update.

/** 
 * A portable bean for transmitting lists of players in lobby and games in progress. 
 */ 
@Portable 
public class LobbyUpdate { 

  /** A map player ids to Player objects (of players in lobby). */
  private Map<Integer, Player> playerMap = null;
  /** A map of game ids to Game objects (of games in progress). */
  private Map<Integer, GameRoom> gameMap = null;

 /** 
   * Construct a LobbyUpdate instance. 
   *  
   * @param playerMap 
   *          A map of player ids to players, for all the players in the lobby. 
   *  
   * @param gameMap 
   *          A map of game ids to games, for all the currently in progress games. 
   */ 
  public LobbyUpdate(Map<Integer, Player> players, Map<Integer, GameRoom> games) {
    this.playerMap = players; 
    this.gameMap = games; 
  }

  // Getters and setters omitted

Like the name suggests, a LobbyUpdate object exists for the sole purpose of transmitting information about the state of the lobby. You'll notice that:
  • playerMap contains the idle players
  • gameMap contains the current games
  • Both of these fields have getters and setters (omitted here for brevity)
  • The class is annotated with @Portable
The Portable annotation is what will allow us to send and receive this object over the network. What we need next is way to send LobbyUpdates to clients. Since we want to broadcast this update to all clients indiscriminately, we'll use a CDI Event.

In it's simplest case, a CDI Event in Errai is a simple way for a server to send an object to all of the connected clients. By using an Event object, we will be able to fire LobbyUpdate objects to all clients with one simple command.


  /** Used for sending lobby updates to clients. */ 
  @Inject 
  private Event<LobbyUpdate> lobbyUpdate; 

  /** 
   * Fire an LobbyUpdate to connected clients. This should result in clients
   * refreshing their lobby lists. 
   */ 
  public void sendLobbyList() {
    lobbyUpdate.fire(new LobbyUpdate(lobbyPlayers, games));
  }

The above is an excerpt from the game's Server class. The private field, lobbyUpdate, is the Event object used in the method sendLobbyList to transmit LobbyUpdates. The @Inject annotation tells Errai to assign an event to the lobbyUpdate field when the server is started.

So what happens when this event is sent to the clients? On the client side we need tell the clients to observe LobbyUpdate. So in the Lobby class we add the following method.

  /** 
   * Update the lobby list model and display with newest lobby update from the server. 
   */ 
  public void updateLobby(@Observes LobbyUpdate update) {
    // Updating logic goes here 
  }

The @Observes tells the framework that this method should be called when an Event containing a LobbyUpdate is received. And that's all it takes to transmit the state of the lobby.

CDI Events from the Client

To go about task (3), we need to send an invitation from one client to a subset of the other connected clients. From the previous code examples, you might be expecting something like this:

@Override 
public void onClick(ClickEvent event) {
  Invitation invite = new Invitation(); 
  // Invitation setup logic goes here...

  gameInvitation.fire(invite); 
}

This click handler is called in the lobby when a user presses the "New Game" button. The Invitation object is a @Portable class with setters and getters as its only methods, much like the LobbyUpdate class shown previously. On the last line, the event is fired using gameInvitation, an Event object, which was created using the @Inject annotation as in the previous example.

This is a good start, but the only hiccup is that a CDI Event fired from a client will only go to the server. So we'll need a method to catch and relay this event at the server.

/** 
 * Respond to an invitation by relaying it to the appropriate client. 
 */ 
public void handleInvitation(@Observes Invitation invitation) {
  // Relaying logic goes here 
}

Limitations of CDI Events

But what exactly is the relaying logic that will go in the handleInvitation method above? Can we target specific clients with events? The answer is that we cannot. At least, not with events as we've seen them so far.

In my next post, I'll discuss the Errai Message Bus and how it can be used to relay messages to specific clients as well as lots of other neat things.

Friday, July 26, 2013

LESS support in Errai

As you may know, GWT supports some cool CSS tools. They have extended CSS and made it all more dynamic, that way your css can be more compact and GWT will create a permutation of your css just as it does for your Javascript. Now in Errai, we have our own approach to building user interfaces based on plain HTML5 templates. These templates can come directly from your designer our brand team. So supporting some of that dynamic behaviour is not feasible as we would loose the ability to directly preview the  templates in the browser without first running them through a template engine.

But, GWT is not the only dynamic CSS language. That is why we added support for LESS. It's already used by web designers, so they are familiar with it. You can convert it using javascript so that it you can still look at your templates in a browser. On top of that Errai will find all the LESS stylesheets in your project and convert them to CSS automatically and with this generated CSS it will perform some optimizations:

Optimizations

Basic minification

.div {
  /* This is the default background color */
  background: blue;
}
.empty {}

Would generate:
.div{background:blue;}

Selector merging

.div {prop: value;}
.div {foo: bar;}

Is converted into:
.div {prop:value;foo:bar;} 

Property merging

.a {background: blue;}
.b {background: blue;}

would give
.a,.b{background:blue;}

Finally the last thing it does is obfuscating the class selectors. For that to work it will go through your templates and find where these selectors are used and change them. To be able to use your CSS classes in your Java code, there is a utility that you can inject to access the selectors.

public class MyComponent extends Component {
   @Inject
   private LessStyle lessStyle;

...

   @PostCreate
   private void init() {
       textBox.setStyleName(lessStyle.get("input"));
   }
}

Errai will also inject this generated stylesheet into the head of your page. So, to use this, all you have to do is put a LESS file in your classpath and in true Errai fashion it will do the rest for you. This is available in the latest 3.0-SNAPSHOTs and 2.4-SNAPSHOTs. Give it a spin and let us know what you think.

What we could do next is automatically add variables to your LESS stylesheet so that you can have logic based on browser for instance.

Wednesday, June 19, 2013

A Boatload of Releases


If you've been watching our Twitter feed over the past two weeks, you'll notice there have been three different releases. So, what's going on?

2.3.2.Final is a narrowly targeted release that fixes a few bugs, one of which was critical and a regression in 2.3.1.Final. If you're already in production on Errai 2.3 or earlier, we recommend you update to this version of Errai as soon as possible.


2.4.0.Beta1 includes many of the new features and improvements that we originally planned to debut in Errai 3.0. Here's a quick summary.
  • Improved two-way data binding module (new declarative binding API, list bindings, support for binding a model property to multiple fields)
  • Improved page navigation module (directly use anchors in your templates for page transitions)
  • Errai Mobile: The new Cordova module provides access to native hardware. Simply @Inject a Camera object or any other supported hardware component into your client-side classes! We also provide a Maven plugin to simplify building Errai Apps for mobile devices.
  • Errai JPA/DataSync: This new module provides automatic support for keeping entities persisted in the browser's offline storage in sync with the server!
It also has a lot of API refinements and non-critical bug fixes as compared to the 2.3.x releases. If you are in development on Errai 2.3.x, we recommend that you switch to this release now with the plan to go into production on 2.4.0.Final. We will provide more details and documentation on all of these new features in the next couple of weeks.

3.0.0.20130604-M1 WAT? We're trying milestone releases for 3.0, and this is the first. The crazy numbering scheme is official JBoss Community policy :-). This first milestone contains everything that's in 2.4.0.Beta1 as well as the new Errai OT/EC and Security modules.

Take Data Sync for a Spin


Last year, we implemented a big chunk of the JPA 2.0 API on the client side. In many cases, this allows you to use your existing JPA entities on the client and on the server, simply by putting them in a shared package which is visible to the GWT compiler and deployed to the server.

This is great, because it allows one model class to fill many roles:
  1. Define the persistence structure on the server side (via Hibernate or any other JPA provider)
  2. Define the persistence structure on the client side (via ErraiJPA)
  3. Act as the backing model for forms on the client side (via Errai UI and Data Binding)
  4. Act as the validation specification to all of the above (via Bean Validation annotations)
Saving all this duplication of structure, persistence logic, form modeling, and validation rules is great for many reasons, but I think the most important reason of all is that is makes the application easy to maintain and adapt to changing requirements. You remain nimble because the structure of the problem you're solving is defined in one (and only one!) place.

Enter Data Sync
But what's all this about data sync in the blog title, then?

Well, now you can add one more thing to the list of roles your shared model classes fill: They define data sets that can be kept in sync between the client and the server!

Here's an example of how easy it is to use the new JPA Data Sync feature:

First, let's say these are our shared model classes that are already doing double duty on the client and the server:

@Portable @Bindable @Entity
@NamedQueries({
  @NamedQuery(name="currentItemsForUser", query="SELECT i FROM TodoItem i WHERE i.user = :user AND i.archived=false ORDER BY i.text"),
  @NamedQuery(name="allItemsForUser", query="SELECT i FROM TodoItem i WHERE i.user = :user ORDER BY i.text")
})
public class TodoItem {

  @Id @GeneratedValue
  private Long id;

  /**
   * The user who owns this To-do item.
   */
  @ManyToOne(cascade=CascadeType.MERGE)
  private User user;

  private String text;

  private Boolean done = Boolean.FALSE;
  private Boolean archived = Boolean.FALSE;

  public Long getId() {
    return id;
  }
  public void setId(Long id) {
    this.id = id;
  }
  public User getUser() {
    return user;
  }
  public void setUser(User user) {
    this.user = user;
  }
  public String getText() {
    return text;
  }
  public void setText(String text) {
    this.text = text;
  }
  public Boolean isDone() {
    return done;
  }
  public void setDone(Boolean done) {
    this.done = done;
  }
  public Boolean isArchived() {
    return archived;
  }
  public void setArchived(Boolean archived) {
    this.archived = archived;
  }
  @Override
  public String toString() {
    return "TodoItem [id=" + id + ", user=" + (user == null ? "null" : user.getId()) + ", done=" + done +
            ", archived=" + archived + ", text=" + text + "]";
  }
}

@Portable @Bindable @Entity @Table(name="todolist_user")
@NamedQueries({
  @NamedQuery(name="userById", query="SELECT u FROM User u WHERE u.id = :userId"),
  @NamedQuery(name="userByEmail", query="SELECT u FROM User u WHERE u.email = :email")
})
public class User {

  @Id @GeneratedValue
  private Long id;

  /**
   * The name the user wants us to call them, both to themselves and other users.
   */
  @NotNull
  @Size(min=1, max=60)
  private String shortName;

  /**
   * The user's full name.
   */
  @NotNull
  @Size(min=1, max=60, message="Is that really your name? I'd like to meet your parents.")
  private String fullName;

  /**
   * The user's email address.
   */
  @Column(nullable=false, unique=true)
  @NotNull
  @GwtCompatibleEmail
  private String email;

  public Long getId() {
    return id;
  }

  public String getShortName() {
    return shortName;
  }

  public void setShortName(String shortName) {
    this.shortName = shortName;
  }

  public String getFullName() {
    return fullName;
  }

  public void setFullName(String fullName) {
    this.fullName = fullName;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }
}

As you see, there are a lot of annotations on these model objects. These annotations correspond with the various roles these two classes play in the overall application. Clearly, these classes model a "To-do list" application where each user has 0 or more To-do items.

The annotations that apply to data synchronization are @Entity and @NamedQuery. These also apply to Errai JPA and server-side JPA, so there's actually no visible intrusion on the object model at all!

To use the data sync API, you talk to a class called ClientSyncManager. Here's an example from an Errai UI (client-side) class:

@Templated
public class TodoListSyncWidget extends Composite {

  @Inject private ClientSyncManager syncManager;

  @Inject private @DataField Label errorLabel;
  @Inject private @DataField Button syncButton;

  @EventHandler("syncButton")
  void sync(ClickEvent event) {
    Map<String,Object> params = new HashMap<String, Object>();
    params.put("user", user);
    syncManager.coldSync("allItemsForUser", TodoItem.class, params,
            new RemoteCallback<List<SyncResponse<TodoItem>>>() {
              @Override
              public void callback(List<SyncResponse<TodoItem>> response) {
                syncButton.setEnabled(true);
                System.out.println("Got data sync complete event!");
                refreshItems();
              }
            },
            new BusErrorCallback() {
              @Override
              public boolean error(Message message, Throwable throwable) {
                syncButton.setEnabled(true);
                errorLabel.setText("Sync failed: " + throwable);
                errorLabel.setVisible(true);
                return false;
              }
            });
    syncButton.setEnabled(false);
    System.out.println("Initiated cold sync");
  }
}

Walking through the above, here's all you need to do:
  1. Inject an instance of ClientSyncManager.
  2. Choose a JPA named query that you want to synchronize between client and server. In this case, we've chosen allItemsForUser.
  3. Set the parameter values for the query you are using for the sync. In this case, the query takes a User object as a parameter.
  4. Create a RemoteCallback<List<SyncResponse<YourModelType>>> which will be notified when the sync is complete. Note that your callback receives the list of data sync operations the client has just performed in reaction to the server's reply. You will normally ignore this (as the example above does) but you can also examine it if you'd like to trigger updates in your app based on certain objects being affected by the sync.
  5. Optionally, create a BusErrorCallback to receive error messages associated with exchanging the sync request data with the server.
  6. Invoke the ClientSyncManager.coldSync() method, passing it the items from steps 2-5.
The data sync sends changes from your client-side EntityManager (which stores its data in the browser's localStorage facility) to the server, which incorporates those changes and then responds with a list of changes the client needs to make to catch up with the server's current state. The client then makes the corresponding changes in your local EntityManager. All operations are confined to the results of the named query you specify, so you don't have to worry about syncing the entire server database to every client (unless your query is missing its WHERE clause!)

Before we move on to discuss communication with the server, why not try out the above demo? We've posted it to OpenShift so you can get a feel for how it works. Try signing in as the same user from multiple browsers (or maybe your phone or tablet) and get a feel for how the coldSync() call works. Remember: every time you press the Sync button, the client invokes ClientSyncManager.coldSync() as shown in the code snippet above.


Communicating with the Server
ClientSyncManager communicates with the server using an ErraiRPC Caller. In the current release, you are responsible for creating the server-side @Service class for Errai's Data Sync feature. This is for three reasons:
  1. It gives you the opportunity to obtain the EntityManager from the correct server-side persistence context
  2. It gives you the opportunity to screen and potentially reject sync requests (for example, requiring a logged-in user; disallowing sync requests that touch data that the current user is not allowed to see)
  3. It allows you to choose an alternative transport mechanism (for example, Errai JAX-RS rather than ErraiBus)
We'd like to find a way that this will "just work" out-of-the-box, but still allow you to control the above-listed factors. Expect the following details to change before 3.0 goes final.

@ApplicationScoped @Service
public class DataSyncServiceImpl implements DataSyncService {

  @Inject private DataSyncEjb dataSyncEjb;

  @Override
  public <X> List<SyncResponse<X>> coldSync(
        SyncableDataSet<X> dataSet, List<SyncRequestOperation<X>> remoteResults) {

    // check prerequisites; throw security exceptions if they are not met...

    return dataSyncEjb.coldSync(dataSet, remoteResults);
  }
}


What's Next?
  • server side per-object security callback, so you can vet each entity instance before it's sent to or accepted from the client
  • dot notation in client-side JPQL queries, so your WHERE clause can refer to nested objects
  • pruning results using the lazy fetch clause in the syncable named queries
  • a client-side API for handling sync conflicts by performing a custom 3-way merge (the current release simply allows server state to win in case of a conflict)
  • implementing application-managed transactions on the client side so you can choose to roll back when a conflict is encountered
And finally, incremental sync. The sync that's available now is a "cold" sync: it can be performed any time without any pre-existing contextual information on the server. You can perform cold syncs over and over to stay up to date. However, the cold sync needs to exchange a fair bit of data with the server in order to work. Our plan as we move forward is to implement an incremental sync which the cold sync process can hand off to. This will have two advantages over periodic cold syncs: it will save a lot of data transmission, and it will allow the server to push changes to the client instantly.

All the above is available both on 2.4.0.Beta1 and in the 3.0.0.20130604-M1 (read "3.0 milestone 1") releases. Update your errai.version property accordingly, and if your project depends on errai-javaee-all, you will have Errai Data Sync on your classpath! If you are not using errai-javaee-all, add the following dependency to your pom.xml:

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

Your feedback will help shape our path. Please join us on Freenode #errai, the errai-dev mailing list, or on our community forums.

Wednesday, May 29, 2013

Security

Security is important in any web application and with GWT this is not trivial. There are some well known security frameworks like PicketLink and Shiro, but they are hard to integrate into GWT because they are still request and URL based. So we decided that in true Errai fashion this should be easy.

The new security module is based on PicketLink, but can work with others as well, and integrates well with Errai's existing features like multi-page navigation and automatic data binding. To create a login page for example you'll need something like this:

There are a couple of things that are new here: on the @Page annotation we've introduced the notion of roles. A page can have multiple roles. "Default Page" is now also a page role. You can also define custom page roles in your application and use them to group your pages however you like. LoginPage is a special role that the security module defines. Errai-security will 'redirect' the user to the Login Page when they don't have enough rights to continue.

That raises the question: how do we specify that we need a logged in user for a specific operation or view? Well, we annotate:

This will 'redirect' the user to the login page when the user is not logged in or doesn't have the admin role. Now for those of you who are paying attention, you will have noticed that this is not very secure as this will all happen in the browser via JavaScript. Although the JavaScript is hard to read, an attacker could still be able to call the service even if he is not allowed. That is why the interceptors have server side equivalents that will throw exceptions instead of 'redirecting' the user.

On the server side, the interceptors are CDI interceptors and in order for them to activate you'll need to add them to your beans.xml.

When a user logs in or out, CDI events are fired. Of course, you can observe these events. Also, you can hide elements declaratively based on users' roles. For instance, hide a menu item in a navigation bar:

In this example the admin link is only shown when the user has this role. You'll need to remember to also annotate the Service methods that fetch data for this admin page as you can not rely on these client side checks alone.

Let me know what you think of it and what kind of features you would like to see in there.


Thursday, May 9, 2013

Upcoming JBoss and Red Hat events!

As you know, Errai is sponsored by JBoss and Red Hat. Errai and other great Red Hat open source technologies will be appearing at some of our fantastic upcoming community events. Here's an overview of some opportunities to learn about new technologies and mingle with the development teams from the plethora of great software we develop!

--- 

Red Hat Developer Exchange:
Red Hat Connect Developer Exchange is heading back to Boston. You won't want to miss this one-day event where you can learn more about Red Hat developer tools and technologies. From gcc to Java to scripting languages, from traditional models to devops--You'll get the chance to connect with fellow developers, share real-world challenges, and solve mutual problems through collaboration.

5 tracks and 25 sessions will cover important topics, including:
• Programming on OpenShift Online PaaS
• OpenShift Enterprise and Java
• Languages and tools for mission-critical development
• Get more out of Red Hat Enterprise Linux tools

Red Hat Developer Exchange Agenda:

JUDCon:
The activities start Sunday evening June 9th with the JUDCon, CamelOne and Red Hat Exchange reception. Then Monday and Tuesday, there will be 3 tracks of sessions, and 2 workshop tracks as well. The evening will also include a JBoss Core Developer panel, a live recording of the JBoss Community Asylum, and yes, beer.

The JBoss Users and Developers Conferences are developer gatherings held around the Globe to give JBoss users the chance to talk to and collaborate with Java contributors and core developers. The core JBoss developers, along with the open source community, create and support the projects that drive innovation and help lead development in standards bodies like the Java Community Process, the Apache Software Foundation, OASIS, W3C and other open standards organizations. Many of these projects become the upstream for Red Hat JBoss products.

3 tracks and 33 sessions will cover topics including:
• Java and Java EE App Development
• Mobile Development
• Drools, jBPM, Fuse, ActiveMQ, Infinispan 
• and many more
6 workshops providing hands-on labs covering:
• Ceylon taught by Gavin King and Stephane Epardaud
• Infinispan and JBoss Data Grid cross-datacenter replication
• CDI, Forge and Errai
• and many more.
JUDCon:2013 Boston Agenda


CamelOne:
CamelOne is designed specifically for professionals using open source integration and messaging solutions in the enterprise and will feature a combination of keynote presentations, educational sessions and networking events that will enable attendees to meet, learn and share ideas with open source integration experts.

Founders, committers and users of Apache Camel, ServiceMix, ActiveMQ and CXF enjoyed a great Meet and Greet in the Exhibit Hall from 6:30 to 8:30. Stop by and mingle with your community over hors d’oeuvres and drinks!


CamelOne Agenda

Tuesday, March 26, 2013

Errai 2.3.0.CR1 released!

We've just released Errai 2.3.0.CR1. This is a maintenance release fixing all reported bugs in 2.2.0.Final (see the release notes for details). Errai 2.3 also upgrades all components to GWT 2.5.1.

Development on Errai 3 is already well underway and we will soon have a first milestone release available. There's lots to look forward to in Errai 3:

  • Automatic data synchronization (with support for JPA entities and operational transform)
  • First class mobile support for deploying Errai apps in Cordova
  • Built-in clustering support for Errai Bus
  • Improved data binding, navigation and templating system
  • Asynchronous Bean Manager, allowing client-side code splitting

Thanks everyone for reporting problems and your feedback! Please keep it coming. In this case, more is more!

Wednesday, March 20, 2013

Maven Cordova Plugin

As you may already know, we are also focusing on making mobile applications with Errai. We have something that will make your life really easy. Inspired by the Cordova CLI, we have created something similar that is Maven based.

How does it work

You want to create a Cordova based Errai project, then all you have to do is add this plugin to your maven build. The plugin will create a config.xml in your project folder. In this configuration file you can set settings, like icon and application name. After that, performing a build will copy the generated web files into the Cordova platforms and these will get built.
Now you have integrated mobile platform builds into your regular release cycle. You can run the simulator with the generated binaries all out of your maven project.

Installation

Create an Errai project with one of the archetypes and add the following to your pom Now when you perform a maven install your Android and iOS projects also get built. To see the result of that in the simulator, you just use a simple maven command:
mvn cordova:emulator -Dplatform=android
This will start the Android emulator for your project.
It's still work in progress, but if you want to become an early adopter, just put this repo in your pom and you are ready to go Let me know what you think of it and what kind of features you would like to see in there.

Tuesday, March 12, 2013

Our booth talks at JavaOne 2012!

We really inundated JavaOne with Errai this past year. Here's a collection of booth talks we gave at the conference:

Errai UI


Errai JPA and JAX-RS


Errai CDI (In the Browser!)


Sunday, February 17, 2013

Errai JavaOne talk on YouTube


If you haven't seen our JavaOne talk on Errai yet. Here's another chance. All JavaOne videos have been posted to YouTube. This means you can sync it to your phone or tablet for offline viewing or embed it in your own blog *hint* *hint*!

Taming the Spaghetti: Rich Web Applications with Errai

In this talk, you will learn
- how to create and send push messages (CDI events) from server to client and back
- how to use the same JPA entities in the browser and on the server
- how to create typesafe, refactorable JAX-RS clients in the browser
- and about the underlying technologies within Errai that make all this possible






Friday, February 15, 2013

RPC batching

Today's spotlight is on yet another new feature in Errai 3: RPC batching.

GWT and Errai shine in big web applications that implement complex use cases. These use cases often require multiple interactions with the server. RPC batching allows for batched invocations of remote methods that will be executed using a single server round-trip. This is useful for reducing the number of simultaneous HTTP connections and at the same time allows for reusing and combining fine-grained remote services.

Errai offers a lightweight and boilerplate-free RPC mechanism. All details can be found here. Simply inject a BatchCaller instead of a Caller<T> to make use of batched remote procedure calls. The rest of the API should be familiar if you already use Errai. Here's an example:


Only after sendBatch is called will the remote methods get executed. An additional RemoteCallback can be provided to the sendBatch call which will be invoked when all remote calls have completed in success. Consequently, an additional ErrorCallback can be provided which will get executed for all remote calls that have completed in failure.

The credits for inspiring this feature go to our invaluable community member Josh Blinick. The API might still change as we're looking for feedback! If you have ideas or any feedback, please comment. Here's the link to the JIRA.

Monday, February 11, 2013

Style bindings

Yet another feature finds its way into the 3.0 branch today. And that feature is called style bindings; a feature designed to make your Errai UI-based apps even easier to work with.

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.

That's where style bindings come in.

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.

That was pretty simple. All we did was create an annotation named Admin, and annotate it with the new @StyleBinding annotation.

This now means that @Admin is a style binding. Let's see how we can apply it.

Consider the following Errai UI template class

Here we have a contrived example of a button that deletes something. In this case, if the user is not an admin, which we're checking using a call to SessionManager.isAdmin(), we hide the button from view.

Although, we can potentially refactor this to reduce code re-use. If we're using the @Admin binding throughout our application, we can actually move the applyAdminStyling() method to a common location. Let's move it to the SessionManager.

When we remove that method from our Errai UI component, we get a far more elegant set of code:

Now, when we apply the @Admin rule to any Errai UI @DataField, we automatically inherit this functionality.

The additional bonus comes 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.

As always, if you're interested, checkout Errai 3.0-SNAPSHOT if you're ready to try and get dirty with the latest and greatest features

Saturday, February 2, 2013

Work those cores!

A brand new feature to find it into the 3.0 branch these past few days is our new generator parallelization system. That's right; all the code generating magic of Errai can now be split across those idle cores of your computer to greatly increase compile and development mode speed.

Right now only three generators support this parallelization: IOC/CDI, Marshalling and RPC. But we'll get them all plugged in soon.

The new approach also reduces the amount of redundant work that was previously done as each generator ran. On my development laptop, we're seeing improvements in code generation time of up to 60%.

This optimization also comes on the heels of some fixes to the caching behaviour in our internal class scanning API which should also greatly benefit devmode speed.

ErraiBus Improvements

The performance optimization train is in full swing all around the framework. The new ErraiBus V3 Protocol is now fully implemented and working in the 3.0 branch. It provides a new ultra-lightweight association protocol (apps load faster), less management traffic (less chatty), and a streamlined RPC protocol (less call latency).

Another feature under development is ErraiBus support for SSE (Server-Sent Events) which will also significantly reduce bandwidth usage on the bus.

SSE is essentially a standardization of COMET built right into the browser. It allows servers to keep a port open and return a stream of responses without the needless overhead of repeated GET and response headers.

Look for this feature showing up in the coming weeks.