Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development

Similar documents
JBoss Developer Studio 3.0

Guide to Red Hat Enterprise Linux 6 Software Collections

Fuse ESB Enterprise 7.0 Installation Guide

Red Hat JBoss Developer Studio 7.0 User Guide

JBoss Developer Studio 3.0

Red Hat Enterprise Virtualization 3.0 User Portal Guide. Accessing and Using Virtual Machines from the User Portal Edition 1

JBoss Developer Studio 6.0

JBoss Developer Studio 3.0

Red Hat Enterprise Linux 6 Cluster Suite Overview. Overview of the High Availability Add- On for Red Hat Enterprise Linux 6

JBoss Enterprise SOA Platform 5 ESB Tools Reference Guide. This guide is for developers Edition 5.3.1

JBoss Enterprise BRMS Platform 5 BRMS Business Process Management Guide

JBoss Communications Platform 5.0 SIP Presence Service User Guide

Red Hat JBoss Core Services Apache HTTP Server 2.4 Apache HTTP Server Installation Guide

Discovery, Reporting, Capacity and Utilization Edition 1. ManageIQ Documentation Team

JBoss Enterprise Data Services 5 Teiid Designer User Guide. for Developers Edition 5.3.1

Red Hat Enterprise Linux OpenStack Platform 7 OpenStack Data Processing

Red Hat JBoss Developer Studio 4.1 Smooks Developer Tools Reference Guide

JBoss Communications Platform 1.2 Platform Installation Guide

Red Hat Subscription Management All Subscription Docs Quick Registration for RHEL

Red Hat Subscription Asset Manager 1.2 Installation Guide. Installing and Using Red Hat Subscription Asset Manager Edition 3

JBoss Enterprise SOA Platform 5.2 Rule Flow Component Guide. for Business Rules Developers

Red Hat Enterprise Virtualization 3.2 Administration Guide

JBoss Developer Studio 4.1

MASTERTAG DEVELOPER GUIDE

Red Hat Directory Server 8.2 Using the Directory Server Console

Fedora 20 Networking Guide

JBoss Enterprise Application Platform 6.2 Development Guide

Red Hat Enterprise Linux 6 Logical Volume Manager Administration. LVM Administrator Guide

JBoss Enterprise Application Platform 5 Negotiation User Guide. for JBoss Enterprise Application Platform 5 Edition 5.2.0

Introduction: The Xcode templates are not available in Cordova or above, so we'll use the previous version, for this recipe.

JBoss Enterprise Application Platform 4.3 Common Criteria Configuration Guide

Red Hat Customer Portal Current Customer Portal Subscription Management

JBoss Enterprise Application Platform 6 Development Guide

IBM TRIRIGA Anywhere Version 10 Release 4. Installing a development environment

JBoss Enterprise Application Platform 6.1 Development Guide

Building and Using Web Services With JDeveloper 11g

Fedora 22 Networking Guide

Red Hat Developer Toolset 1.1

JBoss Communications Platform 5.1 SIP Load Balancer User Guide

Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator

Counter-Strike Game Server Management Module

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

JBoss Enterprise Application Platform 6.2 Administration and Configuration Guide

Red Hat Enterprise Virtualization 3.0 Quick Start Guide

Tutorial: BlackBerry Object API Application Development. Sybase Unwired Platform 2.2 SP04

Pay with Amazon Integration Guide

JBoss Enterprise Application Platform 6

unisys ClearPath eportal Developer 6.1 Unisys Multi-Device App Developer s Guide March

Site Configuration Mobile Entrée 4

Getting Started using the SQuirreL SQL Client

Red Hat Enterprise Linux 7 High Availability Add-On Administration. Configuring and Managing the High Availability Add-On

ovirt 3.0 Installation Guide

Hello World RESTful web service tutorial


Red Hat Enterprise Virtualization 3.2 Installation Guide

DiskPulse DISK CHANGE MONITOR

Plesk for Windows Copyright Notice

Drupal CMS for marketing sites

JBoss Enterprise Application Platform 5 HTTP Connectors Load Balancing Guide

How To Use Titanium Studio

McAfee Cloud Identity Manager

How To Change Your Site On Drupal Cloud On A Pcode On A Microsoft Powerstone On A Macbook Or Ipad (For Free) On A Freebie (For A Free Download) On An Ipad Or Ipa (For

Managing Linux Servers with System Center 2012 R2

ISL Online Integration Manual

JBoss Enterprise Application Platform 5 Performance Tuning Guide

J j enterpririse. Oracle Application Express 3. Develop Native Oracle database-centric web applications quickly and easily with Oracle APEX

Quick Start Guide Mobile Entrée 4

Parallels Virtual Automation 6.1

Making Web Application using Tizen Web UI Framework. Koeun Choi


Customising Your Mobile Payment Pages

Log Analyzer Reference

Apple Applications > Safari

Tutorial: Mobile Business Object Development. SAP Mobile Platform 2.3 SP02

Red Hat CloudForms 3.2 NetApp Storage Integration Guide

Sophos Mobile Control Startup guide. Product version: 3.5

Sophos Mobile Control Startup guide. Product version: 3

Wakanda Studio Features

Novell Identity Manager

Red Hat JBoss Developer Studio 7.0 JBoss SOAP Web Services User Guide

McAfee Cloud Identity Manager

Example. Represent this as XML

Hypercosm. Studio.

UP L18 Enhanced MDM and Updated Protection Hands-On Lab

TIBCO Hawk SNMP Adapter Installation

Visualizing a Neo4j Graph Database with KeyLines

Core Protection for Virtual Machines 1

Parallels Plesk Control Panel

AUTOMATED CONFERENCE CD-ROM BUILDER AN OPEN SOURCE APPROACH Stefan Karastanev

ORACLE BUSINESS INTELLIGENCE WORKSHOP

Parallels Panel. Parallels Small Business Panel 10.2: User's Guide. Revision 1.0

FlexSim LAN License Server

JBoss Operations Network 3.1 Deploying Applications and Content

Adobe Dreamweaver CC 14 Tutorial

Parallels Plesk Panel

Transcription:

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development for use with JBoss Enterprise Application Platform Edition 2.0.0 Jay Balunas

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development for use with JBoss Enterprise Application Platform Edition 2.0.0 Jay Balunas Red Hat jbalunas@redhat.co m

Legal Notice Copyright 2012 Red Hat, and others. T his document is licensed by Red Hat under the Creative Commons Attribution-ShareAlike 3.0 Unported License. If you distribute this document, or a modified version of it, you must provide attribution to Red Hat, Inc. and provide a link to the original. If the document is modified, all Red Hat trademarks must be removed. Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law. Red Hat, Red Hat Enterprise Linux, the Shadowman logo, JBoss, MetaMatrix, Fedora, the Infinity Logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries. Linux is the registered trademark of Linus Torvalds in the United States and other countries. Java is a registered trademark of Oracle and/or its affiliates. XFS is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries. MySQL is a registered trademark of MySQL AB in the United States, the European Union and other countries. Node.js is an official trademark of Joyent. Red Hat Software Collections is not formally related to or endorsed by the official Joyent Node.js open source or commercial project. T he OpenStack Word Mark and OpenStack Logo are either registered trademarks/service marks or trademarks/service marks of the OpenStack Foundation, in the United States and other countries and are used with the OpenStack Foundation's permission. We are not affiliated with, endorsed or sponsored by the OpenStack Foundation, or the OpenStack community. All other trademarks are the property of their respective owners. Abstract This book is a guide to getting started with HTML5 and REST. This approach uses a pure HTML5 based front-end that interacts with server-side content through REST ful endpoints.

Table of Contents Table of Contents. Preface........................................................................................... 3.......... 1. Document Conventions 3 1.1. T ypographic Conventions 3 1.2. Pull-quote Conventions 4 1.3. Notes and Warnings 5 2. Getting Help and Giving Feedback 5 2.1. Do You Need Help? 5 2.2. Give us Feedback 6. Chapter......... 1... Getting........ Started........................................................................ 7.......... 1.1. Prerequisites 7 Prerequisites 7 1.2. Creating, Deploying, and T esting the Application 7 1.2.1. Using the Command Line 7 Deploying the Application 8 Testing 9 1.2.2. Using JBoss Developer Studio 9 Testing 11 1.3. Application in Action 13 JBoss Developer Studio Browser Simulator 16. Chapter......... 2... Further........ Information....................................................................... 18........... 2.1. Client Source Code 18 2.1.1. HTML5 Semantic Tags and Structure 19 2.1.2. HT ML5 Form API 19 2.1.3. app.js File 22 2.1.4. CSS Files 24 2.1.5. T hird Party Libraries 25 2.1.6. JAX-RS Endpoint Source Code 26 2.1.6.1. Member.java 26 2.1.6.2. MemberService.java 26 2.1.6.3. JSONP Support 28. Revision......... History................................................................................. 30............ Index.......................................................................................... 30........... F 30 H 30 1

2 Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development

Preface Preface 1. Document Conventions T his manual uses several conventions to highlight certain words and phrases and draw attention to specific pieces of information. In PDF and paper editions, this manual uses typefaces drawn from the Liberation Fonts set. T he Liberation Fonts set is also used in HTML editions if the set is installed on your system. If not, alternative but equivalent typefaces are displayed. Note: Red Hat Enterprise Linux 5 and later include the Liberation Fonts set by default. 1.1. Typographic Conventions Four typographic conventions are used to call attention to specific words and phrases. T hese conventions, and the circumstances they apply to, are as follows. Mono-spaced Bold Used to highlight system input, including shell commands, file names and paths. Also used to highlight keys and key combinations. For example: T o see the contents of the file m y_next_bestselling_novel in your current working directory, enter the cat m y_next_bestselling_novel command at the shell prompt and press Enter to execute the command. The above includes a file name, a shell command and a key, all presented in mono-spaced bold and all distinguishable thanks to context. Key combinations can be distinguished from an individual key by the plus sign that connects each part of a key combination. For example: Press Enter to execute the command. Press Ctrl+Alt+F2 to switch to a virtual terminal. T he first example highlights a particular key to press. T he second example highlights a key combination: a set of three keys pressed simultaneously. If source code is discussed, class names, methods, functions, variable names and returned values mentioned within a paragraph will be presented as above, in m ono-spaced bold. For example: File-related classes include filesystem for file systems, file for files, and dir for directories. Each class has its own associated set of permissions. Proportional Bold T his denotes words or phrases encountered on a system, including application names; dialog-box text; labeled buttons; check-box and radio-button labels; menu titles and submenu titles. For example: Choose System Preferences Mouse from the main menu bar to launch Mouse Preferences. In the Buttons tab, select the Left-handed m ouse check box and click Close to switch the primary mouse button from the left to the right (making the mouse suitable for use in the left hand). T o insert a special character into a gedit file, choose Applications Accessories 3

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development Character Map from the main menu bar. Next, choose Search Find from the Character Map menu bar, type the name of the character in the Search field and click Next. T he character you sought will be highlighted in the Character T able. Double-click this highlighted character to place it in the T ext to copy field and then click the Copy button. Now switch back to your document and choose Edit Paste from the gedit menu bar. T he above text includes application names; system-wide menu names and items; application-specific menu names; and buttons and text found within a GUI interface, all presented in proportional bold and all distinguishable by context. Mono-spaced Bold Italic or Proportional Bold Italic Whether mono-spaced bold or proportional bold, the addition of italics indicates replaceable or variable text. Italics denotes text you do not input literally or displayed text that changes depending on circumstance. For example: T o connect to a remote machine using ssh, type ssh username@ domain.name at a shell prompt. If the remote machine is example.com and your username on that machine is john, type ssh john@ exam ple.com. T he m ount -o rem ount file-system command remounts the named file system. For example, to remount the /home file system, the command is mount -o remount /home. T o see the version of a currently installed package, use the rpm -q package command. It will return a result as follows: package-version-release. Note the words in bold italics above: username, domain.name, file-system, package, version and release. Each word is a placeholder, either for text you enter when issuing a command or for text displayed by the system. Aside from standard usage for presenting the title of a work, italics denotes the first use of a new and important term. For example: Publican is a DocBook publishing system. 1.2. Pull-quote Conventions T erminal output and source code listings are set off visually from the surrounding text. Output sent to a terminal is set in mono-spaced roman and presented thus: books Desktop documentation drafts mss photos stuff svn books_tests Desktop1 downloads images notes scripts svgs Source-code listings are also set in m ono-spaced rom an but add syntax highlighting as follows: 4

Preface package org.jboss.book.jca.ex1; import javax.naming.initialcontext; public class ExClient { public static void main(string args[]) throws Exception { InitialContext inictx = new InitialContext(); Object ref = inictx.lookup("echobean"); EchoHome home = (EchoHome) ref; Echo echo = home.create(); System.out.println("Created Echo"); } } System.out.println("Echo.echo('Hello') = " + echo.echo("hello")); 1.3. Notes and Warnings Finally, we use three visual styles to draw attention to information that might otherwise be overlooked. Note Notes are tips, shortcuts or alternative approaches to the task at hand. Ignoring a note should have no negative consequences, but you might miss out on a trick that makes your life easier. Important Important boxes detail things that are easily missed: configuration changes that only apply to the current session, or services that need restarting before an update will apply. Ignoring a box labeled Important will not cause data loss but may cause irritation and frustration. Warning Warnings should not be ignored. Ignoring warnings will most likely cause data loss. 2. Getting Help and Giving Feedback 2.1. Do You Need Help? If you experience difficulty with a procedure described in this documentation, visit the Red Hat Customer Portal at http://access.redhat.com. T hrough the customer portal, you can: search or browse through a knowledgebase of technical support articles about Red Hat products. submit a support case to Red Hat Global Support Services (GSS). access other product documentation. 5

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development Red Hat also hosts a large number of electronic mailing lists for discussion of Red Hat software and technology. You can find a list of publicly available mailing lists at https://www.redhat.com/mailman/listinfo. Click on the name of any mailing list to subscribe to that list or to access the list archives. 2.2. Give us Feedback If you find a typographical error, or know how this guide can be improved, we would love to hear from you. Submit a report in Bugzilla against the product JBoss_Enterprise_WFK_Platform_2 and the component doc-getting-started-with-ht ML5-Mobile-Web-Developm ent. T he following link will take you to a pre-filled bug report for this product: http://bugzilla.redhat.com/. Fill out the following template in Bugzilla's Description field. Be as specific as possible when describing the issue; this will help ensure that we can fix it quickly. Document URL: Section Number and Name: Describe the issue: Suggestions for improvement: Additional information: Be sure to give us your name so that you can receive full credit for reporting the issue. 6

Chapter 1. Getting Started Chapter 1. Getting Started 1.1. Prerequisites This guide is a walkthrough of creating a new HTML5 mobile application using a Maven archetype, deploying it to the JBoss Enterprise Application Platform 6, and executing server/client test suites. It also provides an overview of basic behaviour of the application including both command line and JBoss Developer Studio instructions. Prerequisites Java 6.0 (Java SDK 1.6) Maven 3+ JBoss Enterprise Application Platform 6 JBoss Developer Studio 5 HT ML5-compatible browser: Chrome 14+ Safari 5+ Firefox 5+ Internet Explorer 9+ Mobile web support is limited to Android and IOS devices but may also run on HP and Blackberry devices. 1.2. Creating, Deploying, and Testing the Application T here are multiple ways to create the example application from the Maven archetype. T he archetype is located in the Maven central repository. 1.2.1. Using the Command Line 1. Step One cd into the directory the project will be created in. 2. Step Two Run the following Maven archetype command: mvn archetype:generate \ -DarchetypeArtifactId=jboss-html5-mobile-archetype \ -DarchetypeGroupId=org.jboss.aerogear.archetypes \ -DarchetypeVersion=1.0.0.M4 3. Step T hree Maven downloads the archetype and its dependencies and prompts for more information: GroupID the base package for the project ArtifactID the name of the project Version 7

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development the starting version of the project Package if it is different from the GroupID Select the required values and press 'Y' when prompted. Result The project is created in a directory named after the ArtifactID. Check the readme.md for extra information. This example uses the ExampleDS, and a single table. The table suffix can be changed by passing "- DtableSuffix=<your_desired_suffix> when running m vn archetype:generate. Use this when running multiple application generated by the same archetype, or other examples that use the same table name. Deploying the Application 1. Start the JBoss container To start the JBoss container on Linux, run: $JBOSS_HOME/bin/standalone.sh To start the JBoss container on Windows, run: $JBOSS_HOME/bin/standalone.bat Note Add -b 0.0.0.0 to these commands to allow external clients such as phones, tablets, and desktops to connect through your local network. For example: $JBOSS_HOME/bin/standalone.sh -b 0.0.0.0 2. Create the archive Run this command to create the archive: mvn package 3. Deploy Deploy the artifact by executing this command: mvn jboss-as:deploy Result T he application can be accessed at: http://localhost:8080/<artifactid> where <artifactid> is the equivalent to what was entered at creation time. 8

Chapter 1. Getting Started 4. Undeploy Run this command to undeploy: mvn jboss-as:undeploy Testing T his application uses Arquillian for in-container testing of services, and QUnit for verifying JavaScript. Please see Chapter 2, Further Information for more information. By default, tests with Arquillian are configured to be skipped. T he sample test is an Arquilliant test, which requires the use of a container. Use Procedure 1.1, Arquillian testing to run the test. Procedure 1.1. Arquillian testing 1. Step One Start the container instance. On Linux, run: $JBOSS_HOME/bin/standalone.sh To start the JBoss container on Windows, run: $JBOSS_HOME/bin/standalone.bat 2. Step Two Run the test goal with the following profile activated: mvn clean test -Parq-jbossas-remote QUnit is a JavaScript unit testing framework used and built by jquery. This application includes a set of QUnit tests in order to verify JavaScript that is core to this HTML5 application. To execute a QUnit test case, load the following HTML in the browser to be tested: <app-root>/src/test/qunit/index.html 1.2.2. Using JBoss Developer Studio T he following instructions assume JBoss Developer Studio 5 is installed and JBoss Enterprise Application Platform 6 is set up as a server in the IDE. JBoss Developer Studio 5 introduces a splash screen called JBoss Central. T his gives quick access to JBoss quickstarts, tutorials, and more. Procedure 1.2. JBoss Developer Studio 1. Step One Select the HT ML 5 project button and use the wizard to create the project. 2. Step Two Enter the following details into the Wizard: Project Name Package T arget Runtime Directory to create project in. 9

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development Click Finish 3. Step T hree Check that the next page has been pre-populated with values from the previous screen and update as required. Click Finish Result The application is created and imported as a new project in the workspace. Procedure 1.3. Deploying the Project with JBoss Developer Studio 1. Step One If the instructions were followed correctly, there should be a server tab that looks like this: Figure 1.1. Server tab Right click on JBoss Enterprise Application Platform 6 Runtim e Server and select Add and Rem ove 2. Step Two In the Wizard that appears, select the application on the left and add it to the right. 3. Step T hree Click Finished. Result T he application can be started, stopped, republished, and debugged from here. 10

Chapter 1. Getting Started Figure 1.2. Management tab 4. Step Four Testing Start the server and access it at: http://localhost:8080/<artifactid> T his application uses Arquillian for in-container testing of services, and QUnit for verifying JavaScript. See Chapter 2, Further Information for more information. Arquillian's in-container tests can be executed like any JUnit test case in JBoss Developer Studio; except that the JBoss container should be started following the JBoss Developer Studio instructions. Once this has been done, follow Procedure 1.4, JBoss Developer Studio and Arquillian to continue testing. Procedure 1.4. JBoss Developer Studio and Arquillian 1. Step One Navigate to MemberRegistrationT est.java: 11

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development Figure 1.3. Management tab 2. Step Two Right click on the file and select Run As and then JUnit Test. Result T he console shows the tests being deployed and executed. Procedure 1.5. QUnit and JBoss Developer Studio QUnit is a JavaScript unit testing framework used and built by jquery. This application includes a set of QUnit tests in order to verify JavaScript that is core to this HTML5 application. Step One Navigate to the QUnit index.html file as shown below; right click on this and choose to Open With --> Web Browser. 12

Chapter 1. Getting Started Figure 1.4. QUnit Index Result T he default browser launches, loading and executing the QUnit tests in the process. T he browser window will look like this: Figure 1.5. QUnit Browser 1.3. Application in Action Now that the application is running, the following are some of the application screens on both desktop 13

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development and mobile devices. This is the application's main page when viewed within a desktop browser. This form can be used to create new members, and show all current members in a table at the bottom of the page. jquery is being used to make JAX-RS requests to the JBoss Enterprise Application Platform 6, handle POST and GET requests/responses, and handling errors. HT ML5 form and page elements are also used to help with client-side validation. Figure 1.6. Main Page This is the same page from an iphone or Android perspective. 14

Chapter 1. Getting Started Figure 1.7. Mobile Here jquery Mobile is used to help transform the same basic content into a mobile web optimized application. In the mobile version, "pages" are created that jquery mobile then transitions to as we make various requests. T his application uses the same JAX-RS endpoints and access JavaScript as the desktop, allowing for reuse across clients. Since those HT ML5 form elements are being used, the iphone will provide users with the correct keyboard based on the data type requested. 15

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development Figure 1.8. Mobile JBoss Developer Studio Browser Simulator JBoss Developer Studio 5 has a browser simulator that mimics different mobile browsers. T his means the application screen can be quickly checked for adjustments before testing in emulators, or physical hardware. Procedure 1.6, JBoss Developer Studio Browser Simulator explains how to use the BrowserSim function. Procedure 1.6. JBoss Developer Studio Browser Simulator 1. Step One 16

Chapter 1. Getting Started Open JBoss Developer Studio 5 and navigate to the index.htm l file. 2. Step Two Right click index.htm l and choose Open With BrowserSim Result A new window like Figure 1.9, Mobile opens on the loading page. The browsers to mimic can then be manipulated using the Devices menu. Figure 1.9. Mobile 17

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development Chapter 2. Further Information T his chapter details the significant files, libraries, and source code for the AeroGear archetype and quickstarts that are part of the JBoss Enterprise Application Platform quickstart suite called kitchensinkhtml5-mobile. 2.1. Client Source Code Source <project-root>/src/m ain/webapp/index.htm l T his application follows the single page application approach. T his means the entire client application can be encapsulated into a single html file. T his approach follows the "responsive design" concept, which means the application can be adjusted based on the client accessing it. Header The header of the document shows that this is a HTML5 file by the inclusion of the <!DOCTYPE html> tag. The <meta> tags are then set to define the scaling and viewport properties for our application. In this case, the initial width of the page is set to the width of the device, and the initial scale to 1. Following this is the 3rd party libraries being used. See Section 2.1.5, T hird Party Libraries for more information on these libraries. The app.js file contains the majority of the JavaScript logic, which is also pulled in. The README has more information about minifying the app.js. <!DOCTYPE html> <html> <head> <title>aerogear QuickStart</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <!-- Set viewport scaling and zoom features --> <meta name="viewport" content="width=device-width, initial-scale=1"/> <!-- Include the full development version of Modernizr. In production, you should use a --> <!-- minimized custom build to reduce file size --> <script type="text/javascript" src="js/libs/modernizr-2.5.3.min.js"></script> <script type="text/javascript" src="js/libs/underscore-min.js"></script> <!-- Minification - See Readme for details --> <!-- For minification, comment out this file --> <script type="text/javascript" src="js/app.js"></script> <!-- For minification, uncomment this file --> <!-- <script type="text/javascript" src="js/app.min.js"></script> --> Following the heading is the initialization logic for the application. T his is best viewed in the source code starting from line 44. This logic does a couple of different things: 18 1. Demonstrates how to use the yepnope library to conditionally load the jquery-m in.js file from a CDN, or fallback to a local non-minified version for development. 2. Uses Modernizr and new media queries to determine if this is a mobile device.

Chapter 2. Further Information Using this information jquery mobile support and which CSS files to include in the app is toggled. 3. When these are complete, the initial event listeners are set up, and the member table from the server is populated. 2.1.1. HTML5 Semantic Tags and Structure HTML5 has a suite of new semantic-based tags. This means descriptive tags that better described the contained content, such as <section>, <footer>, <aside> for example. T hese make it possible to easily break up the structure of your project without resulting in many <div id=""> in the document These semantic tags are used in the quickstart application to break up the different sections of the page, define the footer, and various article in the application. Breaking up the desktop version of the application makes moving to a mobile browser using jquery Mobile easier. Each article is a different page, the aside is the "info" link, for example. <section> <article/> <article/> <article/> <aside/> <footer/> </section> CSS rules can also be used to 'hide' parts of the page based on the client type and format. This is helped by the media queries described previously, and also by how jquery Mobile defines its page sections. 2.1.2. HTML5 Form API A new feature of HTML5 and its related specifications are the HTML form elements and APIs. Several of the new features are used in the member form of the quickstart. 19

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development <fieldset> <legend>register a member:</legend> <div> <label for="name">name:</label> <input type="text" name="name" id="name" placeholder="your Name" required autofocus/> </div> <div> <label for="email">email:</label> <input type="email" name="email" id="email" placeholder="your Email" required/> </div> <div> <label for="phonenumber">phone #:</label> <input type="tel" name="phonenumber" id="phonenumber" pattern="[0-9]{10,12}" placeholder="your Phone #" required/> </div> <div id="formmsgs"></div> <div data-role="controlgroup" data-type="horizontal"> <input type="submit" name="register" id="register" value="register"/> <input type="button" name="cancel" id="cancel" value="cancel"/> </div> </fieldset> Input T ype Attribute By setting the input type attribute based on the type of field it represents, browsers can make various optimizations. Mobile browsers that support this attribute will display special optimized keyboards - as shown below. Some desktop browsers (such as Webkit and Firefox) will automatically validate the field as well; for example checking that the field is a valid email. 20

Chapter 2. Further Information Figure 2.1. Mobile Placeholder and Autofocus T he "placeholder" and "autofocus" attributes can also be seen. T he placeholder attribute allows you to set a default text string that will display in your field when there is no value. This is valuable for mobile devices where you can shrink or eliminate regular labels for fields. The autofocus attribute allows the keyboard/input focus to automatically be on the specified field. Input Validation Another critical update to the form fields is around built-in client validation. It features attribute such as required and pattern. Along with input type, these allow browsers that support it to 21

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development validate fields on the client side. Currently this is limited to Chrome, Safari,a nd Firefox. Note Any validation entered here should match the Bean Validation from Member.java class. 2.1.3. app.js File Source <project-root>/src/m ain/webapp/js/app.js T he app.js file contains the example's core JavaScript logic, and handles the REST ful requests to the server, as well as handling the updates to the UI based on them. updatemembert able T his method performs a simple GET call to the server, calls the buildmemberrows() method with the response data. /* Uses JAX-RS GET to retrieve current member list */ function updatemembertable() { $.ajax({ url: "rest/members", cache: false, success: function(data) { $('#members').empty().append(buildmemberrows(data)); }, error: function(error) { //console.log("error updating table -" + error.status); } }); } buildmemberrows and getmembert emplate Using underscore.js these methods retrieve the member.tmpl file from the server and populates it with the json data retrieved from the updatemembert able method. T he output of this process is the table body for the member table on the application's main page. For more on what underscore.js does check out the 3rd party section below and the project's home page. 22

Chapter 2. Further Information [ /* Get the member template */ function getmembertemplate() { $.ajax({ url: "tmpl/member.tmpl", datatype: "html", success: function( data ) { $( "head" ).append( data ); updatemembertable(); } }); } /* Builds the updated table for the member list */ function buildmemberrows(members) { return _.template( $( "#member-tmpl" ).html(), {"members": members}); } registermember This method does the heavy lifting of creating a new member on the server using a POST request, and handling any error responses by highlighting fields that are not valid. Besides basic steps like clearing out older messages, if the request is successful it triggers the member table to update. 23

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development [ function registermember(memberdata) { //clear existing msgs $('span.invalid').remove(); $('span.success').remove(); $.ajax({ url: 'rest/members', contenttype: "application/json", datatype: "json", type: "POST", data: JSON.stringify(memberData), success: function(data) { //console.log("member registered"); //clear input fields $('#reg')[0].reset(); //mark success on the registration form $('#formmsgs').append($('<span class="success">member Registered</span>')); updatemembertable(); }, error: function(error) { if ((error.status == 409) (error.status == 400)) { //console.log("validation error registering user!"); var errormsg = $.parsejson(error.responsetext); $.each(errormsg, function(index, val) { $('<span class="invalid">' + val + '</span>').insertafter($('#' + index)); }); } else { //console.log("error - unknown server issue"); $('#formmsgs').append($('<span class="invalid">unknown server error</span>')); } } }); } If, on the other hand the request fails for some reason the method processes the JSON response and based on the JAX-RS response status displays validation errors to the user based on the field, and message provided by the server. For more on the response codes and format see the server side section below on the MemberService.java class. 2.1.4. CSS Files Source <project-root>/src/m ain/webapp/css T his example includes two CSS files; screen.css, and m.screen.css. One is for desktop and the other for 24

Chapter 2. Further Information mobile. These contain the various styles needed for the application. The following is an example of using the new CSS3 selectors to make styling table cells easier. /* Using new CSS3 selectors for styling*/ #members tr:nth-child(odd) { background: #f4f3f3; } #members tr:nth-child(even) { background: #ffffff; } This code allow odd rows to be styled easily. 2.1.5. Third Party Libraries Source <project-root>/client/src/m ain/webapp/js/libs T his application uses several 3rd party libraries to assist with basic programming. T hese libraries represent just one combination, and there are many other quality libraries out there. All of these libraries are packaged in both development and minized versions. Use the minimized versions in production for best performance, and development in the development phase. jquery Mobile http://jquerymobile.com One of several JavaScript mobile framework projects available. T his is a very complete framework for mobile devices and has a great range of device support. This also means it is one of the larger libraries out there so performance should be considered. It does a great job of getting you running and is backed by the jquery project. jquery http://jquery.com One of the most popular general purpose JavaScript projects available. T his example uses it mainly for DOM manipulation and ajax requests. Modernizr http://www.modernizr.com T he Moderizr library is primarily used to check device, and browser capabilities allowing you to have a fine grain of control over your application no matter what device or client may be accessing it. T his library integrates with yepnope to combine feature detection with media queries and conditional resource loading. Yepnope http://www.yepnopejs.com/ As the yepnope web site says it is an asynchronous conditional resource loader that's superfast, and allows you to load only the scripts that your users need. Our example uses it with modernizr to control resource loading and behavior based on the client accessing the application. 25

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development Underscore.js Underscore.js This is great utility library that has many great functions. This examples primary use for it is to process templating of new member table rows by dynamically loading and populating the member.tmpl file. 2.1.6. JAX-RS Endpoint Source Code T he server side of this application consists of a basic domain model using Bean Validation, and JAX-RS service endpoints using REST Easy to provide access. 2.1.6.1. Member.java Source <projectroot>/src/m ain/java/org/jboss/as/quickstarts/htm l5_m obile/m odel/mem ber.java @Entity @ XmlRootElement @Table(name = "Member_html5mobi", 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 the 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 table name is defined for this object, and specifies that the Email field must be unique in the data table. This will come into play later when it is needed to validate this in the JAX-RS services, and process the response codes effectively. 2.1.6.2. MemberService.java Source <project- 26

Chapter 2. Further Information root>/src/m ain/java/org/jboss/as/quickstarts/htm l5_m obile/rest/mem berservice.java T his class contains the actual REST ful endpoint definitions and processing code. It uses REST Easy, which is the JBoss implementation of the JAX-RS specification, to make this easy to do, and is configured using annotations. @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(MediaType.APPLICATION_JSON) public List<Member> listallmembers()... @GET @Path("/{id:[0-9][0-9]*}") @ Produces(MediaType.APPLICATION_JSON) public Member lookupmemberbyid(@ PathParam("id") long id) {... The methods above define the different ways of "getting" data from the service. There are two ways of creating more members. One approach uses the traditional POST approach with the @POST annotation. While the other uses the GET method with an additional /new path. This can be used for JSONP support. The GET method uses query parameters while the POST method uses form parameters. Both of these methods delegate to the same method that processes the request. A full list of members, and invidual members can be accessed, either in XML or JSON format. These are automatically marshaled from one form to another. @POST @ Consumes(MediaType.APPLICATION_JSON) @ Produces(MediaType.APPLICATION_JSON) public Response createmember(member member) {... JAX-RS allows the 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); 27

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development Using those values it then constructs a new member object. try { //Validates member using bean validation validatemember(member); T he 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(s) that are not valid, and the error message associated with them from model class. It is also very important to set the response code correctly. In this case, 400 BAD REQUEST is used for standard constraints, and 409 CONFLICT for 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 HT T P 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();... 2.1.6.3. JSONP Support Source <projectroot>/src/m ain/java/org/jboss/as/quickstarts/htm l5_m obile/util/jsonprequestf ilter.java JSONP support makes requests accessible across domains by adding a callback function to the response. T his may be necessary in certain situations like requesting information from a sub-domain of your site. 28

Chapter 2. Further Information Misc Source <projectsource>src/m ain/java/org/jboss/as/quickstarts/htm l5_m obile/rest/jaxrsactivato r.java T he JaxRsActivator class does two things. It initializes JAX-RS without the need of a web.xml file, and defines the root path for all other JAX-RS HTTP call like this: @ApplicationPath("/rest") public class JaxRsActivator extends Application { /* class body intentionally left blank */ } Source <projectsource>/src/m ain/java/org/jboss/as/quickstarts/htm l5_m obile/util/resources.j ava The Resources class uses CDI to alias Java EE resources, such as the persistence context, to CDI beans. T his makes them available to all other CDI beans, ala MemberSerice.java. 29

Red Hat JBoss Web Framework Kit 2 Getting Started With HTML5 Mobile Web Development Revision History Revision 2.0.0-2.4 05 T ue Dec 17 2013 Rüdiger Landmann Rebuild with Publican 4.0.0 Revision 2.0.0-2 Fri Jun 22 2012 Rebecca Newton Pushing live for JBoss Web Framework Kit 2.0.0 GA. Index F feedback - contact information for this manual, Give us Feedback H help - getting help, Do You Need Help? 30