Developer Materials

Introduction & Getting Started

  • Author: Burr Sutter
  • Contributors: Vineet.Reynolds@gmail.com, lightguard.jp@gmail.com, pmuir@bleepbleep.org.uk, rafabene@gmail.com, dan.j.allen@gmail.com, marius.bogoevici@gmail.com, sgilda@redhat.com, burrsutter@gmail.com
  • Published: Jan 15, 2015

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 Platform 6.3

  • 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

 ticket monster tutorial gfx introduction jbds8 mobile browsersim 4
Figure 1. JBoss Developer Studio 8 with Mobile BrowserSim

Installation

The first order of business is to get your development environment setup and JBoss Developer Studio v8 installed. JBoss Developer Studio is Eclipse Luna (e4.4) for Java EE Developers plus select JBoss Tools and is available for free. Visit http://www.jboss.org/products/devstudio/download to download it. You may also choose to install JBoss Tools 4.2 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. Java 7 JDK is recommended - whilst a JVM runtime will work for most use cases, for a developer environment it is normally best to have the full JDK.

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 jboss-devstudio-8.0.0.GA-v20141020-1042-B317-installer-standalone.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 jboss-devstudio-8.0.0.GA-v20141020-1042-B317-installer-standalone.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 8. Please refer the JBoss Tools Visual Editor FAQ for details.

 ticket monster tutorial gfx introduction installer wizard page1 4
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.

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

Once installed, launch JBoss Developer Studio. 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

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.

 ticket monster tutorial gfx introduction jboss dev studio jboss central 4
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.

 ticket monster tutorial gfx introduction new project wizard 4
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.

 ticket monster tutorial gfx introduction jboss tools runtime detection 4
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.

 ticket monster tutorial gfx introduction runtime open dialog 4
Figure 6. Runtime Open Dialog

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

 ticket monster tutorial gfx introduction searching for runtimes dialog 4
Figure 7. Searching for runtimes window

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

 ticket monster tutorial gfx introduction jboss tools runtime detection after 4
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.

 ticket monster tutorial gfx introduction as eap found 4
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.

Proceed to select the EAP 6.3 runtime, you just created.

 ticket monster tutorial gfx introduction as eap selected 4
Figure 10. JBoss EAP 6 runtime selected
Caution

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

You may see a warning (like the one in the screenshot), if you do not have the JBoss Enterprise Maven repository configured in your environment. Should this be the case, select the repository link in the warning, to open the JBoss Maven Integration wizard. The wizard dialog will prompt you to add the JBoss Enterprise Maven repository.

 ticket monster tutorial gfx introduction jboss maven repository 4
Figure 11. Add the JBoss Enterprise Maven repository

Click Ok.

You’ll now be shown the proposed changes to your Maven settings.xml file. Click Finish after reviewing the proposed updates.

 ticket monster tutorial gfx introduction jboss maven repo settings xml 4
Figure 12. Update the Maven settings.xml file

You’ll be prompted to confirm the update. Click Yes.

 ticket monster tutorial gfx introduction prompt update settings xml 4
Figure 13. Confirm the changes to the Maven settings.xml file

The updates will now be persisted, and you’ll be returned to the original wizard.

Now, select Next in the New Project wizard to proceed to the next step.

 ticket monster tutorial gfx introduction new project example step 2 4
Figure 14. 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.examples.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 open the cheatsheet file associated with the project.

 ticket monster tutorial gfx introduction prompt for cheatsheet 4
Figure 15. 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.

 ticket monster tutorial gfx introduction newly generated project explorer 4
Figure 16. 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.

 ticket monster tutorial gfx introduction pom xml tabs 4
Figure 17. 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.eap>6.3.2.GA</version.jboss.bom.eap> which establishes the version of the JBoss Enterprise Application Platform 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 community version of the JBoss Application Server and you selected that as your Target Runtime, you will find a different property as the version string.

Caution

The specific version of the BOM (e.g. 6.3.2.GA) 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.

 ticket monster tutorial gfx introduction project explorer java packages 4
Figure 18. 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.

 ticket monster tutorial gfx introduction project explorer resources 4
Figure 19. 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.3 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.

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.

Select the project in the Project Navigator view of JBoss Developer Studio and enter the Ctrl + 4 (in Windows/Linux) or Cmd + 4 (Mac) key combination. This will launch Forge if it is not started already.

 ticket monster tutorial gfx introduction forge is starting 4
Figure 20. Starting Forge for the first time

The list of commands that you can execute in Forge will be visible in the Forge quick action menu.

 ticket monster tutorial gfx introduction forge action menu 4
Figure 21. Forge action menu
Tip

If you do not see a lot of commands in the quick action menu, then you may not have selected the project. The Forge quick action menu is contextual in nature, and therefore, it displays commands relevant to the current selection in the project explorer.

When nothing is selected, then fewer commands are shown.

Tip

An alternative method to activate Forge is:

  • Window → Show View → Forge Console. Click the Start button in the view.

 ticket monster tutorial gfx introduction show forge view 4
Figure 22. Launch the Show View dialog
 ticket monster tutorial gfx introduction select forge view 4
Figure 23. Select the Forge Console view

Note: Activating Forge this way displays the Forge console that allows you to execute the same commands via a shell interface.

Tip

You can always start Forge using the green arrow (or stop via the red square) in the Forge Console tab.

 ticket monster tutorial gfx introduction forge console tab 4
Figure 24. Show Forge Start/Stop

Forge is a multi-faceted rapid application development tool that allows you to enter commands that generate classes and code. You could use either a GUI within your IDE that offers a familar wizard and dialog based UI, or a shell-like interface to perform operations. It will automatically update the IDE for you. A key feature is "contentual command activation", launched by running the Forge shortcut (Ctrl + 4 or Cmd + 4). For instance, launching Forge on a selected project activates different commands, than launching it in isolation, or for that matter launching Forge with a selected Java source file.

We’ll generate an entity using the Forge GUI. Let’s work through this, step by step.

We start by selecting the TicketMonster project. Launch Forge through the shortcut (Ctrl + 4 or Cmd + 4). Type jpa in the command filter textbox located in the menu. The menu will filter out irrelevant entries, leaving you with JPA-specific commands.

 ticket monster tutorial gfx introduction forge quick action menu filter jpa 4
Figure 25. Filter commands in the Forge menu

Select the "JPA: New Entity" entry in the menu. Click it or hit the Enter key to execute the command. You will be presented with a dialog where you can provide certain inputs that control how the new entity would be generated, like the package where the entity would be created, the name of the JPA entity/class, the primary-key strategy used for the entity etc.

 ticket monster tutorial gfx introduction forge jpa new entity 4
Figure 26. The new JPA entity command in Forge

Specify the value of the entity as Event and click Finish. The defaults for other values are sufficient - note how Forge intelligently constructs the value for the package field from the Maven group Id and artifact Id values of the project.

 ticket monster tutorial gfx introduction forge jpa new entity event 4
Figure 27. Create the Event entity in Forge

You should see a notification bubble in Eclipse when Forge completes the action.

 ticket monster tutorial gfx introduction forge jpa new entity created 4
Figure 28. The Forge notification bubble in Eclipse

Forge would have created a JPA entity as instructed, and it would also open the Java source file in Eclipse. Note that it would have created not only a new class with the @Entity annotation, but also created a primary-key field named id, a version field, along with getters and setters for both, in addition to equals, hashCode and toString methods.

 ticket monster tutorial gfx introduction forge event entity source 4
Figure 29. The newly created Event entity

Let’s add a new field to this entity. Select the Event class in the project navigator and launch the Forge menu once again. Filter on jpa as usual, and launch the "JPA: New Field" command. Specify the field name as name, to store the name of the event. The defaults are sufficient for other input fields. Click Finish or hit the Enter button as usual.

 ticket monster tutorial gfx introduction forge jpa new field name 4
Figure 30. The JPA field wizard in Forge

You will now notice that the Event class is enhanced with a name field of type String, as well as a getter and setter, along with modifications to the toString method.

 ticket monster tutorial gfx introduction forge added name 4
Figure 31. The newly created field in the Event class

Let’s now add Bean Validation (JSR-303) capabilities to the project. Launch the Forge menu, and filter for the "Constraint: Setup" command. Execute the command.

 ticket monster tutorial gfx introduction forge quick action menu filter constraint 4
Figure 32. Filter for constraint commands in the Forge menu

You’ll be presented with a choice on what Bean Validation providers you’d like to setup in the project. The defaults are sufficient - we’ll use the Bean Validation provider supplied by the Java EE application. Click Finish or hit Enter to setup Bean valdiation.

 ticket monster tutorial gfx introduction forge setup constraint wizard 4
Figure 33. Setup Bean Validation

We’ll now add a constraint on the newly added name field in the Event class. Select the Event class in the project navigator and proceed to launch the "Constraint: Add" command from the Forge menu. Note that selecting the Event class allows Forge to provide commands relevant to this class in the action menu, as well as populating this class in input fields where it is fit to populate them.

 ticket monster tutorial gfx introduction forge add constraint on event 4
Figure 34. Select the Event class and launch the "Constraint: Add" wizard

This launches a wizard where one can add Bean Validation constraints. The class to operate on will default to the currently selected class, i.e. Event. If you want to switch to a different class, you can do so in the wizard. There is no need to re-launch the wizard.

 ticket monster tutorial gfx introduction forge select event entity for constraint 4
Figure 35. The constraint is added to the selected class

Proceed to select the name field, on which we add a NotNull constraint. Click Finish or hit Enter.

 ticket monster tutorial gfx introduction forge constraint add notnull on name 4
Figure 36. Add a NotNull constraint on Event name

Similarly, add a Size constraint with min and max values of 5 and 50 respectively on the name field.

 ticket monster tutorial gfx introduction forge constraint add size on name 4
Figure 37. Add a Size constraint on Event name
 ticket monster tutorial gfx introduction forge constraint add set size attributes on name 4
Figure 38. Specify attribute values for the Size constraint

From this point forward, we will assume you have the basics of using Forge’s menu and the commands executed thus far. Add a new field description to the Event class.

 ticket monster tutorial gfx introduction forge jpa new field description 4
Figure 39. Add the description field to Event

Add a Size constraint on the description field to the event class, with min and max values of 20 and 1000 respectively.

 ticket monster tutorial gfx introduction forge constraint add size on description 4
Figure 40. Add a Size constraint on Event name
 ticket monster tutorial gfx introduction forge constraint add set size attributes on description 4
Figure 41. Specify attribute values for the Size constraint

Add a new boolean field major. Note - you will need to change the type to boolean from the default value of String.

 ticket monster tutorial gfx introduction forge jpa new field major 4
Figure 42. Add the major field to Event

Add another field picture to the Event class.

 ticket monster tutorial gfx introduction forge jpa new field picture 4
Figure 43. Add the picture field to Event

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.

 ticket monster tutorial gfx introduction outline of event 4
Figure 44. Outline View

Alternatively, you could perform the same sequence of operations in the Forge Console, using these commands:

jpa-new-entity --named Event --targetPackage org.jboss.examples.ticketmonster.model ;
jpa-new-field --named name ;
constraint-setup ;
constraint-add --onProperty name --constraint NotNull ;
constraint-add --onProperty name --constraint Size --min 5 --max 50 --message "An event's name must contain between 5 and 50 characters" ;
jpa-new-field --named description ;
constraint-add --onProperty description --constraint Size --min 20 --max 1000 --message "An event's description must contain between 20 and 1000 characters" ;
jpa-new-field --named major --type boolean ;
jpa-new-field --named picture ;

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

 ticket monster tutorial gfx introduction generate getters setters 4
Figure 45. Generate Getters and Setters Menu

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

 ticket monster tutorial gfx introduction getter setter dialog 4
Figure 46. Generate Getters and Setters Dialog

Click Select All and then OK.

 ticket monster tutorial gfx introduction venue after getters setters 4
Figure 47. 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.

 ticket monster tutorial gfx introduction save modified resources 4
Figure 48. Save Modified Resources

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

 ticket monster tutorial gfx introduction hibernate add jpa annotations 4
Figure 49. 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.

 ticket monster tutorial gfx introduction hibernate add jpa annotations step2 4
Figure 50. 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.

 ticket monster tutorial gfx introduction run as run on server 4
Figure 51. Run As → Run on Server

Now, deploy the h2console webapp. It can be found in the JBoss EAP quickstarts. You can read more on how to do this in the h2console quickstart.

 ticket monster tutorial gfx introduction quickstarts directory layout 4
Figure 52. Obtain the H2 console app for deployment

You need to deploy the h2console.war application, located in the quickstarts, to the JBoss Application Server. You can deploy this application by copying the WAR file to the $JBOSS_HOME/standalone/deployments directory.

 ticket monster tutorial gfx introduction h2console deployments 4
Figure 53. Deploy the H2 console app

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.

 ticket monster tutorial gfx introduction result run on server 4
Figure 54. Eclipse Browser after Run As → Run on Server

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

 ticket monster tutorial gfx introduction h2console in browser 4
Figure 55. 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.

 ticket monster tutorial gfx introduction h2console select from event 4
Figure 56. 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.

 ticket monster tutorial gfx introduction new class eventservice 4
Figure 57. New Class EventService

Select Finish.

Replace the contents of the class with this sample code:

package org.jboss.examples.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.

 ticket monster tutorial gfx introduction event service copy paste 4
Figure 58. 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.

 ticket monster tutorial gfx introduction source organize imports 4
Figure 59. 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.examples.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.

 ticket monster tutorial gfx introduction organize imports 1 4
Figure 60. javax.ws.rs.core.MediaType
 ticket monster tutorial gfx introduction organize imports 2 4
Figure 61. org.jboss.examples.ticketmonster.model.Event
 ticket monster tutorial gfx introduction organize imports 3 4
Figure 62. javax.ws.rs.Produces
 ticket monster tutorial gfx introduction organize imports 4 4
Figure 63. java.util.List
 ticket monster tutorial gfx introduction organize imports 5 4
Figure 64. javax.inject.Inject
 ticket monster tutorial gfx introduction organize imports 6 4
Figure 65. 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.examples.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.

 ticket monster tutorial gfx introduction project explorer jax rs services 4
Figure 66. 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.

 ticket monster tutorial gfx introduction full publish 4
Figure 67. 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).

 ticket monster tutorial gfx introduction json event results 4
Figure 68. 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.

 ticket monster tutorial gfx introduction new html file 4
Figure 69. 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.

This issue has been corrected in JBoss Developer Studio 6.

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

 ticket monster tutorial gfx introduction new html file correct location 4
Figure 70. 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.

 ticket monster tutorial gfx introduction select html template 4
Figure 71. 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.

 ticket monster tutorial gfx introduction jquery mobile palette 4
Figure 72. 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.

 ticket monster tutorial gfx introduction js css widget 4
Figure 73. Click the JS/CSS widget
 ticket monster tutorial gfx introduction js css widget library versions 4
Figure 74. Select the versions of libraries to add

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.4.4/jquery.mobile-1.4.4.min.css" />
	<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.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.

 ticket monster tutorial gfx introduction jquery mobile page widget 4
Figure 75. 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.

 ticket monster tutorial gfx introduction jquery mobile page 4
Figure 76. 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.4.4/jquery.mobile-1.4.4.min.css" />
	<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.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.

 ticket monster tutorial gfx introduction jquery mobile listview widget 4
Figure 77. Click the Listview widget

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

 ticket monster tutorial gfx introduction jquery mobile listview 4
Figure 78. 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, modify the label values to One, Two and Three respectively, and finally, set 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.4.4/jquery.mobile-1.4.4.min.css" />
	<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.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="#">One</a></li>
				<li><a href="#">Two</a></li>
				<li><a href="#">Three</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.

 ticket monster tutorial gfx introduction jquery mobile template 4
Figure 79. 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.

 ticket monster tutorial gfx introduction jquery mobile results 4
Figure 80. 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.

 ticket monster tutorial gfx introduction mobile browsersim in toolbar 4
Figure 81. 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!

 ticket monster tutorial gfx introduction mobile browsersim 4
Figure 82. 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.

 ticket monster tutorial gfx introduction mobile browsersim devices menu 4
Figure 83. Mobile BrowserSim Devices Menu
 ticket monster tutorial gfx introduction mobile browsersim windows menu 4
Figure 84. Mobile BrowserSim on Windows 7

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

 ticket monster tutorial gfx introduction mobile browsersim custom devices 4
Figure 85. 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.

 ticket monster tutorial gfx introduction mobile browsersim bofa source 4
Figure 86. 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/examples/ticketmonster/controller/

    • src/main/java/org/jboss/examples/ticketmonster/data/

    • src/main/java/org/jboss/examples/ticketmonster/model/Member.java

    • src/main/java/org/jboss/examples/ticketmonster/rest/MemberResourceRESTService.java

    • src/main/java/org/jboss/examples/ticketmonster/service/MemberRegistration.java

    • src/test/java/org/jboss/examples/ticketmonster/test/MemberRegistrationTest.java

  • Generated web content

    • src/main/webapp/index.html

    • src/main/webapp/index.xhtml

    • src/main/webapp/WEB-INF/templates/

  • JSF configuration

    • 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);

Recent Changelog

  • Jan 15, 2015(Vineet Reynolds):Added tutorials for jboss.org
  • Jan 15, 2015(Vineet Reynolds):Prepare for 2.7.0.Final release
  • Jan 15, 2015(Vineet Reynolds):Prepare for development of 2.7.0 SNAPSHOT
  • Jan 15, 2015(Vineet Reynolds):Prepare for 2.7.0.Final release
  • Jan 8, 2015(Vineet Reynolds):WFK2 839 Update JBoss BOM to 6.3.2.GA
  • Jan 8, 2015(Vineet Reynolds):Fixed path to MemberRegistrationTest
  • Nov 28, 2014(Vineet Reynolds):Prepare for development of 2.7.0 SNAPSHOT
  • Nov 28, 2014(Vineet Reynolds):Prepare for 2.7.0.ER2 release
  • Oct 28, 2014(Vineet Reynolds):Prepare for development of 2.7.0 SNAPSHOT
  • Oct 28, 2014(Vineet Reynolds):Prepare for 2.7.0.ER1 release
 
Avg:
Your Rating: