TicketMonster Tutorial

Introduction & Getting Started

Purpose and Target Audience

The target audience for this tutorial are those individuals who do not yet have a great deal of experience with:

  • Eclipse + JBoss Tools (JBoss Developer Studio)

  • JBoss Enterprise Application 6.2

  • Java EE 6 features like JAX-RS

  • HTML5 & jQuery for building an mobile web front-end.

This tutorial sets the stage for the creation of TicketMonster - our sample application that illustrates how to bring together the best features of Java EE 6 + HTML5 + JBoss to create a rich, mobile-optimized and dynamic application.

TicketMonster is developed as an open source application, and you can find it at github.

If you prefer to watch instead of read, a large portion of this content is also covered in video form.

In this tutorial, we will cover the following topics:

  • Working with JBoss Developer Studio (Eclipse + JBoss Tools)

  • Creating of a Java EE 6 project via a Maven archetype

  • Leveraging m2e and m2e-wtp

  • Using Forge to create a JPA entity

  • Using Hibernate Tools

  • Database Schema Generation

  • Deployment to a local JBoss Server

  • Adding a JAX-RS endpoint

  • Adding a jQuery Mobile client

  • Using the Mobile BrowserSim

jbds7 mobile browsersim
Figure 1. JBoss Developer Studio 7 with Mobile BrowserSim

Installation

The first order of business is to get your development environment setup and JBoss Developer Studio v7 installed. JBoss Developer Studio is Eclipse Kepler (e4.3) for Java EE Developers plus select JBoss Tools and is available for free. Visit https://devstudio.jboss.com/download/7.x.html to download it. You may also choose to install JBoss Tools 4.1 into your existing Eclipse for Java EE Developers installation. This document uses screenshots depicting JBoss Developer Studio.

You must have a Java Development Kit (JDK) installed, either v6 or v7 will work - whilst a JVM runtime will work for most use cases, for a developer environment it is normally best to have the full JDK. System requirements for JBoss Developer Studio are listed in the System Requirements chapter of the JBoss Developer Studio 7.0 Installation Guide online documentation.

Tip

If you prefer to see JBoss Developer studio being installed, then check out this video.

To see JBoss Tools being installed into Eclipse, see this video.

The JBoss Developer Studio installer has a (very long!) name such as jbdevstudio-product-universal-7.0.0.GA-v20130720-0044-B364.jar where the latter portion of the file name relates to build date and version information and the text near the front related to the target operating system. The "universal" installer is for any operating system. To launch the installer you may simply be able to double-click on the .jar file name or you may need to issue the following from the operating system command line:

java -jar jbdevstudio-product-universal-7.0.0.GA-v20130720-0044-B364.jar

We recommend using the "universal" installer as it handles Windows, Mac OS X and Linux - 32-bit and 64-bit versions.

Note

Even if you are installing on a 64-bit OS, you may still wish to use the 32-bit JVM for the JBoss Developer Studio (or Eclipse + JBoss Tools). Only the 32-bit version provides a supported version of the Visual Page Editor - a split-pane editor that gives you a glimpse of what your HTML/XHTML (JSF, JSP, etc) will look like. Also, the 32-bit version uses less memory than the 64-bit version. You may still run your application server in 64-bit JVMs if needed to insure compatibility with the production environment whilst keeping your IDE in 32-bit mode. Visual Page Editor has experimental support for 64-bit JVMs in JBoss Developer Studio 7. Please refer the JBoss Tools Visual Editor FAQ for details.

installer wizard page1
Figure 2. Installation Wizard, Step 1 of 9

The rest of the steps are fairly self explanatory. If you run into trouble, please consult the videos above as they explore a few troubleshooting tips related to JRE/JDK setup.

Please make sure to say Yes to the prompt that says "Will you allow JBoss Tools team to receive anonymous usage statistics for this Eclipse instance with JBoss Tools?". This information is very helpful to us when it comes to prioritizing our QA efforts in terms of operating system platforms. More information concerning our usage tracking can be found at http://www.jboss.org/tools/usage

You can skip the step in the installation wizard that allows you to install JBoss Enterprise Application Platform 6.2 as we will do this in the next step.

Creating a new Java EE 6 project with Maven

Tip

For a deeper dive into the world of Maven and how it is used with JBoss Developer Studio and JBoss Enterprise Application Platform 6 review this video.

Now that everything is properly installed, configured, running and verified to work, let’s build something "from scratch".

We recommend that you switch to the JBoss Perspective if you have not already.

Tip

If you close JBoss Central, it is only a click away - simply click on the JBoss icon in the Eclipse toolbar - it is normally the last icon, on the last row - assuming you are in the JBoss Perspective.

First, select Start from scratch → Java EE Web Project in JBoss Central. Under the covers, this uses a Maven archetype which creates a Java EE 6 web application (.war), based around Maven. The project can be built outside of the IDE, and in continuous integration solutions like Hudson/Jenkins.

jboss dev studio jboss central
Figure 3. JBoss Central

You will be prompted with a dialog box that verifies that JBoss Developer Studio is configured correctly. If you are in a brand new workspace, the application server will not be configured yet and you will notice the lack of a check mark on the server/runtime row.

new project wizard
Figure 4. New Project Wizard
Note

There are several ways to add JBoss Enterprise Application Platform 6 to JBoss Developer Studio. The Install… button on the new project wizard is probably the easiest, but you can use any of the methods you are familiar with!

To add JBoss Enterprise Application Platform, click on the Install… button, or if you have not yet downloaded and unzipped the server, click on the Download and Install… button.

Caution

The download option only works with the community application server. Although the enterprise application server is listed, it still needs to be manually downloaded.

Selecting Install… will pop up the JBoss Runtime Detection section of Preferences. You can always get back to this dialog by selecting Preferences → JBoss Tools → JBoss Tools Runtime Detection.

jboss tools runtime detection
Figure 5. JBoss Tools Runtime Detection

Select the Add button which will take you to a file browser dialog where you should locate your unzipped JBoss server.

runtime open dialog
Figure 6. Runtime Open Dialog

Select Open and JBoss Developer Studio will pop up the Searching for runtimes… window.

searching for runtimes dialog
Figure 7. Searching for runtimes window

Simply select OK. You should see the added runtime in the Paths list.

jboss tools runtime detection after
Figure 8. JBoss Tools Runtime Detection Completed

Select OK to close the Preferences dialog, and you will be returned to the New Project Example dialog, with the the server/runtime found.

as eap found
Figure 9. JBoss AS 7.0/7.1 or EAP 6 Found

The Target Runtime allows you to choose between JBoss Enterprise Application Platform and JBoss AS 7. If it is left empty, JBoss AS 7 will be elected.

Caution

Choosing an enterprise application server as the runtime will require you to configure Maven to use the JBoss Enterprise Maven repositories. For instructions on configure the Maven repositories, visit the JBoss Enterprise Application Platform 6.2 documentation.

Select Next.

new project example step 2
Figure 10. New Project Wizard Step 2

The default Project name is jboss-javaee6-webapp. If this field appears blank, it is because your workspace already contains a "jboss-javaee6-webapp" in which case just provide another name for your project. Change the project name to ticket-monster, and the package name to org.jboss.jdf.example.ticketmonster.

Select Finish.

JBoss Tools/JBoss Developer Studio will now generate the template project and import it into the workspace. You will see it pop up into the Project Explorer and a message that asks if you would like to review the readme file.

prompt for readme
Figure 11. New Project Wizard Step 3

Select Finish

Exploring the newly generated project

Using the Project Explorer, open up the generated project, and double-click on the pom.xml.

The generated project is a Maven-based project with a pom.xml in its root directory.

newly generated project explorer
Figure 12. Project Explorer

JBoss Developer Studio and JBoss Tools include m2e and m2e-wtp. m2e is the Maven Eclipse plug-in and provides a graphical editor for editing pom.xml files, along with the ability to run maven goals directly from within Eclipse. m2e-wtp allows you to deploy your Maven-based project directly to any Web Tools Project (WTP) compliant application server. This means you can drag & drop, use Run As → Run on Server and other mechanisms to have the IDE deploy your application.

The pom.xml editor has several tabs along its bottom edge.

pom xml tabs
Figure 13. pom.xml Editor Tabs

For this tutorial, we do not need to edit the pom.xml as it already provides the Java EE 6 APIs that we will need (e.g. JPA, JAX-RS, CDI). You should spend some time exploring the Dependencies and the pom.xml (source view) tabs.

One key element to make note of is <version.jboss.bom>1.0.4.Final</version.jboss.bom> which establishes if this project uses JBoss Enterprise Application Platform or JBoss AS dependencies. The BOM (Bill of Materials) specifies the versions of the Java EE (and other) APIs defined in the dependency section.

If you are using JBoss Enterprise Application Platform 6 and you selected that as your Target Runtime, you will find a -redhat-1 suffix on the version string. You may need to setup the JBoss Enterprise Maven repository to use the certified dependencies in your project, details of which are available here.

Caution

The specific version of the BOM (e.g. 1.0.4.Final) is likely to change, so do not be surprised if the version is slightly different.

The recommended version of the BOM for a runtime (EAP 6) can be obtained by visiting the JBoss Stacks site.

project explorer java packages
Figure 14. Project Explorer Java Packages

Using the Project Explorer, drill-down into src/main/java under Java Resources.

The initial project includes the following Java packages:

.controller

contains the backing beans for #{newMember} and #{memberRegistration} in the JSF page index.xhtml

.data

contains a class which uses @Produces and @Named to return the list of members for index.xhtml

.model

contains the JPA entity class, a POJO annotated with @Entity, annotated with Bean Validation (JSR 303) constraints

.rest

contains the JAX-RS endpoints, POJOs annotated with @Path

.service

handles the registration transaction for new members

.util

contains Resources.java which sets up an alias for @PersistenceContext to be injectable via @Inject

Now, let’s explore the resources in the project.

project explorer resources
Figure 15. Project Explorer Resources

Under src you will find:

main/resources/import.sql

contains insert statements that provides initial database data. This is particularly useful when hibernate.hbm2dll.auto=create-drop is set in persistence.xml. hibernate.hbm2dll.auto=create-drop causes the schema to be recreated each time the application is deployed.

main/resources/META-INF/persistence.xml

establishes that this project contains JPA entities and it identifies the datasource, which is deployed alongside the project. It also includes the hibernate.hbm2dll.auto property set to create-drop by default.

test/java/test

provides the .test package that contains MemberRegistrationTest.java, an Arquillian based test that runs both from within JBoss Developer Studio via Run As → JUnit Test and at the command line: + + mvn test –Parq-jbossas-remote + + Note that you will need to start the JBoss Enterprise Application Platform 6.2 server before running the test.

src/main/webapp

contains index.xhtml, the JSF-based user interface for the sample application. If you double-click on that file you will see Visual Page Editor allows you to visually navigate through the file and see the source simultaneously. Changes to the source are immediately reflected in the visual pane.

visual page editor
Figure 16. Visual Page Editor

In src/main/webapp/WEB-INF, you will find three key files:

beans.xml

is an empty file that indicates this is a CDI capable EE6 application

faces-config.xml

is an empty file that indicates this is a JSF capable EE6 application

ticket-monster-ds.xml

when deployed, creates a new datasource within the JBoss container

Adding a new entity using Forge

There are several ways to add a new JPA entity to your project:

Starting from scratch

Right-click on the .model package and select New → Class. JPA entities are annotated POJOs so starting from a simple class is a common approach.

Reverse Engineering

Right-click on the "model" package and select New → JPA Entities from Tables. For more information on this technique see this video

Using Forge

to create a new entity for your project using a CLI (we will explore this in more detail below)

Reverse Engineering with Forge

Forge has a Hibernate Tools plug-in that allows you to script the conversion of RDBMS schema into JPA entities. For more information on this technique see this video.

For the purposes of this tutorial, we will take advantage of Forge to add a new JPA entity. This requires the least keystrokes, and we do not yet have a RDBMS schema to reverse engineer. There is also an optional section for adding an entity using New → Class.

Right-click on the .model package in the Project Explorer and select Show In → Forge Console.

show in forge console
Figure 17. Show In Forge Console
Tip

Alternative methods to activate Forge include:

  • Window → Show View → Forge Console

  • Ctrl 4 (Windows) or Cmd 4 (Mac).

Note: the Show In method will issue a "pick-up" command to switch you to the right location within your project.

The first time you start Forge, you will be prompted with a Forge Not Running dialog, select Yes.

forge is not running
Figure 18. Show Forge Not Running
Tip

If you are not prompted you can always start Forge using the green arrow (or stop via the red square) in the Forge Console tab.

forge console tab
Figure 19. Show Forge Start/Stop
forge console
Figure 20. Show Forge Console

Forge is a command-oriented rapid application development tool that allows you to enter commands that generate classes and code. It will automatically update the IDE for you. A key feature is "content assist" or "tab completion", activated by pressing tab.

To generate an entity, use these commands:

entity --named Event --package org.jboss.jdf.example.ticketmonster.model
field string --named name
validation setup --provider JAVA_EE
constraint NotNull --onProperty name
constraint Size --onProperty name --min 5 --max 50 --message "Must be > 5 and < 50"
field string --named description
constraint Size --onProperty description --min 20 --max 1000 --message "Must be > 20 and < 1000"
field boolean --named major
field string --named picture

Let’s work through this, step by step.

At the [ticket-monster] model $ prompt, type en and hit the tab key on your keyboard. entity will fill in. Hit tab again and entity --named will appear. Type in Event and add a space — Forge can not anticipate the name of your new entity!

Hit tab again and select --package. Now, hit tab repeatedly to fill in org.jboss.jdf.example.ticketmonster. Since there are multiple entries underneath examples, Forge will display those options. Type in m and hit tab to select model.

Now hit the Enter/Return key to watch the command execute. The Event entity will be generated into the "model" package and open up inside of Eclipse.

forge event entity
Figure 21. Forge new entity
forge event entity created
Figure 22. Event Entity
Note

@Entity public class is placed on the same line as ` import java.lang.Override` by Forge. Using the formatter your IDE provides on the entity will make this look more like you would expect!

Forge has automatically changed the context of the CLI to Event.java, and typing ls will provide a listing of the fields and methods.

forge ls
Figure 23. Forge ls

Now that the base Event entity has been created, let’s add the fields and their JSR 303 Bean Validation constraints.

This next step involves adding a name property for the Event entity so that an event could hold data like "Rock Concert".

Type fie and hit tab to fill in field, if you hit tab again, Forge will list out the possible field types. Type in s and hit tab, Forge will respond with string. Hit tab again to get --named and type in name. You should end up with the command field string --named name, to execute it, press enter. This will add a private String name; field, and the appropriate accessor and mutator (getter and setter) methods. You should also notice that the toString method is tweaked to include name as well.

forge added name
Figure 24. @Column name

From this point forward, we will assume you have the basics of using Forge’s interactive command line. The remaining commands to run are:

validation setup --provider JAVA_EE
constraint NotNull --onProperty name
constraint Size --onProperty name --min 5 --max 50 --message "Must be > 5 and < 50"
field string --named description
constraint Size --onProperty description --min 20 --max 1000 --message "Must be > 20 and < 1000"
field boolean --named major
field string --named picture

The easiest way to see the results of Forge operating on the Event.java JPA Entity is to use the Outline View of JBoss Developer Studio. It is normally on the right-side of the IDE when using the JBoss Perspective.

outline of event
Figure 25. Outline View

Reviewing persistence.xml & updating import.sql

By default, the entity classes generate the database schema, and is controlled by src/main/resources/persistence.xml.

The two key settings are the <jta-data-source> and the hibernate.hbm2ddl.auto property. The datasource maps to the datasource defined in src\main\webapp\ticket-monster–ds.xml.

The hibernate.hbm2ddl.auto=create-drop property indicates that all database tables will be dropped when an application is undeployed, or redeployed, and created when the application is deployed.

The import.sql file contains SQL statements that will inject sample data into your initial database structure. Add the following insert statements:

insert into Event (id, name, description, major, picture, version) values (1, 'Shane''s Sock Puppets', 'This critically acclaimed masterpiece...', true, 'http://dl.dropbox.com/u/65660684/640px-Carnival_Puppets.jpg', 1);
insert into Event (id, name, description, major, picture, version) values (2, 'Rock concert of the decade', 'Get ready to rock...', true, 'http://dl.dropbox.com/u/65660684/640px-Weir%2C_Bob_(2007)_2.jpg', 1);

Adding a new entity using JBoss Developer Studio

Alternatively, we can add an entity with JBoss Developer Studio or JBoss Tools.

First, right-click on the .model package and select New → Class. Enter the class name as Venue - our concerts & shows happen at particular stadiums, concert halls and theaters.

First, add some private fields representing the entities properties, which translate to the columns in the database table.

package org.jboss.jdf.example.ticketmonster.model;

public class Venue {
        private Long id;
        private String name;
        private String description;
        private int capacity;
}

Now, right-click on the editor itself, and from the pop-up, context menu select Source → Generate Getters and Setters.

generate getters setters
Figure 26. Generate Getters and Setters Menu

This will create accessor and mutator methods for all your fields, making them accessible properties for the entity class.

getter setter dialog
Figure 27. Generate Getters and Setters Dialog

Click Select All and then OK.

venue after getters setters
Figure 28. Venue.java with gets/sets

Now, right-click on the editor, from the pop-up context menu select Source → Generate Hibernate/JPA Annotations.

If you are prompted to save Venue.java, simply select OK.

save modified resources
Figure 29. Save Modified Resources

The Hibernate: add JPA annotations wizard will start up. First, verify that Venue is the class you are working on.

hibernate add jpa annotations
Figure 30. Hibernate: add JPA annotations

Select Next.

The next step in the wizard will provide a sampling of the refactored sources – describing the basic changes that are being made to Venue.

hibernate add jpa annotations step2
Figure 31. Hibernate: add JPA annotations Step 2

Select Finish.

Now you may wish to add the Bean Validation constraint annotations, such as @NotNull to the fields.

Deployment

At this point, if you have not already deployed the application, right click on the project name in the Project Explorer and select Run As → Run on Server. If needed, this will startup the application server instance, compile & build the application and push the application into the JBOSS_HOME/standalone/deployments directory. This directory is scanned for new deployments, so simply placing your war in the directory will cause it to be deployed.

Caution

If you have been using another application server or web server such as Tomcat, shut it down now to avoid any port conflicts.

run as run on server
Figure 32. Run As → Run on Server

Now, deploy the h2console webapp. You can read how to do this in the h2console quickstart.

The Run As → Run on Server option will also launch the internal Eclipse browser with the appropriate URL so that you can immediately begin interacting with the application.

result run on server
Figure 33. Eclipse Browser after Run As → Run on Server

Now, go to http://localhost:8080/h2console to start up the h2 console.

h2console in browser
Figure 34. h2console in browser

Use jdbc:h2:mem:ticket-monster as the JDBC URL (this is defined in src/main/webapp/WEB-INF/ticket-monster-ds.xml), sa as the username and sa as the password.

Click Connect

You will see both the EVENT table, the VENUE table and the MEMBER tables have been added to the H2 schema.

And if you enter the SQL statement: select * from event and select the Run (Ctrl-Enter) button, it will display the data you entered in the import.sql file in a previous step. With these relatively simple steps, you have verified that your new EE 6 JPA entities have been added to the system and deployed successfully, creating the supporting RDBMS schema as needed.

h2console select from event
Figure 35. h2console Select * from Event

Adding a JAX-RS RESTful web service

The goal of this section of the tutorial is to walk you through the creation of a POJO with the JAX-RS annotations.

Right-click on the .rest package, select New → Class from the context menu, and enter EventService as the class name.

new class eventservice
Figure 36. New Class EventService

Select Finish.

Replace the contents of the class with this sample code:

package org.jboss.jdf.example.ticketmonster.rest;

@Path("/events")
@RequestScoped
public class EventService {
        @Inject
        private EntityManager em;

        @GET
        @Produces(MediaType.APPLICATION_JSON)
        public List<Event> getAllEvents() {
                final List<Event> results =
                        em.createQuery(
                        "select e from Event e order by e.name").getResultList();
                return results;
        }
}

This class is a JAX-RS endpoint that returns all Events.

event service copy paste
Figure 37. EventService after Copy and Paste

You’ll notice a lot of errors, relating to missing imports. The easiest way to solve this is to right-click inside the editor and select Source → Organize Imports from the context menu.

source organize imports
Figure 38. Source → Organize → Imports

Some of the class names are not unique. Eclipse will prompt you with any decisions around what class is intended. Select the following:

  • javax.ws.rs.core.MediaType

  • org.jboss.jdf.example.ticketmonster.model.Event

  • javax.ws.rs.Produces

  • java.util.List

  • java.inject.Inject

  • java.enterprise.context.RequestScoped

The following screenshots illustrate how you handle these decisions. The Figure description indicates the name of the class you should select.

organize imports 1
Figure 39. javax.ws.rs.core.MediaType
organize imports 2
Figure 40. org.jboss.jdf.example.ticketmonster.model.Event
organize imports 3
Figure 41. javax.ws.rs.Produces
organize imports 4
Figure 42. java.util.List
organize imports 5
Figure 43. javax.inject.Inject
organize imports 6
Figure 44. javax.enterprise.context.RequestScoped

You should end up with these imports:

import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.jboss.jdf.example.ticketmonster.model.Event;

Once these import statements are in place you should have no more compilation errors. When you save EventService.java, you will see it listed in JAX-RS REST Web Services in the Project Explorer.

project explorer jax rs services
Figure 45. Project Explorer JAX-RS Services

This feature of JBoss Developer Studio and JBoss Tools provides a nice visual indicator that you have successfully configured your JAX-RS endpoint.

You should now redeploy your project via Run As → Run on Server, or by right clicking on the project in the Servers tab and select Full Publish.

full publish
Figure 46. Full Publish

Using a browser, visit http://localhost:8080/ticket-monster/rest/events to see the results of the query, formatted as JSON (JavaScript Object Notation).

json event results
Figure 47. JSON Response
Note

The rest prefix is setup in a file called JaxRsActivator.java which contains a small bit of code that sets up the application for JAX-RS endpoints.

Adding a jQuery Mobile client application

Now, it is time to add a HTML5, jQuery based client application that is optimized for the mobile web experience.

There are numerous JavaScript libraries that help you optimize the end-user experience on a mobile web browser. We have found that jQuery Mobile is one of the easier ones to get started with but as your skills mature, you might investigate solutions like Sencha Touch, Zepto or Jo. This tutorial focuses on jQuery Mobile as the basis for creating the UI layer of the application.

The UI components interact with the JAX-RS RESTful services (e.g. EventService.java).

Tip

For more information on building HTML5 + REST applications with JBoss technologies, check out Aerogear.

These next steps will guide you through the creation of a file called mobile.html that provides a mobile friendly version of the application, using jQuery Mobile.

First, using the Project Explorer, navigate to src/main/webapp, and right-click on webapp, and choose New HTML file.

new html file
Figure 48. New HTML File
Caution

In certain versions of JBoss Developer Studio, the New HTML File Wizard may start off with your target location being m2e-wtp/web-resources, this is an incorrect location and it is a bug, JBIDE-11472.

It has been corrected in JBoss Developer Studio 6.

Change directory to ticket-monster/src/main/webapp and enter name the file mobile.html.

new html file correct location
Figure 49. New HTML File src/main/webapp

Select Next.

On the Select HTML Template page of the New HTML File wizard, select New HTML File (5). This template will get you started with a boilerplate HTML5 document.

select html template
Figure 50. Select New HTML File (5) Template

Select Finish.

The document must start with <!DOCTYPE html> as this identifies the page as HTML 5 based. For this particular phase of the tutorial, we are not introducing a bunch of HTML 5 specific concepts like the new form fields (type=email), websockets or the new CSS capabilities. For now, we simply wish to get our mobile application completed as soon as possible. The good news is that jQuery and jQuery Mobile make the consumption of a RESTful endpoint very simple.

You will now notice the Palette View visible in the JBoss perspective. This view contains a collection of popular jQuery Mobile widgets that can be dragged and dropped into the HTML pages to speed up construction of jQuery Mobile pages.

jquery mobile palette
Figure 51. The jQuery Mobile Palette
Tip

For a deeper dive into the jQuery Mobile palette feature in JBoss Developer Studio review this video.

Let us first set the title of the HTML5 document as:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TicketMonster</title>
</head>
<body>

</body>
</html>

We shall now add the jQuery and jQuery Mobile JavaScript and CSS files to the HTML document. Luckily for us we can do this by clicking the JS/CSS widget in the palette.

js css widget
Figure 52. Click the JS/CSS widget

This results in the following document with the jQuery JavaScript file and the jQuery Mobile JavaScript and CSS files being added to the head element.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
    <meta charset="UTF-8">
    <title>TicketMonster</title>
</head>
<body>

</body>
</html>

We shall now proceed to setup the page layout. Click the page widget in the palette to do so. Ensure that the cursor is in the <body> element of the document when you do so.

jquery mobile page widget
Figure 53. Click the page widget
Caution

When you click some of the widgets in the palette, it is important to have the cursor in the right element of the document. Failing to observe this will result in the widget being added in undesired locations. Alternatively, you can drag and drop the widget to the desired location in the document.

This opens a dialog to configure the jQuery Mobile page.

jquery mobile page
Figure 54. Create a new jQuery Mobile page

Set the page title as "TicketMonster", footer as blank, and the ID as "page1". Click Finish to add a new jQuery Mobile page to the document. The layout is now established.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
    <meta charset="UTF-8">
    <title>TicketMonster</title>
</head>
<body>
        <div data-role="page" id="page1">
                <div data-role="header">
                        <h1>TicketMonster</h1>
                </div>
                <div data-role="content">
                        <p>Page content goes here.</p>
                </div>
                <div data-role="footer">
                        <h4></h4>
                </div>
        </div>
</body>
</html>

To populate the page content, remove the paragraph element: <p>Page content goes here.</p> to start with a blank content section. Click the Listview widget in the palette to start populating the content section.

jquery mobile listview widget
Figure 55. Click the Listview widget

This opens a new dialog to configure the jQuery Mobile listview widget.

jquery mobile listview
Figure 56. Add a jQuery Mobile Listview widget

Select the inset checkbox to display the list as an inset list. Inset lists do not span the entire widget of the display. Set the ID as "listOfItems". Retain the number of items in the list as three, and also their labels, but modify the URL values to #. Retain the default values for the other fields, and click Finish. This will create a listview widget with 3 item entries in the list. The jQuery Mobile page is now structurally complete.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
        <meta charset="UTF-8">
        <title>TicketMonster</title>
</head>
<body>
        <div data-role="page" id="page1">
                <div data-role="header">
                        <h1>TicketMonster</h1>
                </div>
                <div data-role="content">
                        <ul data-role="listview" id="listOfItems" data-inset="true">
                                <li><a href="#">Item 1</a></li>
                                <li><a href="#">Item 2</a></li>
                                <li><a href="#">Item 3</a></li>
                        </ul>
                </div>
                <div data-role="footer">
                        <h4></h4>
                </div>
        </div>
</body>
</html>

You might notice that in the Visual Page Editor, the visual portion is not that attractive, this is because the majority of jQuery Mobile magic happens at runtime and our visual page editor simply displays the HTML without embellishment.

Note

Note: Normally HTML files are deployed automatically, if you find it missing, just use Full Publish or Run As Run on Server as demonstrated in previous steps.

As soon as the page loads, you can view the jQuery Mobile enhanced page.

jquery mobile template
Figure 57. jQuery Mobile Template

One side benefit of using a HTML5 + jQuery-based front-end to your application is that it allows for fast turnaround in development. Simply edit the HTML file, save the file and refresh your browser.

Now the secret sauce to connecting your front-end to your back-end is simply observing the jQuery Mobile pageinit JavaScript event and including an invocation of the previously created Events JAX-RS service.

Insert the following block of code as the last item in the <head> element

<head>
    ...
    <title>TicketMonster</title>
    <script type="text/javascript">
        $(document).on("pageinit", "#page1", function(event){
            $.getJSON("rest/events", function(events) {
                // console.log("returned are " + events);
                var listOfEvents = $("#listOfItems");
                listOfEvents.empty();
                $.each(events, function(index, event) {
                    // console.log(event.name);
                    listOfEvents.append("<li><a href='#'>" + event.name + "</a>");
                });
                listOfEvents.listview("refresh");
            });
        });
    </script>
</head>

Note:

  • On triggering pageinit on the page having id "page1"

  • using $.getJSON("rest/events") to hit the EventService.java

  • a commented out // console.log, causes problems in IE

  • Getting a reference to listOfItems which is declared in the HTML using an id attribute

  • Calling .empty on that list - removing the exiting One, Two, Three items

  • For each event - based on what is returned in step 1

  • another commented out // console.log

  • append the found event to the UL in the HTML

  • refresh the listOfItems

Note

You may find the .append("<li>...") syntax unattractive, embedding HTML inside of the JS .append method, this can be corrected using various JS templating techniques.

The result is ready for the average mobile phone. Simply refresh your browser to see the results.

jquery mobile results
Figure 58. jQuery Mobile REST Results

JBoss Developer Studio and JBoss Tools includes BrowerSim to help you better understand what your mobile application will look like. Look for a "phone" icon in the toolbar, visible in the JBoss Perspective.

mobile browsersim in toolbar
Figure 59. Mobile BrowserSim icon in Eclipse Toolbar
Note

The BrowserSim tool takes advantage of a locally installed Safari (Mac & Windows) on your workstation. It does not package a whole browser by itself. You will need to install Safari on Windows to leverage this feature – but that is more economical than having to purchase a MacBook to quickly look at your mobile-web focused application!

mobile browsersim
Figure 60. Mobile BrowserSim

The Mobile BrowserSim has a Devices menu, on Mac it is in the top menu bar and on Windows it is available via right-click as a pop-up menu. This menu allows you to change user-agent and dimensions of the browser, plus change the orientation of the device.

mobile browsersim devices menu
Figure 61. Mobile BrowserSim Devices Menu
mobile browsersim windows menu
Figure 62. Mobile BrowserSim on Windows 7

You can also add your own custom device/browser types.

mobile browsersim custom devices
Figure 63. Mobile BrowserSim Custom Devices Window

Under the File menu, you will find a View Page Source option that will open up the mobile-version of the website’s source code inside of JBoss Developer Studio. This is a very useful feature for learning how other developers are creating their mobile web presence.

mobile browsersim bofa source
Figure 64. Mobile BrowserSim View Source

Conclusion

This concludes our introduction to building HTML5 Mobile Web applications using Java EE 6 with Forge and JBoss Developer Studio. At this point, you should feel confident enough to tackle any of the additional exercises to learn how the TicketMonster sample application is constructed.

Cleaning up the generated code

Before we proceed with the tutorial and implement TicketMonster, we need to clean up some of the archetype-generated code. The Member management code, while useful for illustrating the general setup of a Java EE 6 web application, will not be part of TicketMonster, so we can safely remove some packages, classes, and resources:

  • All the Member-related persistence and business code:

    • src/main/java/org/jboss/jdf/example/ticketmonster/controller

    • src/main/java/org/jboss/jdf/example/ticketmonster/data

    • src/main/java/org/jboss/jdf/example/ticketmonster/model/Member.java

    • src/main/java/org/jboss/jdf/example/ticketmonster/rest/MemberResourceRESTService.java

    • src/main/java/org/jboss/jdf/example/ticketmonster/service/MemberRegistration.java

  • Generated web content

    • src/main/webapp/index.html

    • src/main/webapp/index.xhtml

    • src/main/webapp/WEB-INF/templates/default.xhtml

  • JSF configuration (we will re-add it via Forge)

    • src/main/webapp/WEB-INF/faces-config.xml

  • Prototype mobile application (we will generate a proper mobile interface)

    • src/main/webapp/mobile.html

Also, we will update the src/main/resources/import.sql file and remove the Member entity insertion:

insert into Member (id, name, email, phone_number) values (0, 'John Smith', 'john.smith@mailinator.com', '2125551212'

The data file should contain only the Event data import:

insert into Event (id, name, description, major, picture, version) values (1, 'Shane''s Sock Puppets', 'This critically acclaimed masterpiece...', true, 'http://dl.dropbox.com/u/65660684/640px-Carnival_Puppets.jpg', 1);
insert into Event (id, name, description, major, picture, version) values (2, 'Rock concert of the decade', 'Get ready to rock...', true, 'http://dl.dropbox.com/u/65660684/640px-Weir%2C_Bob_(2007)_2.jpg', 1);

Share the Knowledge

Find this guide useful?

Feedback

Find a bug in the guide? Something missing? You can fix it by [forking the repository](http://github.com/jboss-jdf/ticket-monster), making the correction and [sending a pull request](http://help.github.com/send-pull-requests). If you're just plain stuck, feel free to ask a question in the [user discussion forum](http://jboss.org/jdf/forums/jdf-users).

Recent Changelog

  • Mar 10, 2014: Prepare for development of 2.5.1-snapshot Vineet Reynolds
  • Mar 10, 2014: Prepare for 2.5.0.final release Vineet Reynolds
  • Mar 03, 2014: Updated references to eap 6.2 in the pom and in the docs Vineet Reynolds
  • Nov 11, 2013: Corrected the readme to include hibernate search installation Vineet Reynolds
  • Nov 08, 2013: Removed references to jboss as 7 Vineet Reynolds
  • Aug 01, 2013: Jdf-438 ticketmonster tutorial now uses jqm palette of jbds 7 Vineet Reynolds
  • Aug 01, 2013: Jdf-439 updated ticketmonster tutorial to use jbds 7 Vineet Reynolds
  • Apr 22, 2013: Jdf-262 updated the tutorial to use jboss eap 6.1 and jbds 6.0.1 Vineet Reynolds
  • Jul 13, 2013: Forge-345 improved the styling for code listings Vineet Reynolds
  • Jun 27, 2013: Oops. changes to tax headers removed the authors metadata. correcting it Rafael Benevides
  • Jun 24, 2013: Switching from setex to tax headers completely Rafael Benevides
  • Jun 11, 2013: Jdf-360 specifed bv provider type to avoid deployment error on eap 6.1 Vineet Reynolds
  • Jun 07, 2013: Fixed spelling and formatting issues Vineet Reynolds
  • Jun 07, 2013: Jdf-194 added a requirement note for running the arquillian test Vineet Reynolds
  • Jan 24, 2013: Fix syntax errors that upset asciidoctor Dan Allen

See full history »