HTML5 Mobile Quickstart & Archetype Deep Dive

TODO: Update links to new as-quickstart repository when completed

 

This article details the sigificant files, libraies, and source code for the AeroGear archetype and quickstart that is part of the JBoss-AS quickstart suite called "jboss-as-html5-mobile".

 

The quickstart example is the direct product of the archetype, and for that reason this article will use the quickstart of reference, but same files will exist if you create your own application using the archetype.  For instructions on getting started with the archetype and quickstart see: Getting Started With HTML5 Mobile Web Development with JBoss

Client Side

The client side of this quickstart consists of single page application (index.html), its dependent libraries, and other standard resources (JavaScript, CSS, images). 

index.html

Github Source: index.html

HTML5 Semantic Tags
HTML5 Form API

app.js

Github Source: app.js

CSS Files

Github Source: CSS directory

 

3rd Party Libraries

Github Source: JavaScript directory

Server Side

The server side of this application consists of a basic domain model using Bean Validation, and JAX-RS service endpoints using RESTEasy to provide access.

Member.java

Github Source: Member.java

 

@Entity
@XmlRootElement
@Table(name = "MemberHTML5", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class Member implements Serializable {
   /** Default value included to remove warning. Remove or modify at will. **/
   private static final long serialVersionUID = 1L;

   @Id
   @GeneratedValue
   private Long id;

   @NotNull
   @Size(min = 1, max = 25, message = "1-25 letters and spaces")
   @Pattern(regexp = "[A-Za-z ]*", message = "Only letters and spaces")
   private String name;

   @NotNull
   @NotEmpty
   @Email(message = "Invalid format")
   private String email;

   @NotNull
   @Size(min = 10, max = 12, message = "10-12 Numbers")
   @Digits(fraction = 0, integer = 12, message = "Not valid")
   @Column(name = "phone_number")
   private String phoneNumber;

 

Here you can see the domain object that is the base of our quickstart.  This class has three fields (Name, Email, and PhoneNumber).  It uses Bean Validation annotations to define constraints for each of these fields so that only valid values will be accepted.

 

Also note that at the top we are defining a table name for this object, and specifying that the Email field must be unique in the data table.  This will come into play later when need to validate this in the JAX-RS services, and process the response codes effectively.

MemberService.java

Github Source: MemberSerive.java

 

This class contains the actual RESTful endpoint definitions and processing code.  It uses RESTEasy which is JBoss's implementation of the JAX-RS specification to make this easy to do, and configure using annotations.  A general discussion of JAX-RS is beyond the scope of this document but checkout the RESTEasy site for more!

 

@Path("/members")
@RequestScoped
@Stateful
public class MemberService {

 

Any requests to /members will be routered to this class and be processed by its methods that are defined below.

 

   @GET
   @Produces("text/xml")
   public List<Member> listAllMembers() {
     ...

   @GET
   @Path("/json")
   @Produces(MediaType.APPLICATION_JSON)
   public List<Member> listAllMembersJSON() {
   ...

   @GET
   @Path("/{id:[0-9][0-9]*}")
   @Produces("text/xml")
   public Member lookupMemberById(@PathParam("id") long id) {
   ...

   @GET
   @Path("/{id:[0-9][0-9]*}/json")
   @Produces(MediaType.APPLICATION_JSON)
   public Member lookupMemberByIdJSON(@PathParam("id") long id) {
   ...

 

The methods above define the different ways of "getting" data from the service.  No only can you get a full list of members, and individual members, you can get them in either XML, or JSON format.  The power of JAX-RS is that these are automatically marshaled from one form to another - we are just dealing with POJOs!

 

Adding members is where it gets more interesting.  Following RESTful conventions we use POST requests to create new objects in the data base.  We define that using the @POST annotation.

 

   @POST
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   @Produces(MediaType.APPLICATION_JSON)
   public Response createMember(@FormParam("name") String name, @FormParam("email") String email, @FormParam("phoneNumber") String phone) {
      Response.ResponseBuilder builder = null;

 

JAX-RS allows our method to accept standard URL encoding form variables, and make it easy to map these to method parameters using the @FormParam annotation. 

 

      //Create a new member class from fields
      Member member = new Member();
      member.setName(name);
      member.setEmail(email);
      member.setPhoneNumber(phone);

 

Using those values it then constructs a new member object.  We don't want to just commit this to the database though.  We want to make sure it is valid first!

 

      try {
         //Validates member using bean validation
         validateMember(member);

 

The validateMember method validates the given Member variable and throws validation exceptions based on the type of error.  If the error is a standard bean validation violation then it will throw a ConstraintValidationException containing a set of the constraints violated.  If the error is caused because an existing member with the same email is registered it throws a regular validation exception so that it can be interpreted separately by the catch block.

 

      } catch (ConstraintViolationException ce) {
         //Handle bean validation issues
         builder = createViolationResponse(ce.getConstraintViolations());
      } catch (ValidationException e) {
         //Handle the unique constrain violation
         Map<String, String> responseObj = new HashMap<String, String>();
         responseObj.put("email","Email taken");
         builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
      }

 

If the member is not valid them a map is created that contains the field name with the error, and the error message associated with that error from Bean Validation.  It is also very important to set the response code correctly.  In our case with use 400 BAD REQUEST for standard constraints, and 409 CONFLICT is another member already has the same email.

 

If the member is valid the object is committed to the database and a CDI event is triggered just in case anything in the application wanted to know when a new member was created.  The method then returns a standard HTTP 200 OK message using the Response.OK() method.

 

         //Register the member
         log.info("Registering " + member.getName());
         em.persist(member);


         //Trigger the creation event
         memberEventSrc.fire(member);


         //Create an "ok" response
         builder = Response.ok();

 

Misc

 

Github Source: JaxRsActivator.java

 

Github Source: Resources.java

 

 

 

Testing the Application Code

Testing an HTML5 based application requires some addition considerations.  First you need to test the JAX-RS  back end services.  Second with more logic existing in JavaScript you need an effective way of unit testing that.

 

We cover that in another article: Testing HTML5 Mobile Quickstart & Archetype