Errai: The browser as a platform

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!