Upload
vuongtuyen
View
222
Download
1
Embed Size (px)
Citation preview
Mastering XPagesIBM’s Best-Selling Guide to XPages Development—Now Updated and Expanded for Lotus Notes/Domino 9.0.1By Martin Donnelly, Mark Wallace, Tony McGuckin
ISBN-10: 0-13-337337-1
ISBN-13: 978-0-13-337337-0
Three key members of the IBM XPages team have
brought together comprehensive knowledge for
delivering outstanding solutions. They have added
several hundred pages of new content, including
four new chapters. Drawing on their unsurpassed
experience, they present new tips, samples, and
best practices refl ecting the platform’s growing
maturity. Writing for both XPages newcomers and
experts, they cover the entire project lifecycle,
including problem debugging, performance
optimization, and application scalability.
Related Books of Interest
Sign up for the monthly IBM Press newsletter at
ibmpressbooks.com/newsletters
XPages Portable Command Guide A Practical Primer for XPages Application Development, Debugging, and PerformanceBy Martin Donnelly, Maire Kehoe, Tony
McGuckin, Dan O’Connor
ISBN-10: 0-13-294305-0
ISBN-13: 978-0-13-294305-5
A perfect portable XPages quick reference
for every working developer. Straight from the
experts at IBM®, XPages Portable Command Guide offers fast access to working code,
tested solutions, expert tips, and example-
driven best practices. Drawing on their
unsurpassed experience as IBM XPages lead
developers and customer consultants, the
authors explore many lesser known facets
of the XPages runtime, illuminating these
capabilities with dozens of examples that solve
specifi c XPages development problems. Using
their easy-to-adapt code examples, you can
develop XPages solutions with outstanding
performance, scalability, fl exibility, effi ciency,
reliability, and value.
Related Books of Interest
Visit ibmpressbooks.com
for all product information
Mobile StrategyHow Your Company Can Win by Embracing Mobile TechnologiesBy Dirk Nicol
ISBN-10: 0-13-309491-X
ISBN-13: 978-0-13-309491-6
Mobile Strategy gives IT leaders the ability to
transform their business by offering all the
guidance they need to navigate this complex
landscape, leverage its opportunities, and protect
their investments along the way. IBM’s Dirk Nicol
clearly explains key trends and issues across
the entire mobile project lifecycle. He offers
insights critical to evaluating mobile technolo-
gies, supporting BYOD, and integrating mobile,
cloud, social, and big data. Throughout, you’ll fi nd
proven best practices based on real-world case
studies from his extensive experience with IBM’s
enterprise customers.
XPages Extension Library A Step-by-Step Guide to the Next Generation of XPages ComponentsBy Paul Hannan, Declan Sciolla-Lynch, Jeremy
Hodge, Paul Withers, Tim Tripcony
ISBN-10: 0-13-290181-1
ISBN-13: 978-0-13-290181-9
XPages Extension Library is the fi rst and only
complete guide to Domino development with
this library; it’s the best manifestation yet of
the underlying XPages Extensibility Framework.
Complementing the popular Mastering XPages,
it gives XPages developers complete information
for taking full advantage of the new components
from IBM.
Combining reference material and practical use
cases, the authors offer step-by-step guidance for
installing and confi guring the XPages Extension
Library and using its state-of-the-art applications
infrastructure to quickly create rich web applica-
tions with outstanding user experiences.
Related Books of Interest
Sign up for the monthly IBM Press newsletter at
ibmpressbooks.com/newsletters
IBM WebSphere DataPower SOA Appliance HandbookHines, Rasmussen, Ryan,
Kapadia, Brennan
ISBN: 0-13-343041-3
Dynamic SOA and BPMBest Practices for Business Process
Management and SOA Agility
Fiammante
ISBN: 0-13-701891-6
WebSphere EngineeringA Practical Guide for WebSphere
Support Managers and Senior
Consultants
Ding
ISBN: 0-13-714225-0
Executing SOAA Practical Guide for the Service-Oriented Architectby Norbert Bieberstein, Robert G. Laird,
Dr. Keith Jones, and Tilak Mitra
ISBN: 0-13-235374-1
ISBN-13 978-0-13-235374-1
In Executing SOA, four experienced SOA
implementers share realistic, proven, “from-the-
trenches” guidance for successfully delivering on
even the largest and most complex SOA initiative.
This book follows up where the authors’ best-
selling Service-Oriented Architecture Compass
left off, showing how to overcome key obstacles
to successful SOA implementation and identifying
best practices for all facets of execution—
technical, organizational, and human. Among
the issues it addresses: introducing a services
discipline that supports collaboration and
information process sharing; integrating services
with preexisting technology assets and strategies;
choosing the right roles for new tools; shifting
culture, governance, and architecture; and
bringing greater agility to the entire organizational
lifecycle, not just isolated projects.
SOA GovernanceAchieving and Sustaining
Business and IT Agility
Brown, Laird, Gee, Mitra
ISBN: 0-13-714746-5
Application Architecture for WebSphereA Practical Approach to Buiding
WebSphere Applications
Bernal
ISBN: 0-13-712926-2
WebSphere Application Server Administration Using JythonGibson, McGrath, Bergman
ISBN: 0-13-358008-3
This page intentionally left blank
Modern Web Development with IBM® WebSphere®
This page intentionally left blank
Modern Web Development with IBM® WebSphere®
IBM Press Pearson plc Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Cape Town • Sydney • Tokyo • Singapore • Mexico City
ibmpressbooks.com
Kyle Brown , Roland Barcia,
Karl Bishop , Matthew Perrins
The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
© Copyright 2014 by International Business Machines Corporation. All rights reserved.
Note to U.S. Government Users: Documentation related to restricted right. Use, duplication, or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corporation.
IBM Press Program Managers: Steven M. Stansel, Ellice Uffer Cover design: IBM Corporation
Associate Publisher: Dave Dusthimer Executive Editor: Mary Beth Ray Marketing Manager: Stephane Nakib Publicist: Heather Fox Senior Development Editor: Christopher Cleveland Technical Editors: David Artus, Gang Chen Managing Editor: Kristy Hart Cover Designer: Alan Clements Senior Project Editor: Lori Lyons Copy Editor: Krista Hansing Editorial Services, Inc. Indexer: Publishing Works Senior Compositor: Gloria Schurick Proofreader: The Wordsmithery LLC Manufacturing Buyer: Dan Uhrig
Published by Pearson plc Publishing as IBM Press
For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests), please contact our corporate sales department at [email protected] or (800) 382-3419.
For government sales inquiries, please contact [email protected] .
For questions about sales outside the U.S., please contact [email protected] .
The following terms are trademarks of International Business Machines Corporation in many jurisdictions worldwide: IBM, IBM Press, WebSphere, Rational, VisualAge, Worklight, developerWorks, Cast Iron, DataPower, Redbooks, MaaS360, PureApplication and IBM SmartCloud. Softlayer is a registered trademark of SoftLayer, Inc., an IBM Company. Kenexa is a registered trademark of Kenexa, an IBM Company. Other product and service names might be trademarks of IBM or other companies. A current list of IBM trademarks is available on the Web at “Copyright and trademark information” at www.ibm.com/legal/copytrade.shtml .
Oracle, Java, JavaScript, and all Java-based trademarks and logos are trademarks or registered trademarks of Oracle and/or its affiliates. Microsoft, Windows, Visual Basic, Internet Explorer, Windows Phone are trademarks of Microsoft Corporation in the United States, other countries, or both. Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both. Other company, product, or service names may be trademarks or service marks of others.
Library of Congress Control Number: 2014935480
All rights reserved. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236-3290.
ISBN-13: 978-0-13-306703-3 ISBN-10: 0-13-306703-3
Text printed in the United States on recycled paper at Courier Westford in Westford, Massachusetts. First printing June 2014
Kyle: This one is dedicated to my wife, Ann, and my son, Nate,
who supported me and sometimes worried me (yes, that was you, Nate!) during its writing.
Roland: Thank you to God the Father and my Lord Jesus Christ.
Thank you, Blanca, for all your support. Thank you to my children: Alyssa, Savannah, Amadeus, and Joseph.
Thank you, Kyle, for being a great mentor. Thanks to my coauthors and to my family and friends.
Karl: I’d like to thank my family—my wife, Cheryl, and my awesome kids, Matthew and Aubriana.
It still amazes me that you put up with me being so continually distracted by work and this book for so long.
I would also like to thank IBM for being a great place to work and grow, as well as all the IBM clients I’ve had the pleasure of working
with to provide high-quality solutions for your customers.
Matt: To my family, Tania, Elyse, Fintan, Joe, and Tabitha—thanks for being patient.
Contents-at-a-Glance
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii
Chapter 1 The Modern Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Chapter 2 WAS and the Liberty Profile . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Chapter 3 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Chapter 4 REST Web Services in WebSphere Liberty . . . . . . . . . . . . . . 65
Chapter 5 Application Architecture on the Glass . . . . . . . . . . . . . . . . . . 103
Chapter 6 Designing and Building RESTful Applications with Modern Java EE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Chapter 7 Introduction to IBM Worklight . . . . . . . . . . . . . . . . . . . . . . . 213
Chapter 8 Building a Worklight Hybrid App with Open Source Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Chapter 9 Testing and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Chapter 10 Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Chapter 11 Key Takeaways of Modern Web Development . . . . . . . . . . . 307
Appendix A Installation Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii
Chapter 1 The Modern Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1How the Web Has Changed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1The Mobile Effect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Mobile Application Development Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Building for the Mobile Experience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Choosing a Mobile Development Approach. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
The Convergence of Desktop Web and Mobile: Multichannel Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15REST and Web APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17IBM WebSphere and IBM Worklight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18The Process of Building Modern Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Introducing the Team . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Following a User-Centered Design and Development Process . . . . . . . . . . . . . . . . . . . . . . . 20
Introducing User-Centered Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Applying the Design Process: Descriptions from Our Example. . . . . . . . . . . . . . . . . . . . . . . 22Introducing Development into the Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Division of Labor: Defining the User Model and REST Interfaces . . . . . . . . . . . . . . . . . . . . 25
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Endnotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Chapter 2 WAS and the Liberty Profile . . . . . . . . . . . . . . . . . . . . .29How We Got Here . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
A Brief History of WAS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29What Changed in the Programming Model?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
What Is Liberty? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Some Coding Considerations and a Servlet and JDBC Example . . . . . . . . . . . . . . . . . . . . . . 36
Deploying the Example Using the Liberty Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Server Creation and Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42Deploying an Application on a Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Contents xiii
Testing the Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44Running the Example Within Eclipse. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Endnotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Chapter 3 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49Agile UI Design Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49More on User Centric Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Design for Multichannel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Page-Oriented User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53Patterns for User Interface Design Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55View Interaction Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55Targeted Mobile Apps vs. Multichannel Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
UI Design Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Chapter 4 REST Web Services in WebSphere Liberty . . . . . . . . .65What Is REST? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65The Pieces of a RESTFul Web Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66Introducing JAX-RS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Basic Concepts: Resources and Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68A JAX-RS “Hello World” in WebSphere Liberty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68Creating the WebSphere Liberty Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74Starting the Server and Testing the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
More JAX-RS Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80Testing the New Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
JAXB and More Interesting XML-Based Web Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82The JAXB Annotations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83A Trivial DAO (and Its Use). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
JSON Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88A Simple Transaction Example with JAX-RS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88Handling Entity Parameters with POST and the Consumes Annotation . . . . . . . . . . . . . . . . 90The Use of Singletons in Application Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91Testing POST and Other Actions with RESTClient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
More on Content Negotiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95Introducing the JAX-RS Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97Hints on Debugging: Tips and Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98Simple Testing with JUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
RESTful SOA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Endnotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
xiv Contents
Chapter 5 Application Architecture on the Glass. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103
Why Well-Designed Applications Matter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103Defining a Client-Side Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104Responsive Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109Client-Side Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Application Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115Model-View-Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116Error Logging and Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120Data Storage and Caching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Introduction to the Dojo Toolkit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123Dojo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124Dijit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124DojoX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124Util . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Why Use Dojo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125Asynchronous Module Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126Future of Dojo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129Using Dojo in Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Section: HTML Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132Section: Styling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132Section: Configure Dojo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132Section: Load Dojo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134Section: Initialize Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134Section: Body Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Creating Your Own Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136Building the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Chapter 6 Designing and Building RESTful Applications with Modern Java EE . . . . . . . . . . . . . . . . . . . . . . . . . .167
Modern Java EE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167EJB 3.1 and CDI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168JPA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Application Architecture for Modern RESTful Systems. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172Division of Labor: Defining the User Model and REST Interfaces . . . . . . . . . . . . . . . . . . . 174Application Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Building the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185Loading the Example and Setting Up Liberty. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185Test-Driven Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190Building REST Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195Domain Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Contents xv
Building DAO and Business Logic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205Running the Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
A Discussion on Choices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Chapter 7 Introduction to IBM Worklight . . . . . . . . . . . . . . . . . .213What Is IBM Worklight?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213Elements of IBM Worklight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213The IBM Worklight Product Family . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214Developing with IBM Worklight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215IBM Worklight Deployment Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216IBM Worklight Server Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221The Structure of a Worklight Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223What This Means for You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Chapter 8 Building a Worklight Hybrid App with Open Source Frameworks. . . . . . . . . . . . . . . . . . . . . . .227
Design for the Hybrid Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227Overview of Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
jQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229jQuery Mobile. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229Require.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229Backbone and Underscore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230Handlebars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Building a Hybrid App with Worklight. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230Setting Up the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230Worklight Adapter Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233Worklight Hybrid App Folder Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240Examining the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242Running the Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Chapter 9 Testing and Debugging . . . . . . . . . . . . . . . . . . . . . . . . .261HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263Asynchronous Module Definition (AMD) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Unit Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269The Browser as a Test Platform. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
xvi Contents
Exploring Chrome’s DevTools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273Essential Browser Plug-ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
IBM Worklight Specific Concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281Disabling AppCache for Mobile Web Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281Disabling Security for Cross-Domain Ajax in Mobile Apps . . . . . . . . . . . . . . . . . . . . . . . . 283
Remote Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284Safari Remote Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284Chrome Remote Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285Online Code Snippit Runners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Chapter 10 Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .287Understanding Where Your Application Fits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287Achieving Reliability Through Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
Versioning in the URI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293Versioning in the Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Mechanisms for Improving Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294Pagination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295Caching Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296Response Caching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297Server-Side Caching with WXS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Security Issues for Modern Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304Endnotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Chapter 11 Key Takeaways of Modern Web Development . . . . . .307The Engaging Enterprise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Mobile-First Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308Web APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309Polyglot Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310Cloud Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313Endnote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Appendix A Installation Instructions . . . . . . . . . . . . . . . . . . . . . . . .315Development Machine Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
Installing Java Runtime Environment, v1.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316Installing Eclipse Juno IDE, v4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317Installing IBM WebSphere Liberty Profile Developer Tools, v8.5.5 . . . . . . . . . . . . . . . . . . 318Installing the Source Code for the Book Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Contents xvii
Optional Development Tooling for Mobile Web Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321IBM Worklight Studio v6.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321Android Development Tools and Eclipse Plug-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324OSX XCode IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
Server Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328IBM WebSphere Liberty Profile, v8.5.5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329Apache Derby, v10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Downloading and Installing Example Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .335
Preface
“The only thing that is constant is change.” —Greek philosopher Heraclitus, circa 500 B. C.
Some days I can’t believe it, but I’ve now been a consultant in the IT industry for more than 20 years. During that time, I’ve seen a number of technology shifts. When I started in the indus-try, the client/server wave was just beginning. What is now called the first generation of the web (or Web 1.0) came next, quickly followed by Web 2.0. Web 2.0 is now cresting, followed closely by the mobile wave.
The amazing part of all this is that each new technology wave appears to have little in com-mon with the ones before them, but the lessons learned during one wave are actually foundations for the next wave. We developers learned the hard lessons of distributed computing during the client/server wave; that affected the way we went about building distributed systems in Web 1.0. In Web 1.0, we learned quickly that you can’t easily separate the design of your website from the functionality of your website, and we saw that a good dynamic website is not the same as either a static website or a client/server system. These lessons about separation of concerns prepared us for the work of designing Web 2.0 websites that were more much responsive and easier to use. Likewise, the lessons we’ve learned in Web 2.0 about designing for different browsers and screen aspects have prepared us for the mobile wave.
Essentially, that’s what this book is about. My co-authors and I have written it to help you understand how to apply all these different lessons we’ve learned over time in the context of a coherent strategy for building what we’re terming “Modern” Web Applications (meaning ones suitable for use by mobile devices, or browser-based systems using Web 2.0 design techniques).
This book had its genesis in a previous book I wrote for IBM ® press titled Enterprise Java ™ Programming for IBM WebSphere ® . In the two editions of those books, my coauthors and I concentrated on both providing soup-to-nuts coverage of the capabilities of IBM Web-Sphere Application Server and delivering that same kind of “here’s the lessons you need to learn” approach. But the problem is that Enterprise Java, or JEE, has grown so large (as has WebSphere Application Server) that it’s no longer feasible to cover all of it effectively in one book.
Instead, we’ve found that developers of Modern Web Applications have started to spe-cialize in one of two areas: “Front-end” developers write the code that provides both the user interface and the API to the application. “Back-end” developers are more concerned with
Preface xix
building infrastructure and dealing with issues of enterprise connectivity to mainframe systems, messaging systems, and so on. We feel that this forms a natural split between the issues involved, and the book you hold in your hand is our first of at least a two-part set.
Of course, just as in earlier books we had to show how developers build applications for IBM WebSphere Application Server using the Rational ® VisualAge ® for Java and then Rational Application Developer Toolset, now we have a whole new set of tools that developers need to understand. These include not only the tools that come in Eclipse for building Java applications with RESTful services, but also tools for building and deploying mobile applications, such as IBM Worklight ® . We demonstrate to you in this book how the different parts of your team can use these tools to build Modern Web Applications more effectively.
Revamped IBM developerWorks Series
At the same time we were planning this book, my editors at IBM Press and I looked at the landscape of books about IBM products and noticed a gap in the coverage we needed to fill. Enterprise Java Programming with IBM WebSphere was one of the first titles in the IBM Press imprint. It was designed to provide practical, hands-on advice to teams adopting the then-new WebSphere Application Server. We’ve seen that, as new technologies such as mobile, cloud, and social computing technologies have developed, we’ve not provided that same level of practical, hands-on coverage. Thus, we also intend to meet that need with additional topics in the revamped IBM developerWorks ® series—this book is the first example.
Just as IBM developerWorks has always provided the most up-to-the-minute information on topics of interest to developers, we want the books in this series to provide the best combina-tion of in-depth instruction and links to new and updated material on the web so that the books will both inform our readers on the subjects that interest them and help readers follow along with exercises and examples even when the underlying technologies and products change.
So one of the key aspects of the books in this new series is that we not only provide links to information on developerWorks that is relevant to the topics in the text, but we also provide a “landing pad” about each book on developerWorks that links to constantly updated instructions for installing the tools, working through the examples, and helping developers understand what they need to do to be effective with the IBM products that the books are about.
You can find the landing page for this book at www.ibm.com/developerworks/dwbooks/modernwebdev/index.html . We hope you enjoy reading this book as much as we’ve enjoyed writing it.
—Kyle Brown, January 2014
xx Preface
How This Book Is Organized
This book gives you with a simple guide to the principal techniques and tools necessary to build Modern Web Applications with the IBM WebSphere Application Server and devel-oper tools such as Eclipse and IBM Worklight. We alternate between more in-depth chapters focusing on our example and concept-focused chapters to help you gain an understanding of both the material and our recommended approach.
• Chapter 1 , “The Modern Web,” defines what we mean by a Modern Web Application and introduces you to the landscape of technologies and tools that we use for developing Modern Web Applications. We also introduce you to the example we reference through-out the rest of the book.
• Chapter 2 , “WAS and the Liberty Profile,” describes the first of our tools: the Web-Sphere Application Server Liberty profile for lightweight JEE application development. We provide a short “conventional” JEE application example to show you how applica-tions are developed, deployed, and run with WebSphere Liberty.
• Chapter 3 , “Design,” discusses the importance of an agile, user-centered design method and introduces Page-Oriented User Interface design. We also introduce the UI design patterns and elements for our example.
• Chapter 4 , “REST Web Services in WebSphere Liberty,” demonstrates the advan-tages of using the WebSphere Application Server Liberty profile as a server for writing REST services. We introduce the JEE annotations used in building REST services and provide a progressively more complex example to show you how to construct useful REST services with WebSphere Liberty and Eclipse.
• Chapter 5 , “Application Architecture on the Glass,” provides an overview of how to build an effective front-end application architecture. This includes lessons about build-ing and using front-end frameworks, and it also covers the front-end JavaScript design of the example application.
• Chapter 6 , “Designing and Building RESTful Applications with Modern Java EE,” introduces the techniques, technologies, and annotations to help you understand how to build more complex transactional RESTful services that interface with databases and other data sources. In this chapter, we revisit and complete our earlier samples to show you a full example of what constitutes a functional RESTful interface for a Modern Web Application.
• Chapter 7 , “Introduction to IBM Worklight,” looks at the elements, architecture, and fundamental components of Worklight, the IBM platform for developing, deploying, and managing mobile and multiplatform applications.
Preface xxi
• Chapter 8 , “Building a Worklight Hybrid App with Open Source Frameworks,” covers how to build a Worklight application using the open source frameworks of jQuery Mobile, Backbone, Require.js, and Handlebars.
• Chapter 9 , “Testing and Debugging,” introduces a number of techniques and tools for finding and fixing problems in cross-platform, multilanguage Modern Web Applications.
• Chapter 10 , “Advanced Topics,” covers other topics relevant to building enterprise-scale Modern Web Applications. This includes scalability and caching, security, and ser-vices connectivity into the wider enterprise.
• Chapter 11 , “Key Takeaways for Modern Web Development,” wraps up our cover-age by discussing how Modern Web Development fits in with other emerging and domi-nant trends in the industry.
• Appendix A , “Installation Instructions,” covers how to locate, install, and configure all the software necessary to compile, run, and debug our examples, as well as how to obtain and download the sample code for the book. You can find its complete and most up-to-date form here:
www.ibm.com/developerworks/dwbooks/modernwebdev/index.html .
Acknowledgments
We would first like to thank our wonderful technical reviewers, David Artus and Gang Chen, whose time, dedication, and effort made this book a much more valuable and insightful document. We would also like to thank Andrew Ferrier, Chris Mitchell, Cory Eden, Mohsen Yasarizare, Alberto Manjarrez, Leigh Williamson, Greg Truty, and others for additional insight.
We also want to thank the team at IBM Press for the opportunity to deliver this book to you. Thanks to Chris Cleveland for making this the best it can be. Thanks also to Executive Edi-tor Mary Beth Ray for giving us the opportunity to create this book on a flexible schedule, despite several restarts and delays. Finally, we want to thank Steve Stansel, Editorial Program Manager for IBM Press, who helped us immensely through this whole process by cajoling us, lending a sympathetic ear, and keeping things moving along.
About the Authors
Kyle Brown is a Distinguished Engineer and CTO of Emerging Technologies with IBM Software Services and Support for WebSphere. He has 20 years of experience in designing and architecting large-scale systems. In his role as a DE, he is responsible for helping customers adopt emerging technologies, specifically cloud technologies and services-oriented approaches. He specializes in developing and promoting best practices approaches to designing large-scale systems using SOA, Java Enterprise Edition (JEE), and the IBM WebSphere product family. He is a best-selling author and regular conference speaker, as well as an internationally recognized expert in patterns, JEE, and object technology.
Roland Barcia is an IBM Distinguished Engineer and CTO for the Mobile and Web-Sphere Foundation for Software Group Lab Services. Roland is responsible for technical thought leadership and strategy, practice technical vitality, and technical enablement. He works with many enterprise clients on mobile strategy and implementations. He is the coauthor of four books and has published more than 50 articles and papers on topics such as mobile technologies, IBM MobileFirst, Java™ Persistence, Ajax, REST, JavaServer Faces, and messaging technologies. He frequently presents at conferences and to customers on various technologies. Roland has spent the past 16 years implementing middleware systems on various platforms, including Sockets, CORBA, Java EE, SOA, REST, web, and mobile platforms. He has a master’s degree in com-puter science from the New Jersey Institute of Technology
Karl Bishop is a Product Manager with the IBM Worklight team. He currently works with the IBM Worklight Product Design team, focusing on developer experience. Before that, Karl spent many years working within the IBM Software Services for WebSphere group. His techni-cal focus has been mobile app development, HTML5, Web 2.0, and JavaScript toolkits. Karl has worked for IBM for more than 16 years. He previously spent another dozen years honing his geek credentials at another computer company in California. Karl currently works out of his house, hidden away in the Sandhills near Pinehurst, North Carolina.
Matthew Perrins is an Executive IT Specialist and the lead architect for the BlueMix Mobile Backend as a Service Client SDK. He is the technical lead for IBM Software Services for Mobile for Europe, which is focused on delivering first-of-their-kind mobile solutions for IBM clients. He has worked for IBM since 1989 and has spent a significant amount of time designing and building Java-based enterprise solutions based on WebSphere.
This page intentionally left blank
This page intentionally left blank
65
C H A P T E R 4
REST Web Services in WebSphere Liberty
What Is REST?
Earlier in Chapter 1 , “The Modern Web,” and again in Chapter 3 , “Design,” we discussed the REST approach to building web services. REST is about creating web services around a set of constraints. By sticking to the constraints that stem from the way the web was designed and built, you can take better advantage of the existing web infrastructure. Routers, caching proxies, and web servers are all optimized to deliver web content. Delivering your services as web content through these channels enables you to take advantage of existing optimizations in these channels.
The philosophy of RESTful services construction has two parts. One part centers on expos-ing resources, putting them into the hands of the masses and then allowing others in the commu-nity to create new types of applications by mixing and matching content from various places. In our context, you can view REST services as the data source for your model layer inside a Modern Web Application that runs in the browser or as a mobile app. REST services can provide data for reusable widgets that you can mix together to create mashups. REST services can also present data as feeds, notifying end users of content through the use of feed readers.
In general, almost any data—including business logic—can easily be expressed through REST. What’s more, it’s easy to build REST services that provide content in different forms (for instance, JSON and XML). For these reasons, REST services are extending into the API space and rapidly becoming accepted as the default standard for providing externally accessible web APIs. This services exposure for enabling reuse is a central part of the REST philosophy.
The second aspect of the REST philosophy focuses on using RESTful idioms to simplify access, increase orthogonality, and enable discovery. This is where the arguments tend to start. REST is based on a set of simple principles that derive from the HTTP specification and other web standards. Some developers tend to follow these principles very closely, whereas others are more lax in their compliance with the principles set forward in the original REST paper by Roy Fielding. In our examples, we tend toward a more strict interpretation of REST, but we do point out places where deviations might commonly occur.
66 Chapter 4 REST Web Services in WebSphere Liberty
The Pieces of a RESTFul Web Service
Creating a RESTful web service is like forming a sentence: You need a noun, a verb, and an adjective. In REST terms, nouns are the resources URLs point to. The verbs are the HTTP actions on resources. The adjectives (okay, this might be stretching the analogy) are the formats of data in which the resources are represented. We like to lay this out in tables similar to the way we broke down sentences in primary school. For example, Table 4.1 outlines how you might describe a set of services related to a prospect list application, such as the one in Chapter 2 , “WAS and the Liberty Profile.”
Table 4.1 Prospect URI Structure
Sentence (Resource
Description)
Noun (URI) Verb (Action) Adjectives (Formats)
List all the prospects. .../prospects GET JSON, XML
Get a specific prospect. .../prospects/{id}
GET JSON, XML
Add a contact. .../prospects POST JSON, XML
Delete a specific contact.
.../prospects/{id}
DELETE JSON, XML
• Nouns/URIs: URLs are the most identifiable part of the web and, as such, are a straight-forward way of organizing your services. Organizing a unique URI for each resource avoids confusion and promotes scalability.
• Verbs/actions: In REST, you usually perform four HTTP operations against these URLs: POST , GET , PUT , and DELETE . (HTTP supports a few more actions, or officially request-methods , but these are the interesting ones.) Although having just four opera-tions might seem constraining, the simplicity is somewhat liberating. These operations roughly map to Create, Read, Update, and Delete (CRUD). CRUD provides the founda-tional functions needed to interface with a relational database or other data store, so you can use these four methods in interesting and powerful ways.
• Adjectives/data formats: There are well known data types (the MIME types—text/html, image/jpeg) that HTTP servers and browsers natively support. Simple XML and JSON allow more custom data formats that are self-describing and can easily be parsed by the user. (When we say parse , we also mean “read with your eyes and parse with your brain.”)
Introducing JAX-RS 67
Using REST enables you to take advantage of many assumptions made by web infrastruc-ture. Because you constrain the problem to only HTTP, you can make assumptions about items such as caching and HTTP-based security models. Because these technologies are ubiquitous, following this approach enables you to take advantage of existing solutions such as browser caches and web security proxies. By making your resources stateless, you can easily partition your resources across multiple servers, providing scalability opportunities. Another advantage is you can easily test HTTP-based services using a browser or a simple command-line tool such as cURL. By following RESTful idioms such as representing connections between resources by links in the data, you can enable runtime discovery of additional services. Finally, from the consumer perspective, services written to RESTful idioms have a regularity that enables you to benefit from examples and to practice reuse through cut-and-paste.
Building an effective REST architecture involves many aspects:
• Resources
• Resource types
• Query formats, headers, and status codes
• Content negotiation
• Linking
• Versioning
• Security
• Documentation
• Unit tests
We begin to cover these issues in this chapter, and we address more of these topics more fully in later chapters.
Introducing JAX-RS
Very soon after the REST model was described, it began to gain acceptance in the Java commu-nity. Early efforts focused on building REST services directly with Java Servlets, but an effort soon concentrated on creating a draft specification (JSR) for developing REST services in Java. The specification that resulted from that effort (JSR-033) became the JAX-RS standard. The authors of the JAX-RS standard set some specific goals for the JAX-RS approach:
• POJO based: The authors of the specification wanted to allow developers to build their services entirely with annotated POJOs—no special component model, such as earlier versions of EJB or web services standards, required.
• HTTP-centric: In keeping with the REST architectural approach, the JAX-RS standard assumes that HTTP is the only underlying network protocol. It does not attempt to be protocol independent—in fact, it provides simple mechanisms for exploiting the under-lying HTTP protocol.
68 Chapter 4 REST Web Services in WebSphere Liberty
• Format independent: The developers of the standard also wanted to make the JAX-RS standard compatible with a number of different content types. Therefore, they focused on providing plugability so that additional content types could be added in a compli-ant way.
Basic Concepts: Resources and Applications
The most basic concept in the JAX-RS standard is the notion of a resource. A resource is a Java class that uses annotations to implement a RESTful service. If you consider a web resource to be a specific URI (or pattern of URIs) that represents an entity type, then the resource is the imple-mentation of that entity. Resources are tied together logically by your Application subclass, which extends the javax.ws.rs.core.Application class provided by the JAX-RS runtime. To implement the simplest JAX-RS service in WebSphere Liberty profile, all you need are two classes and a bit of configuration.
A JAX-RS “Hello World” in WebSphere Liberty
Given that we need to introduce several concepts with JAX-RS, we assume that you’ll be devel-oping your JAX-RS services inside Eclipse using the WebSphere Liberty Profile Test Server. For instructions on downloading and installing Eclipse, WebSphere Liberty, and the WebSphere Lib-erty tools for Eclipse, either see our website or take a look at Appendix A , “Installation Instruc-tions.” Note that the following instructions were specifically written and tested on Eclipse Juno for Java EE Developers Service Release 2 and the WAS 8.5.5 Liberty Profile. If you’re using a different (later) version of Eclipse or WAS, you might see some differences, but they should remain nearly the same.
AUTHORS’ NOTE
This chapter walks you through the process of creating a new web project and a number of new classes. If you’d rather not type in the code and you instead want to just run the completed examples, then follow the instructions in Appendix A and load the Chapter4Ex-amples.zip file from the book’s website into your Eclipse workspace.
You start the process by creating a new Eclipse Dynamic Web Project. The JAX-RS speci-fication gives container providers some flexibility in how they can implement the specification, but they assume that artifacts will be deployed in a Servlet container such as WebSphere Liberty. In the Eclipse web development tool suite, a web project represents artifacts that are meant to be deployed to a Servlet container and packaged in a WAR file. If you’re not familiar with develop-ment in Eclipse, you might want to first refer to any of the helpful tutorials on Java development with Eclipse. 1
Introducing JAX-RS 69
First, switch to a Java EE perspective in Eclipse. Then select File > New . The menu that pops up enables you to select a Dynamic Web Project. After you select that, the dialog box in Figure 4.1 appears.
Figure 4.1 Creating a new web project
Name your project RestServicesSamples . For this particular project, we want to walk you through all the pieces included in a web project using REST in Eclipse, so you won’t actually use all the built-in wizards for creating REST services that the Eclipse web tools provide. However, you will use some of the features to set up a project that uses JAX-RS and WebSphere Liberty.
70 Chapter 4 REST Web Services in WebSphere Liberty
Make sure that the Include in EAR check box is unchecked; you only need a WAR file from this project, so you don’t need to worry about inclusion in an EAR.
Next, click the Modify button. This takes you to the page in Figure 4.2 , which enables you to add facets to your project. Facets enable you to specify requirements and dependencies on specific technologies—Eclipse automatically handles modifications such as classpaths after you declare that you need those facets. On this page, check the check boxes to include support for JAX-RS and JAXB in your project (we explain why you need JAXB in the later section “JAXB and More Interesting XML-Based Web Services”).
Figure 4.2 Modifying Facets
Finally, back on the Dynamic Web Project creation page, click Finish . Eclipse creates the project and might inform you through a dialog box that this type of project is best viewed in the JEE perspective; it asks if you want to open that perspective now. If you are not already in that perspective, answer Yes; you can work in the JEE perspective from then on.
Introducing JAX-RS 71
Next, you need to create your first resource class. This resource class simply introduces you to many of the common annotations in JAX-RS and familiarizes you with the way you start and test REST services using Eclipse and the WebSphere Liberty Profile. Go to File > New > Class from within the web perspective, and open the dialog box in Figure 4.3 that enables you to create your first resource class.
Figure 4.3 Creating GreetingResource
72 Chapter 4 REST Web Services in WebSphere Liberty
Name your new class GreetingResource , and put it in a package named com.ibm.mwdbook.restexamples. Click Finish, and the Java Editor for your newly created class opens. At this point, you can go into the Java editor and change the newly created class stub to match the code in Listing 4.1 .
Listing 4.1 GreetingResource
package com.ibm.mwdbook.restexamples;
import javax.ws.rs.GET;import javax.ws.rs.Path;
@Path("/Greeting")public class GreetingResource {@GET
public String getMessage() {return "Hello World";
}}
This little example doesn’t do much, but it does point out a few key aspects of resource classes in JAX-RS. First, notice that this class doesn’t descend from any specialized subclass, nor does it implement any special interfaces. This is in accordance with the design of the JAX-RS specification, which aimed to allow developers to implement services as annotated POJOs. This was a principle that originated in JEE5 and has continued into later specifications. Next, notice the @Path annotation at the class level. As with the other annotations, @Path corresponds to a particular class—in this case, javax.ws.rs.Path , which you must import. In fact, each of the annotations you import in this example come from the javax.ws.rs package. @Path deter-mines where in the URI space this particular resource is placed. Adding a path of /Greeting states that the last part of the URL (the resource identifier) will end in /Greeting . Other parts of the URL can be in front of the path identifier, but at least this identifies the end. In terms of the JAX-RS specification, annotating a class like this makes it a root resource class. This distinction becomes important when we start discussing subresources later.
The final point to notice about this simple example is the @GET annotation. Remember that, in the REST model, the HTTP methods are the verbs of the service. If the URI represents the noun that the action is performed against, then the method is the action that is performed. So the meaning of this simple example is that you are GET ting a greeting. That makes the response that we are returning, Hello World! , very appropriate! Now, of course, @GET isn’t the only HTTP method annotation you can use; in the later section “Handling Entity Parameters with POST and the Consumes Annotation,” we cover a case in which you use @POST , and Chapter 6 shows uses for @DELETE and @PUT as well.
Introducing JAX-RS 73
The next piece of the puzzle to put in place is the Application subclass. According to the JAX-RS specification, the purpose of the Application subclass is to configure the resources and providers (we cover those later) of the JAX-RS application. In fact, you’ll be editing and adding to the Application subclass as we expand the examples. For now, we start with another File > New > Class and bring up the new class dialog box. Your Application subclass should be named BankingApplication and should be placed in the com.ibm.mwdbook.restexamples package. The class needs to inherit from javax.ws.rs.core.Application . Figure 4.4 shows the completed fields in the dialog box.
Figure 4.4 Creating the Application subclass
74 Chapter 4 REST Web Services in WebSphere Liberty
After you enter these fields, click Finish and then replace the template text of the newly created class with the text in Listing 4.2 .
Listing 4.2 BankingApplication Class
package com.ibm.mwdbook.restexamples;import javax.ws.rs.ApplicationPath;import javax.ws.rs.core.Application;
@ApplicationPath("/banking/*")public class BankingApplication extends Application {
}
Note that we’ve added a single annotation in this class, the @ApplicationPath annota-tion. This annotation instructs the JAX-RS runtime what the path for JAX-RS resources will be. The path segment referenced in the annotation is added after the server name and web project context root, so resources are referenced by this pattern:
http://localhost:9090/RestServicesSamples/banking/your_resource_here
This is only one of three mechanisms defined in the Infocenter for configuring JAX-RS in the WebSphere Liberty Profile. This approach enables you to specify multiple JAX-RS appli-cations with different application paths in the same JAR file, but it doesn’t allow you to set up security constraints for the applications. For information on how to set up JAX-RS to allow that, refer to the Infocenter. 2
Creating the WebSphere Liberty Server
You’re almost ready to put the final piece in place for this simple example. Now that you’ve created all the artifacts necessary to implement a service, you need to deploy those artifacts into the WebSphere Liberty Profile. To do so, you must define a server in Eclipse. In this section, we assume that you created one server back in Chapter 2 when you tested a simple Web 1.0 example in Eclipse. If you haven’t done so, your panels might differ slightly. Remember the discussion in Chapter 2 on how you might have different servers for different layers in your application. One advantage of defining multiple servers is that it keeps your servers from being cluttered by
Introducing JAX-RS 75
association with projects you don’t need that might slow the startup of your particular server. For now, begin in the JEE Perspective by clicking the Servers tab at the bottom of the page, selecting the existing server you created in Chapter 2 , and then using the right mouse button menu to select New > Server . The dialog box in Figure 4.5 then appears.
Figure 4.5 Define a New Server dialog box
76 Chapter 4 REST Web Services in WebSphere Liberty
In the Define a New Server dialog box, make sure you have selected WebSphere Applica-tion Server V8.5 Liberty Profile, and then click Next . The page in Figure 4.6 appears.
Figure 4.6 Creating a new server from an existing server
This dialog box informs you that you have already created one server named defaultServer and that this name is in use. On this page, click the New button. That action brings up the next page of this dialog box (see Figure 4.7 ).
Introducing JAX-RS 77
Figure 4.7 New RESTServer creation
Give the server the name RESTServer. When you click Finish on the dialog box in Figure 4.7 , you are taken back to the new Servers page, but this time you see a description of the server configuration for your new server, as in Figure 4.8 . Note that your server is pretty bare bones at this time—only the basic configuration for your HTTP host and port is defined. That changes in the next step.
The final task in creating your server is associating your project with the server you just created. Click the Next button one final time. The dialog box in Figure 4.8 enables you to associ-ate your project with the server by clicking the Add button to move the project from the list of available projects on the left side over to the list of configured servers on the right side.
78 Chapter 4 REST Web Services in WebSphere Liberty
Figure 4.8 Add Project dialog box
At this point, you can finally click the Finish button to finish configuring the server. This adds the required features (in this case, JAX-RS support) to the server.xml file. Feel free to examine the server.xml file to verify that it has been reconfigured.
Starting the Server and Testing the Application
You’re finally ready to test your application. Begin the process by starting the server you just cre-ated. On the Servers tab, click the green Start button in Figure 4.9 .
Introducing JAX-RS 79
Figure 4.9 Starting the server
Now switch to the Console tab and make sure you see a message stating something like the following:
[AUDIT ] CWWKZ0001I: Application SimpleBankingProject started in 0.419 seconds.
If you don’t see this message, or if see an error message instead, take a look through the earlier messages in the console to find out what you did wrong. You can also turn to the end of this chapter and look at the debugging hints for JAX-RS services. Finally, presuming that every-thing went well, you can open a browser and type the following into the URL line:
http://localhost:9080/RestServicesSamples/banking/Greeting
If everything worked correctly, you should see your REST service greeting you with Hello World! (see Figure 4.10 ).
Figure 4.10 Greeting results
80 Chapter 4 REST Web Services in WebSphere Liberty
More JAX-RS Annotations
Having a REST service greet you is nice, but it’s hardly a very useful service. Next you’ll imple-ment a simple service that ties directly to our Banking example. Remember from the description of the sample in Chapter 1 that often a development team wants to mock up services so that the UI and Java development teams can test independently. The rest of this chapter walks you through the implementation of such a set of services—in Chapter 7 , “Introduction to IBM Work-light,” we show you a complete example that is much more like the production code that would be used to implement these services. Table 4.2 shows a set of services you need to implement as part of the example online and mobile banking solution.
Table 4.2 Services for Online Banking
URI Description
/banking/accounts List of accounts
/banking/accounts/{id} Detail of given account ID
/banking/accounts/{id}/transactions
List of transactions for a given account
/banking/accounts/{id}/transactions/{id}
Detail of given account ID/transaction ID
We begin by looking at the Accounts resource. You can see two interesting resource refer-ences here: one service to return a list of accounts and another service to return the detail for a specific account. From this point on in the chapter, we assume that you know how to create new resource classes, so we just look at the code for each new class. Let’s start by creating a new class in com.ibm.mwdbook.restexamples named SimpleAccountResource , with the code shown in Listing 4.3 . We begin with this class in the listing and use it to learn some more features of JAX-RS; then we replace it with a more complete implementation in Listing 4.4 . Remember that this class, as with all resource classes, has no special base class.
Listing 4.3 SimpleAccountResource Class
package com.ibm.mwdbook.restexamples;
import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;
@Path("/simple/accounts")public class SimpleAccountResource { @GET
More JAX-RS Annotations 81
@Produces("application/xml")public String getAccounts() {
return "<accounts><account>123</account>"+ "<account>234</account></accounts>"; } @Path("{id}") @GET @Produces("application/xml")
public String getAccount(@PathParam(value="id") int accountId){if (accountId==123)
return "<account><id>123</id>" + "<description>Savings</description>" + "<balance>110.00</balance></account>";
elsereturn "<error>No account having that id</error>";
}}
In this example, the code implementing the functionality of the service isn’t the interesting part; it’s the annotations that surround the functionality. The first @Path annotation simply sets up the basic URI of this example—remember that you’re initially building a throwaway example that you will replace, so you don’t use the actual URI in Table 4.2 for this example. Instead, to differentiate this example from others later, you prefix the end of this test URI with simple instead of just accounts , as the table shows.
As in the previous example, you begin with the method named getAccounts() , which returns an XML string representing a collection of two different accounts. The first point to notice is a new tag, @Produces , which states what type of content the method returns. In the case of both our new methods, this is application/xml . At this point, you might be wondering why we didn’t need this for our previous example. The answer is simple—if you don’t add the @Produces annotation to a resource method, the JAX-RS provider assumes that the content type is text/html .
As useful as that is, you can see a much more interesting new feature in the second @Path annotation added to the bottom method. Here we’re adding the mechanism to handle a second part of the URI that comes after the /accounts portion handled by getAccounts() . In the example, we want to provide access to a specific account that is identified by an integer account number placed after the /accounts portion of the URI. The @Path({id}) annotation identi-fies that specific account number. But then the question becomes, how do we manage to map the account number information from the URI to the getAccount(int) method? That’s the role of the @PathParam(value="id") annotation.
82 Chapter 4 REST Web Services in WebSphere Liberty
@PathParam is probably the single most useful source of parameter information for resource methods, but it’s not the only source. Table 4.3 shows some other common sources of information that you can use as parameters in your resource classes.
Table 4.3 Sources of Parameter Information in Resource Classes
Source Description
@QueryParam Individual query string parameter attached to the URI in the form ?name=value
@PathParam Parameter from URI template
@CookieParam Http cookies value
@HeaderParam Http header value
@FormParam HTML form elements
@Context Limited set of context objects
Testing the New Example
Entering that little bit of code is all you need to do for this new example. At this point, you should be able to test your new examples in your browser. You don’t even need to restart the server—when you change the classes, Eclipse and Liberty automatically update the files on the server (using the dropins directory on the Liberty server that we mentioned in Chapter 2 ), so your changes take effect immediately.
Enter the following URLs into your browser to view the results. First, to see the list type, use this:
http://localhost:9080/RestServicesSamples/banking/simple/accounts
Then to see the individual account, type this:
http://localhost:9080/RestServicesSamples/banking/simple/accounts/123
Finally, to see the error path, type this:
http://localhost:9080/RestServicesSamples/banking/simple/accounts/234
JAXB and More Interesting XML-Based Web Services
We’ve now implemented a simple RESTful web service for the banking example, but it still leaves a lot to be desired. Hand-crafting XML might have been an appealing thought at the dawn of the REST services era, but it’s hardly a scalable solution. Instead, we need to discuss ways of generating the XML produced by our services from our POJOs. This can be accomplished in
JAXB and More Interesting XML-Based Web Services 83
several ways. One is using the org.w3c.dom.Document interface to generate a document from its parts. In some cases, this is the best possible approach, especially if you have to handle the generation of several different XML schemas. However, you usually don’t need the flexibility of a dynamic approach. In such a case, a simple static approach that ties your POJOs to a single XML schema is best. The JAXB standard gives you the capability to easily generate XML docu-ments from your POJO objects with just a few annotations.
The JAXB Annotations
Essentially, only two annotations are needed to get going with JAXB:
• @XmlRootElement: This annotation maps an entire Java class or enum type to an XML element. It’s called the “RootElement” because it’s the root of the tree of XML tags (with the attributes of the class being the leaves of the tree).
• @XmlElement: This annotation maps a JavaBean property or a nonstatic, nontransient field to an XML element.
One of the common changes made to the XML tags that are output by a JAXB mapping is to change the name of the tag (which, by default, is the same as the name of the field or property). This is done with the name parameter to the annotation. Consider the following example where you have a field named foo in your code, which you annotate with a standard @XMLElement tag:
@XmlElementpublic int foo;
Your XML output then is of the form <foo>123</foo> . That might not be helpful for someone trying to read and parse the XML without knowledge of your special variable naming conventions. Instead, using name as follows
@XmlElement(name="accountNumber")public int foo;
results in more readable output:
<accountNumber>123</accountNumber>.
Combining these annotations is easy. Consider a simple POJO class that represents an account in our banking example. As in previous examples, you create a new class in your proj-ect, named com.ibm.mwdbook.restexamples.Account , and then fill in the code from the example (see Listing 4.4 ).
84 Chapter 4 REST Web Services in WebSphere Liberty
Listing 4.4 Account Class
package com.ibm.mwdbook.restexamples;
import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElementpublic class Account{
int id; String accountType; String description; String currency;
double balance;
// For JAXB Serialization to work every class must have a // default no-arg constructor // if there are any other constructors defined!
public Account() { }
public Account( int i, String name, String type, double balance) { setId(i); setDescription(name); setAccountType(type); setBalance(balance); setCurrency("USD"); }
@XmlElementpublic int getId() {
return id; }
public void setId( int id) {this.id = id;
}
@XmlElement(name="name")public String getDescription() {
return description; }
public void setDescription(String description) {
JAXB and More Interesting XML-Based Web Services 85
this.description = description; }
@XmlElement(name="type")public String getAccountType() {
return accountType; }
public void setAccountType(String accountType) {this.accountType = accountType;
}
@XmlElementpublic String getCurrency() {
return currency; }
public void setCurrency(String currency) {this.currency = currency;
}
@XmlElementpublic double getBalance() {
return balance; }
public void setBalance( double balance) {this.balance = balance;
}}
A couple of points are worth calling out in this example. The first is the use of the no-arg constructor. Even if your code doesn’t use a no-arg constructor, one is necessary for any class serialized by JAXB because the JAXB framework itself expects to use it. The second point to notice is that we’ve annotated the getter methods. This means that we’ve annotated the proper-ties for this example; later in Listing 4.7 , we annotate the fields and discuss the differences. In one particular case, we’ve even illustrated a common aspect of properties annotation—note this annotation:
@XmlElement(name="type")
86 Chapter 4 REST Web Services in WebSphere Liberty
Here, we want the name of the tag in the XML to differ from the name of the property itself. You can do this by specifying the name= property within the annotation. This way, the seg-ment of XML generated would be of this form
<type> somevalue </type>
instead of the default:
<accountType> somevalue </accountType>
You’ll find yourself substituting names like this fairly often when you have to work with existing XML schemas or JSON formats.
A Trivial DAO (and Its Use)
Now that we have an annotated POJO class representing our accounts, we need to turn our atten-tion to how accounts are created and managed. One of the biggest contributions to the field of Java EE design over the last 15 years is the book Core J2EE Patterns, by Alur, et. al. Later devel-opments in JEE have superseded many of the patterns called out in this book, but some are still as appropriate as ever. One in particular that is extremely helpful in many different situations, and one that we will follow in this book, is the Data Access Object (DAO) pattern. (You might remember that you built a simple JDBC-based DAO in Chapter 2 .) The benefit of this pattern is that it provides an interface that encapsulates and abstracts away all the details of access to any data source. This enables you to replace one implementation of a DAO with another, without having to change any of the code that uses the DAO. So in this case, we’re building a very trivial DAO that’s useful for testing and hides the details of retrieving an account from an account list. Listing 4.5 shows the code for this DAO.
NOTE
Most of the example snippets in the rest of the chapter leave out the package declaration (always the same, com.ibm.mwdbook.restexamples ) and the includes statements. For the most part, you’ve seen everything that needs to be included—besides, Eclipse can automatically patch these up for you using Source > Organize Imports. This makes the examples much shorter.
Listing 4.5 AccountDao Class
public class AccountDao { HashMap<Integer, Account> accounts = new HashMap<Integer, Account>(); public AccountDao() { Account anAccount = new Account(123,"savings",110.0); accounts.put(123, anAccount);
JAXB and More Interesting XML-Based Web Services 87
} public List<Account> getAccounts() { List<Account> accountslist = new Vector<Account>(); accountslist.addAll(accounts.values()); return accountslist; } public Account get(int id) { return (Account) accounts.get(id); }}
That’s all you need for now—just a simple constructor that creates a HashMap of accounts and adds one to the list, and then a getter for both a list of all accounts and an account stored at a specific ID. However, that’s enough to help implement our next, more useful example of a JAX-RS resource (see Listing 4.6 ).
Listing 4.6 AccountResource Class
@Path("/accounts")public class AccountResource { AccountDao dao = new AccountDao(); public AccountResource() { } @GET @Produces(MediaType.APPLICATION_XML) public List<Account> getAccounts() { return dao.getAccounts(); } @GET @Path("{id}") @Produces(MediaType.APPLICATION_XML) public Account getAccount(@PathParam(value="id") int id){ return dao.get(id); }}
We now have an example that’s complete enough to be of some use. This is exactly the type of simple resource that you would implement when testing an AJAX UI that relies on a number of REST services to provide information that you can manipulate through JavaScript and HTML. You can see that we’ve used all the different annotations we’ve examined already, and we’ve also used the constants in the class MediaType instead of hand-coding application/xml for the @Produces annotation (which is a best practice to eliminate the possibility of mistyping).
To test the example, simply type the following into your browser:
http://localhost:9080/RestServicesSamples/banking/accounts/123
88 Chapter 4 REST Web Services in WebSphere Liberty
JSON Serialization
Although RESTful services that produce XML are common, it is perhaps even more common for the service to produce JSON, or the JavaScript Object Notation. JSON is a simple notation based on name/value pairs and ordered lists that are both easy to produce in many languages and extremely easy (in fact, part of the language) for JavaScript to parse and create. It’s actually noth-ing more than a proper subset of the JavaScript object literal notation. 3
When it comes to Java, especially inside the WebSphere Liberty Profile, you have sev-eral ways to produce JSON, just as you have different ways of producing XML. You can, of course, manually hand-code it, although that is not recommended. For more complex situations requiring a great deal of flexibility, a dynamic method of producing JSON might be needed, just as a dynamic approach to producing XML is sometimes helpful. However, the most common approach for producing JSON is the same as that for XML—using static annotations with JAXB.
A Simple Transaction Example with JAX-RS
To show how annotations for JSON work, we going to introduce another service from the list ear-lier in the chapter. The Transaction service enables you to view a transaction with GET , view a list of transactions with GET , and also create a new transaction by POST ing to the appropriate URL.
Let’s start by introducing our BankingTransaction class (see Listing 4.7 ).
Listing 4.7 BankingTransaction Class
package com.ibm.mwdbook.restexamples;
import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement@XmlAccessorType(XmlAccessType.FIELD)public class BankingTransaction { @XmlElement
protected String id; @XmlElement
protected Date; @XmlElement
protected double amount; @XmlElement
protected String currency; @XmlElement
protected String merchant; @XmlElement(name="memo")
protected String description; @XmlElement
JSON Serialization 89
protected String tranType;
public BankingTransaction() { }
public BankingTransaction(String id, long date,String currency,➥String memo, double amount, String tranType, String merchant) { setId(id); setDescription(memo); setAmount(amount); setCurrency(currency); setTranType(tranType); setMerchant(merchant); setDate( new Date(date)); }
public String getDescription() {return description;
}public void setDescription(String aDescription) {
description = aDescription; }
public double getAmount() {return amount;
}public void setAmount( double anAmount) {
amount = anAmount; }
public String getCurrency() {return currency;
}public void setCurrency(String currency) {
this.currency = currency; }
public String getId() {return id;
}public void setId(String id) {
this.id = id; }
public String getTranType() {return tranType;
}public void setTranType(String tranType) {
this.tranType = tranType; }
90 Chapter 4 REST Web Services in WebSphere Liberty
public String getMerchant() {return merchant;
}public void setMerchant(String merchant) {
this.merchant = merchant; }
public Date getDate() {return date;
}public void setDate(Date date) {
this.date = date; }}
At this point, you might be thinking that this looks exactly like the annotations in the previ-ous example. That’s the point. If you use JAXB annotations, you have to annotate the class only once; you don’t have to put in separate annotations for JSON and XML. Also, it’s not entirely the same. Note that, in this case, we annotated the fields and not the properties—in practice, there is little difference between the two, and you can use either.
Handling Entity Parameters with POST and the Consumes Annotation
Now that you’ve seen how you can create a class with annotations that work for both XML and JSON, you can explore how to add methods to a service to take advantage of that. We’re only introducing a couple new concepts in this part of the example—take a look at the following new method from the AccountResource class:
@Path("{account}/transaction")@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)@POSTpublic int putTransaction(@PathParam(value="account") int account, BankingTransaction aTrans){
return txnDao.putTransaction(account, aTrans);}
The first new annotation is the @Consumes annotation. None of the previous services we’ve written have taken in any message bodies, so this is the first time we’ve needed to use it. As you can see, it’s essentially similar to the @Produces annotation. The interesting part is how the browser interacts with the server based on these annotations. In this case, we’re being very restrictive—we insist that the format of the message body be in JSON, but we also provide the response back in JSON. This information about what format is acceptable to the server and the client is communicated in specific HTTP headers. Figure 4.11 shows the interaction.
JSON Serialization 91
Figure 4.11 Header and annotation interaction
For a resource method to process a request, the Content-Type header of the request must be compatible with the supported type of the @Consumes annotation (if one is provided). Like-wise, the Accept header of the request must be compatible with the supported type of the @Produces annotation. The Content-type header of the response will be set to a type listed in the @Produces annotation. This case is very simple—we’re allowing only a single content type ( application/json ) into our service and a single content type (also application/json ) out of the service; more complex cases might require content negotiation , which we discuss in more detail in the later section “More on Content Negotiation.”
Looking back at the code for our BankingTransaction class, you see one more interest-ing fact about the putTransaction() method. Not only does it take a @PathParam , as have several of our preceding examples, but another method parameter is not attached to a @Path-Param annotation: an instance of a BankingTransaction named aTrans . Where does this parameter come from? The JAX-RS specification is very clear on this: A resource method may have only one nonannotated parameter; that special parameter is called the entity parameter and is mapped from the request body. It is possible to handle that mapping yourself, but in our case (and in most cases), that mapping will be handled by a mapping framework such as JAXB.
The Use of Singletons in Application Classes
Before you can test your simple transaction-posting method, you need to understand a couple more concepts. The first is how we’re implementing the DAO for this example. All the previous DAOs we implemented were just for prepopulating a collection with examples that we could retrieve with a GET . However, if we are now enabling POST , we want to be able to check that the information that we POST to the resource will be available on the next GET to that resource. In a “real” implementation of a DAO, that would be fine—we’d just fetch the values from a relational
92 Chapter 4 REST Web Services in WebSphere Liberty
database on a GET and create the new rows on a POST . However, in our simplified example, we don’t yet have that option (we show that in Chapter 6 ). Our solution for this case is very simple—we add a static variable that is an instance of our DAO to the DAO class. That way, we implement what in Design Patterns parlance is often called a singleton, a class that has a single instance. You can see this in the source code ( see Listing 4.8 ) of our very simple BankingTransactionDao , which holds on to a single static variable that is an instance of the class that we name instance .
Listing 4.8 BankingTransactionDao Class
package com.ibm.mwdbook.restexamples;
import java.util.HashMap;
public class BankingTransactionDao {
static BankingTransactionDao instance = new➥BankingTransactionDao();
public static BankingTransactionDao getInstance() {return instance;
}
HashMap<String, BankingTransaction> accounts =new HashMap<String, BankingTransaction>();
int lastId=123;
public BankingTransactionDao() { String key=deriveKey(123,123); BankingTransaction aTrans = new BankingTransaction("123",➥1388249396976L,"USD", "paycheck", 110.0, "DEPOSIT", "DIRECT"); accounts.put(key, aTrans); }
private String deriveKey( int account, int id) { StringBuffer buf = new StringBuffer(); buf.append(account); buf.append("-"); buf.append(id); String key = buf.toString();
return key; }
public BankingTransaction getTransaction( int account, int id){ String key = deriveKey(account, id);
return (BankingTransaction)accounts.get(key);
JSON Serialization 93
}
public int putTransaction( int account, BankingTransaction aTrans) {
int id=getNextID(); String key = deriveKey(account,id); aTrans.setId(Integer. toString(id)); accounts.put(key, aTrans);
return id; }
private int getNextID() {return ++lastId;
}
}
Now the variable declaration of txnDao within our AccountResource class simply needs to obtain the instance of the Dao by invoking the getInstance() method, as follows:
BankingTransactionDao txnDao = BankingTransactionDao.getInstance();
However, although this is simple, it’s not the best solution for most cases. A better approach is to consider that JAX-RS provides you with the capability to produce singleton instances of resource classes. In JAX-RS, the normal process is that a new instance of the resource class is created for every request. However, this might not always be the best choice. Even though it is a best practice that resources be stateless (as are the REST services themselves), sometimes a singleton instance can be useful—notably, when it needs to contain cached information to improve performance. Our simple service has another reason for this—to provide a stateful test service that mimics a service implemented on a backing store such as a relational database. You achieve this through the use of the @Singleton annotation. When your resource class contains this annotation, the resource class itself is considered to be a singleton and will live through the lifetime of the server. We show you many examples of @Singleton -annotated resource classes in our more fully fleshed-out example in Chapter 7 .
NOTE
If you’re interested in learning about the Singleton pattern, see Design Patterns, Elements of Reusable Object Oriented Software, by Gamma, et. al.
94 Chapter 4 REST Web Services in WebSphere Liberty
To complete this example, simply create a new class for your BankingTransactionDao and enter the previous code and then modify the AccountResource class to add the variable declaration for the txnDao and the new putTransaction() method we earlier described. You then need to let Eclipse patch up your import list using Source > Organize Imports so that the example compiles cleanly.
Testing POST and Other Actions with RESTClient
Now it’s time to test adding a banking transaction to our newly defined POST resource method in our AccountResource class. However, that brings up a problem: In all the previous examples, we’ve been testing only GET ting a response from a resource, which can be tested in any browser. How can we test POST ing to a resource? That requires you to provide a message body and also (as you’ve already seen) a special Content-Type HTTP header. Essentially, a basic browser won’t do for this case. You can look into several testing options:
• Curl ( http://curl.haxx.se/ ) is a commonly used command-line client tool for transferring data with a URL syntax that can be used over a variety of protocols, including HTTP. Curl is especially useful for scripting if you need to write reusable test scripts.
• rest-client ( http://code.google.com/p/rest-client/ ) is a simple Java GUI application from Google (although it also comes in a command-line version) that can be used for testing REST resources.
The solution we demonstrate in this chapter fits better with our methodology of testing resource methods within the browser: We use RESTClient, a free Mozilla add-on written by Chao Zhou that is available on the Mozilla add-ons site (see https://addons.mozilla.org/en-US/firefox/addon/restclient/ ). Chapter 9 discusses similar plug-ins for Chrome.
Obtaining RESTClient and installing it into Firefox is easy; just visit the site and follow the instructions. To start a RESTClient session, click the red RESTClient icon in the upper-right cor-ner of your screen that is added during the installation process. You will see a new tab that looks something like the one in Figure 4.12 .
When you are ready to test your new service, first select POST from the Method drop-down list. Then type the following URL on the URL line:
http://localhost:9080/RestServicesSamples/banking/accounts/123/transaction
You need to add an appropriate Content-Type header. Click the Headers menu and choose Custom Header; then in the Request Header dialog box, type Content-Type as the Name and application/json as the value before clicking OK to dismiss the dialog box. Finally, type this into the body text area and click Send:
{"currency":"USD","memo":"books","amount":10,"tranType":"PURCHASE","merchant":"Amazon" }
More on Content Negotiation 95
If you look at either of the Response Body tabs, they should show the new ID number of your transaction ( 124 if you’ve added only one BankingTransaction ). Likewise, the Response Header tab should show a status code of 200 OK and a Content-Type of applica-tion/json , as explained in our earlier diagram.
More on Content Negotiation
One of the most challenging parts of writing a resource is determining what Content-Type the resource for each method will accept and what Content-Type will be returned. The problem is that different Content-Type s are better suited for different purposes, as we hinted at earlier. For instance, XML is extremely well suited to Enterprise-level SOA services because a number of languages can parse and generate XML. Likewise, XML has the benefit of a commonly accepted schema language (XML Schema) for defining valid XML documents. This enables you to asso-ciate a particular schema document representing the entire range of valid request or response
Figure 4.12 RESTClient for POST testing
96 Chapter 4 REST Web Services in WebSphere Liberty
bodies with each service that you write—this capability can be useful for creating an Enterprise registry of your services.
However, a great number of services will be mostly consumed by JavaScript code as part of the Modern Web Application architecture we’ve described. Thus, the simplicity and efficiency of JSON needs to be strongly considered also. So in practice, many of the actual services you write will have to handle the possibility of consuming and producing multiple Content-Type s. People have suggested handling this content negotiation problem in a few ways.
You could accept different URI parameters for each content type and then implement dif-ferent methods in your Resource class (each having a different @Path annotation) to differenti-ate between the two. The problem with this approach is that, although it’s simple, it’s not natural. Appending .xml or .json to the end of URI is not something most developers would think to do. Also, it has the problem that you now have two different methods that effectively do the same thing—so any changes thus have to be made in two places.
Another possibility is to use QueryParams . With this solution, you append a ?format= someformat query parameter to the end of each URI or for cases when you want to use a format other than the default (presuming that you remembered to test for the query param-eter being null). Although this avoids the two-method problem of the previous solution, it’s still not natural. It makes the format request not part of the structure of the request URI itself, but something that hangs off the end. The problem with that kind of extension by query parameter is that when it’s begun, it’s hard to stop. 4
The best way to avoid this kind of pain is simply not to follow any of these approaches. HTTP already gives you the right mechanism for negotiating the content type that should be returned, and JAX-RS provides easy support for this approach. To illustrate this, take a look at the following example, which is a new method in the AccountResource class:
@Path("{account}/transaction/{id}")@Produces(MediaType.APPLICATION_XML+ ","+MediaType. APPLICATION_JSON)@GETpublic BankingTransaction getTransaction(@PathParam(value="account")➥int account,@PathParam(value="id") int id){ BankingTransaction aTrans = txnDao.getTransaction(account, id);
return aTrans;}
Note that, in this method, we’ve simply expanded on our earlier examples by adding two different MediaTypes into the @Produces method. Here, if the client states that it wants to receive back JSON, it needs to send along application/json in the Accept header. If the client wants to receive back XML, it sends application/xml instead. Likewise, this method interprets either XML or JSON correctly as its input; it uses the Content-Type header (looking for those same two values) to figure out which is which and determine how to interpret what is sent in.
More on Content Negotiation 97
Testing the new method is simple: After it has been added to the class, go back into the RESTClient in your browser and set the Accept header to application/json . Then perform a GET on the following URL:
http://localhost:9080/RestServicesSamples/banking/accounts/123/transaction/123
The returned value in the body should be in JSON. However, you change the Accept header value to application/xml , you’ll receive the value in XML.
Introducing the JAX-RS Response
So far in our examples, the only thing we’ve ever returned from a Resource method is what cor-responds to the value the client should receive in the best of all possible cases—the case in which the request works. However, in the real world, you often need some more sophisticated error-handling techniques to deal with more complex problems. The JAX-RS spec essentially says that you can return three things from a Resource method. If you return void , that gives you back an empty message body and an HTTP status code 204 ( No Content ). We’ve seen the second case several times: You return an entity of some type, and the status code sent back is HTTP status code 200 ( OK ). However, sometimes it’s important to be able to set your own status codes for more complicated error handling cases. That is where the JAX-RS spec defines one more thing you can return: an instance of javax.ws.rs.core.Response . Response contains methods for adding bodies that have other status codes—for instance, temporaryRedirect() for redi-rect (HTTP status code 307) and, the one we are interested in, status , which we use to send the correct response for a missing resource, HTTP status code 404 ( Not Found ). We demonstrate this in the following code snippet, which is a rewritten version of the getAccount() method from the AccountResource class:
@GET@Path("/{id}")@Produces(MediaType.APPLICATION_XML)public Response getAccount(@PathParam(value="id") int id){ Account value = dao.get(id);
if (value != null)return Response. ok(value).build();
elsereturn Response. status(404).build();
}
Note a couple important points about what we’ve done to this method. First, the return type of the method is no longer Account , but Response . We are using two helpful static methods in Response : The method ok(Object) simply indicates that the response should be built around the object that is passed in as a parameter, and that the HTTP return code should be status code 200. By contrast, the status(int) method indicates that you simply want to return an HTTP
98 Chapter 4 REST Web Services in WebSphere Liberty
status code. Both of these methods actually return an instance of a ResponseBuilder object. You create a Response from the ResponseBuilder by sending it the message build() . You might want to investigate the many other useful methods on the Response class on your own.
Hints on Debugging: Tips and Techniques
So far, we’ve assumed that everything has gone well for you in writing and running these exam-ples. However, that’s not always the case; sometimes you need to debug problems in the code. Eclipse itself provides a lot of helpful features. You can always examine the console log (which is STDOUT), and you can start the server in debug mode (using the bug icon to start it) to set breakpoints and step through your code. However, when the console doesn’t give you enough information to help you determine the cause of your problems, another helpful place to look for more detailed information that is unique to the WebSphere Liberty profile is in your server’s logs directory. We briefly passed by this directory in Chapter 2 when we examined the Liberty directory structure. Look under your WAS Liberty Profile installation directory for /wlp/usr/RESTServer/logs . In particular, if you encounter a problem that keeps a service from execut-ing (for example, a mismatch between the @Produces Content-Type and the annotations that you provide in your entity classes), you can often find helpful information in the TRACEXXX logs that are created in this directory. The FFDC (First Failure Data Capture) logs are also good places to look for additional information in debugging problems.
NOTE
As we’ve mentioned, if you get tired of typing in these examples on your own, you can always download them from the book’s website: www.ibm.com/developerworks/dwbooks/modernwebdev/index.html
Simple Testing with JUnit
One of the best approaches to software development that has emerged in the last 15 years is the notion of Test Driven Development, popularized by Kent Beck as a part of the Extreme Pro-gramming method. Many other agile methods have adopted this principle, and we’ve found it to be extremely useful in our own development as well. A helpful tool that has emerged from this movement is the JUnit testing tool. JUnit enables you to write simple test cases that you can use to validate your own code.
From what you’ve learned in this chapter, you’ve probably concluded that testing at the browser is helpful for fast little validation tests, but it quickly becomes tedious. What’s more, you’ve probably noticed that it is quite error prone and hardly repeatable, especially when you have to use a tool such as RESTClient to manually enter JSON or XML request bodies.
More on Content Negotiation 99
Let’s finish the code examples in this chapter with an example of how to write a JUnit test for one of the previous examples (see Listing 4.9 ).
Listing 4.9 JUnit Test for SimpleAccountResource
package com.ibm.mwdbook.restexamples.tests;import static org.junit.Assert.*;
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;
import org.junit.Test;
public class SimpleAccountResourceTest {
@Testpublic void testGetAccounts() {
String address = "http://localhost:9080/➥RestServicesSamples/banking/simple/accounts"; StringBuffer result = new StringBuffer(); String expectedResult = "<accounts><account>123</account>"+ "<account>234</account></accounts>";
try {
fetchResult(address,result); } catch (MalformedURLException e) { e.printStackTrace();
fail("MalformedURLException caught"); } catch (IOException e) { e.printStackTrace();
fail("IOException caught"); }
assertEquals(expectedResult, result.toString()); }
private void fetchResult(String address,StringBuffer result) ➥throws MalformedURLException,IOException { URL; url = new URL(address); URLConnection conn = url.openConnection();
100 Chapter 4 REST Web Services in WebSphere Liberty
BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream())); String inputLine;
while ((inputLine = in.readLine()) != null) result.append(inputLine); in.close(); }
}
JUnit tests are like most other classes in Java today—they are annotated POJOs. In this case, the annotation @Test (from org.junit.test ) identifies a method as a JUnit test method. A single class can have many test methods, each individually identified. In this excerpt, we show only the test method for the getAccounts() method, which corresponds to a GET to the URL http://localhost:9080/RestServicesSamples/banking/simple/accounts. If you browse the full class definition as included in the sample code, you’ll see that we also include test methods that test retrieving an account that has an account number defined, as well as the error case of retrieving an account that does not have an account number defined. All these methods use a utility method named fetchResult() that uses a URLConnection to fetch the contents of a particular URL.
After fetching the results, we use JUnit assertions (from org.junit.Assert ) to compare the value we receive against an expected value. So if you know the XML or JSON you want to compare against ahead of time, you can easily set up a test that can validate that your code still functions, even after multiple changes.
Running the JUnit Test is extremely easy. Just select the SimpleAccountResourceTest class in the Java EE explorer pane and then right-click and select Run As > JUnit Test from the menu. You should see a result in the bottom-right pane that looks like Figure 4.13 .
Figure 4.13 JUnit test results
RESTful SOA 101
This is an improvement over using a browser for testing, but as you can tell from close inspection of the code, even this approach leaves much to be desired. In particular, the fetchResult() utility method is limited to GET s and does not provide a way to pass in header values or even a message body. You can address each of these issues, but the method becomes more complicated as a result (see the corresponding method in the class AccountResource-Test for an example of exactly how complicated). Thus, you’ll want a better mechanism for invoking the REST APIs than hand-coding it with a URLConnection . In Chapter 7 , you exam-ine using the Apache Wink client for just that purpose.
RESTful SOA
Before closing this chapter, which has been a whirlwind tour of REST, JAX-RS, and JAXB, as well as how to use them in the WebSphere Liberty Profile and Eclipse, we need to talk about the way in which the services we’ve been talking about here relate to the Enterprise services you might also want to implement. The problem is exactly how often the technologies discussed here, as powerful as they are, should be applied.
An old adage that still rings true is, “If all you have is a hammer, everything looks like a nail.” That’s true of technologies as well as physical tools. Another truism is that all technologies follow the “hype cycle,” popularized by the analyst firm Gartner, Inc. 5 In the hype cycle, all tech-nologies first encounter a period of inflated expectations, followed by the inevitable “trough of disillusionment.” In the years since the publication of the predecessor volume to this book, 6 the hype cycle has definitely run its course for Enterprise Web Services with SOAP and the WS-* standards. Many people tried applying the WS-* standards to situations for which they were not appropriate, or when something simpler would definitely have worked better. However, it’s easy to see that the REST services that are rapidly replacing WS-* in the hearts and minds of Enter-prise developers could soon suffer the same fate. You have to be smart about what you’re build-ing when you’re crafting a service and what you’re building it for. Otherwise, REST can simply become another hammer used inappropriately for trying to insert a wood screw.
It also comes down determining what each different service implementation approach is best suited for. REST is about exposing content through HTTP; it does not replace traditional WS-* web services. Traditional web services are much more about program-to-program integra-tion. The WS-* approach allows for a variety of protocols and integrating logic. For example, you might need distributed transactions and message delivery on top of a reliable protocol such as JMS when assured delivery is essential.
Traditional web services built using WS-* standards are about technology abstraction to allow for a wide variety of infrastructures. REST-based web services are about HTTP exploi-tation, to take advantage of a single delivery channel. For example, WS-* abstracts security through WS- Security, enabling you to apply security policies away from the code and abstract-ing the encryption methods and decisions such as token providers. REST-based services, on the other hand, make assumptions, using HTTP security mechanisms such as Open ID or HTTPS for encryption.
102 Chapter 4 REST Web Services in WebSphere Liberty
The real key lies in channel abstraction rather than channel exploitation. REST does not address transactions, reliability, or standard context propagation, or other protocols such as mes-saging. However, these are important considerations for the enterprise as a whole. REST is great for the responsibilities it is meant to handle, but it can’t do everything. The two approaches can coexist in the same enterprise—and they should. Always make sure you choose the right tool for the job.
Summary
This chapter discussed a lot. You’ve seen how the JAX-RS standard defines REST services in Java, you’ve explored how to annotate POJOs with JAXB, and you examined how to implement these services in the WAS Liberty Profile. In the following chapters, you use the things you’ve learned in this chapter to build more complex REST services using JAX-RS; then you connect these to front ends built using JavaScript.
Endnotes
1. See Eclipse Java IDE – Tutorial: www.eclipse.org/resources/resource.php?id=505 .
2. See Configuring JAX-RS applications using JAX-RS 1.1 methods: http://tinyurl.com/latksog .
3. See JSON in JavaScript: www.json.org/js.html .
4. The Google Search REST API ( https://developers.google.com/custom-search/v1/using_rest ) is a particularly egregious example of this: its documentation has multiple pages of required and optional parameters.
5. See Hype Cycles, www.gartner.com/technology/research/methodologies/hype-cycle.jsp .
6. Brown, Kyle et al. Enterprise Java Programming with IBM WebSphere (Second Edi-tion). IBM Press 2004.
This page intentionally left blank
335
Index
A Account class, 83 - 86 Account DAO, 205 - 207 Account Service, 196 - 200 AccountController.js, 248 - 249 AccountDao class, 86 account.html, 247 AccountList application
AccountList.js, 155 - 156 back-end services, invoking,
156 - 157 context object, 156 desktop
mode, 160 view, 153
event handling, 159 - 160 grids
building, 157 - 158 implementing, 154
HTML, 154 internationalization, 163 loading, 152 - 153 , 155 localserver mode, setting, 164 logging in, 165 mobile
version, 161 view, 153
real services, 165 transaction details
loading, 163 template, 162 - 163
translation fi le, 164 accountLoaded() method, 249 AccountResource class, 87 Accounts test spike, 272 AccountTest class
Admin test case, 192 createTransaction test case,
193 - 195 defi nition, 192 methods, 190 test cases, 191 , 209
adapters (Worklight), 218 , 221 - 222
fi les, 233 logic, implementing, 234 - 235 security confi gurations,
235 - 236 testing, 236 - 238 XML, 233
Admin Account Test test case, 192
agile UI design, 49 - 50 design artifacts, creating, 51 learning about users, 50 - 51 process, 50
Ajax (Asynchronous JavaScript and XML), 3 - 4
AMD (Asynchronous Module Defi nition), 126
defi ne() method, 127 - 128 future, 130 JavaScript syntax rules,
263 - 264 overview, 126 primary macros, 128 require() method, 126 - 127
Android ADT Eclipse plug-in,
installing, 324 - 326 Developer Tools, installing,
325 - 326 Development Kit, installing,
324 Emulator, 259 environments, 258 - 259 testing development kit/tools
installation, 326 - 327 annotations
adding to classes, 74 Consumes, 90 - 91 JAXB
JSON, 88 - 90 XML, 83 - 86
336 Index
JAX-RS, 81 Path, 81 PathParam, 82 Produces, 81
Apache Cordova, 11 , 217 Derby
database server confi guration, 186 - 189
installing, 330 - 331 APIs. See REST APIs; web APIs Apple
app caches, disabling, 281 hybrid-based mobile apps,
running, 256 - 257 iOS
SDK, 6 Simulator, 257
Application Center (Worklight), 220
Application subclass, 73 - 74 ApplicationController class, 146 applications
controllers, 115 - 116 banking example, 146 mapping, 123 module loading, 115 navigation routing, 116 template, 148 - 149
deploying Eclipse, 45 - 48 Liberty profi le, 43
hybrid. See hybrid applications
initializing banking example, 143 Dojo toolkit, 134 - 135
JAX-RS, 68 layers
bank example, 180 DAO, 183 database schema, 182 domain objects, 183 Java EE architecture, 179 JAX-RS services, 181 - 182 utility classes, 185
logging in, 165 mobile. See mobile
applications
packaging, 216 servers, 1 sharing, 220 testing
REST service greeting, 78 - 79
sampleServer, 44 - 45 Worklight, 216
Worklight structure, 223 - 224 architecture
classic web, 1 client-side
application controllers, 115 - 116
banking example. See client-side architecture, banking example
building principles, 114 confi guration layer, 121 data storage and
caching, 121 design, 103 Dojo Mobile, 106 error handling, 120 - 121 frameworks, 106 , 122 - 123 jQuery, 106 mobile frameworks,
104 - 105 multichannel
applications, 108 MVC, 116 - 120
enterprise infrastructure. See enterprise infrastructure architecture
mobile application deployment. See mobile applications, deployment
RESTful web services, 66 - 67 effective
characteristics, 67 prospect URI example, 66
servers, 36 Worklight
Server, 221 - 222 shells, 223 Studio, 215
aspect-oriented connectivity, 292 assertions, 270
Asynchronous JavaScript and XML (Ajax), 3 - 4
Asynchronous Module Defi nition. See AMD
attach-events, 138 attach points (templates),
138 , 149 attack paths (mobile
security), 303 Audit tab (Chrome DevTools),
277 authentication
adapter-based, 235 - 236 mobile
application deployment, 218
security, 304 authorization (mobile
security), 304
B back-end
data sources, generating, 172 interactions sequence
diagram, 175 - 176 services, invoking, 156 - 157
Backbone, 230 banking example, 36
Account class, 83 - 86 account list. See AccountList
application Account Test. See
AccountTest class AccountDao class, 86 adapters
fi les, 233 logic, implementing,
234 - 235 security confi guration,
235 - 236 testing, 236 - 238 XML, 233
application controller, 146 , 148 - 149
application layers, 180 DAO, 183 database schema, 182
Index 337
domain objects, 183 JAX-RS services, 181 - 182 utility classes, 185
ApplicationController class, 146
attach points, 149 bank
administrator actions diagram, 175 - 176
customer actions diagram, 174 - 175
rules, creating, 208 - 209 transactions, adding,
94 - 95 BankingApplication class, 74 BankingTransaction class,
88 - 90 BankingTransactionDao
class, 92 - 94 Bijit superclass, 147 - 148 bookmarking, implementing,
150 - 152 DAO
Account, 205 - 207 Transaction, 207 - 208
desktop web menu, 149 domain objects
Account, 202 - 203 Transaction, 203 - 205
DoradoBank folder structure common, 240 environment, 240 - 242
frameworks, 141 hybrid-based mobile
application. See mobile applications, hybrid-based
importing projects, 140 JAX-RS annotations example
annotations, 81 - 82 services needed, 80 SimpleAccountResource
class, 80 testing, 82
JSON model, defi ning, 26 menu template, 254 - 255 mobile web menu, 150 REST APIs, defi ning,
176 - 178
REST services Account Service, 196 - 200 JAXRS providers,
confi guring, 196 Transaction Service,
200 - 201 Web application project
structure, 195 SimpleAccountResource
class, 99 - 100 stubbed JSON location, 141 team organization, 19 - 20 Transaction list JSON
model, 179 transaction-posting method,
90 - 91 UCD. See UCD UI design. See UI design
BankingApplication class, 74 BankingTransaction class, 88 - 90 BankingTransactionDao class,
92 - 94 BankRules class, 208 - 209 Beck, Kent, 98 Bijit class, 147 - 148 bin folder (Worklight
Server), 238 bookmarking, implementing,
150 - 152 Bootstrap, 148 bring your own device
(BYOD), 303 browsers
as debuggers, 272 - 273 Chrome DevTools. See
Chrome DevTools multiple browsers, 273
mobile devices, 8 plug-ins, 279 - 280
performance analyzers, 280
REST Client, 280 web developer, 280
remote debugging Chrome, 285 Safari, 284
resource methods, testing, 94 - 95
build systems, mapping, 122 business factors (mobile
development), 13 - 15 business rules, creating, 208 - 209 BYOD (bring your own
device), 303
C Cache-Control directive, 297 caching
client-side architectures, 121 disabling, 281 performance, improving,
296 - 297 response directives,
297 - 298 server-side caching,
298 - 302 predictive, 301
Canonical Data Model, 172 Cascading Style Sheets. See CSS Cast Iron adapters, 222 CDI (Contexts and Dependency
Injection), 171 , 196 - 200 channel shifting, 53 Chrome DevTools, 273
Audit tab, 277 Console tab, 277 - 279
Inspector, 279 logging methods, 277 module/method names,
278 multiple arguments, 279 output, 279
Elements tab, 274 - 275 Network tab, 275 - 276 Profi les tab, 277 Resources tab, 273 - 274 , 275 Sources tab, 276 - 277 Timeline tab, 277
Chrome remote debugging, 285 classes
Account, 83 - 86 AccountDao, 86 AccountResource, 87 AccountTest
Admin test case, 192 createTransaction test
case, 193 - 195
338 Index
defi nition, 192 methods, 190 test cases, 191
annotations, adding, 74 ApplicationController, 146 BankingApplication, 74 BankingTransaction, 88 - 90 BankingTransactionDao,
92 - 94 BankRules, 208 - 209 Bijit, 147 - 148 MWBApplication, 196 POJO annotated, creating,
83 - 86 Prospect, 37 resource
creating, 71 - 72 parameter information
sources, 82 Path annotation, 81 Produces annotation, 81
Response, 97 - 98 SimpleAccountResource
creating, 80 JUnit testing, 99 - 100
singletons, 92 - 94 utility, 185
classic web architecture, 1 client-side architectures
application controllers, 115 - 116
module loading, 115 navigation routing, 116
banking example application initialization,
143 confi guration fi le, 144 index.html fi le, 141 - 143 stub fi les, 145
building principles, 114 confi guration layer, 121 data storage and caching, 121 defi ning, 104 - 108 design, 103 error handling, 120 - 121 frameworks, mapping,
122 - 123
mobile frameworks, 104 - 105 choosing, 106 Dojo, 106 jQuery, 106
multichannel applications, 108
MVC. See MVC cloud computing, 310 - 313 clustering, 292 CMP Entity Bean, 31 code, example fi les, 333coherence (multichannel
design), 53 combination multichannel
development, 16 common folder (hybrid-based
mobile app), 240 compatibility (Liberty
profi le), 34 complementarity (multichannel
design), 53 composite, 56 confi guring
client-side architectures, 117 JAXRS providers, 196 servers, 186 - 189
Console (Worklight), 219 Console tab (Chrome DevTools),
277 - 279 Inspector, 279 logging
methods, 277 module/method names,
278 multiple arguments, 279 output, 279
constructor() method, 136 Consumes annotation, 90 - 91 content types (resource
methods), 96 - 97 context
JavaScript, 264 - 267 object, 156
Contexts and Dependency Injection (CDI), 171 , 196 - 200
Cordova, 11 , 217 Core J2EE Patterns (Alur, et.
al), 86
create, read, update, delete (CRUD) interaction pattern, 56
createHandler() method, 250 createTransaction test case,
193 - 195 Crockford, Douglas, 262 - 263 cross-domain Ajax security,
disabling, 283 CRUD (create, read, update,
delete) interaction pattern, 56 CSS (Cascading Style Sheets)
CSS3 rules, 267 - 268 media queries
example, 109 - 110 HTML, 111 - 112
syntax rules, 267 - 268 cssvalidator plug-in, 268 Curl, 94 custom launchers
creating, 281 - 282 icon, editing, 282
D DAOs (Data Transfer Objects)
application layers tier, 183 banking example
Account, 205 - 207 Transaction, 207 - 208
data source, retrieving, 38 - 39 defi ning, 37 get() method, 39 - 40 XML-based web services,
86 - 87 data
binding, mapping, 122 caching, 121 Domain Model, 172
domain object, 202 - 203 Transaction domain
object, 203 - 205 fl ows (Modern Web
Applications), 5 sources, retrieving, 38 - 39 storage, 121
Data Tier application layers
bank example, 180 DAO, 183
Index 339
database schema, 182 domain objects, 183 Java EE architecture, 179 JAX-RS services, 181 - 182 utility classes, 185
Canonical Data Model, 172 front-end/back-end
interactions sequence diagrams, 174 - 176
JSON defi ning, 178 - 179 generating from back-end
data sources, 172 REST APIs, defi ning,
176 - 178 User Model, 173
Data Transfer Object. See DAOs database schema, 182 debugging. See also testing
with browsers, 272 - 273 Chrome DevTools, 273
Audit tab, 277 Console tab, 277 - 279 Elements tab, 274 - 275 Network tab, 275 - 276 Profi les tab, 277 Resources tab, 275 settings, 273 - 274 Sources tab, 276 - 277 Timeline tab, 277
HTML, 261 - 262 JavaScript
AMD, 263 - 264 context, 264 - 267 CSS, 267 - 268 external data, 269 global variables, 263 JSLint.com tool, 263
jsFiddle tool, 285 - 286 JUnit testing tool, 98 - 100 mobile web applications
app caches, disabling, 281 cross-domain Ajax
security disabling, 283 nonwrapped
simulator, 283
remote, 284 Chrome, 285 Safari, 284
tips and techniques, 98 defi ne() method
AccountController.js, 249 AMD, 127 - 128
demilitarized zone. See DMZ deploying
applications Eclipse, 45 - 48 Liberty profi le, 43
mobile applications. See mobile applications
Worklight Console, 219 Worklight Server
artifacts, 239 design
artifacts, creating, 51 bank example
account summary view, 60
bank use case diagram, 58 larger form factor, 62 much larger form
factor, 62 transaction details, 61 transaction summary
view, 60 client-side architectures, 103 hybrid applications, 227 mobile apps, 57 - 58 multichannel, 52 - 53
channel shifting, 53 coherence, 53 complementarity, 53 Enterprise
expectations, 52 screen sharing, 53 simultaneity, 53 synchronization, 53 user expectations, 52
patterns, 55 responsive, 109
CSS media queries, 109 - 110
example, 109 feature detection, 114
grid-based frameworks, 112
HTML for CSS media queries, 111 - 112
Micro Responsive Design, 113 - 114
ranges, 112 UI design phase, 113
UI. See UI design websites, 51
desktops applications, 160 grids, building, 157 - 158 mobile devices, compared, 7 web and mobile convergence.
See multichannel design web menu (banking
example), 149 destroy() method, 136 development machine
installation, 315 - 316 Eclipse Juno IDE, v4.3,
317 - 318 Java Runtime Environment,
v1.7, 316 source code for book
examples, 319 - 321 WebSphere Liberty Profi le
Developer Tools, v8.5.5, 318 - 319
development styles (mobile) business factors, 13 - 15 HTML 5, 9 native mobile, 8 summary, 7 web applications, 8
DGrid website, 154 dijits
future, 130 overview, 124 widgets, creating, 136
dependencies, 139 instantiating, 139 lifecycle events, 136 module basis example,
137 - 138 templates, 138
disabling app caches, 281
340 Index
display form interaction pattern, 56
DMZ (demilitarized zone) overview, 287 secure gateway, 288 server roles, 288
DOH (Dojo Objective Harness), 125 , 270
Dojo AMD
defi ne() method, 127 - 128 overview, 126 primary macros, 129 require() method, 126 - 127
banking account list application
account list component, 152 - 153
AccountList.js, 155 - 156 application controller
template, 148 - 149 ApplicationController
class, 146 attach points, 149 back-end services,
invoking, 156 - 157 Bijit superclass, 147 - 148 bookmarking,
implementing, 150 - 152 context object, 156 desktop mode, 160 event handling, 159 - 160 grids, building, 157 - 158 grids, implementing, 154 HTML, 154 internationalization, 163 loading account lists, 155 localserver mode, setting,
164 logging in, 165 mobile version, 161 real services, 165 transaction detail
template, 162 - 163 transaction details,
loading 163 translation fi le, 164
benefi ts, 125
client-side architectures, building, 114
Deferred Objects, 144 dojo router website, 150 future, 129 HTML example
applications, initializing, 134 - 135
body content, 135 - 136 confi guring Dojo, 132 explanation, 130 HTML declaration, 132 loading dojo, 134 styling, 132
Mobile, 106 object orientation
website, 146 Objective Harness. See DOH overview, 106 , 123 packages, 124
dijits, 124 Dojo, 124 dojox, 124 util, 125
website, 123 widgets, creating, 136
dependencies, adding, 139 instantiating, 139 lifecycle events, 136 module basis example,
137 - 138 superclass, 146 templates, 138
dojoConfi g global variable, 132 dojox, 124 Domain Model, 172
domain object, 202 - 203 Transaction domain object,
203 - 205 domain objects
Account, 202 - 203 application layers, 183 Transaction, 203 - 205
doPost() method, 38 DoradoBank folder structure
common, 240 environment, 240 - 242
DoradoBankAdapter fi les, 233
DoradoBank.html fi le, 242 - 243 DoradoBank.js, 246 dynamic CSS compilers/
interpreters, mapping, 122 dynamic pages, rendering,
246 - 247
E Eclipse
Android ADT plug-in, installing, 325 - 326
applications, deploying, 45 - 48
debugging, 98 Juno IDE, v4.3, installing,
317 - 318 EJBs (Enterprise JavaBeans), 33 ,
168 - 170 3.0
container, 168 Java annotations, 169 POJOs, 169 specifi cation history, 168
3.1 asynchronous
methods, 170 JAXRS components,
implementing, 196 - 200 Lite, 170 Singletons, 169
CDI (Contexts and Dependency Injection), 170
Elements tab (Chrome DevTools), 274 - 275
endpoint management, 303 engaging enterprises, 307 - 308
cloud computing, 310 - 313 mobile-fi rst development,
308 - 309 polyglot programming, 310 web APIs, managing, 309
enterprise infrastructure architecture
DMZ overview, 287 security gateway, 288 server roles, 288
Index 341
ESB aspect-oriented
connectivity, 292 implementing, 292 integration, 290 - 292 overview, 291 service virtualization, 291
Web API and secure gateway, 289
Worklight as channel entry point, 289
WXS caching servers, 292 Enterprise JavaBeans. See EJBs Enterprise services, 101 - 102 entity parameters, handling, 91 environment folders
(hybrid-based mobile app), 240 - 242
Environment Optimization technology, 216
error handling, 120 - 121 ESB (Enterprise Services
Bus), 290 aspect-oriented
connectivity, 292 implementing, 292 overview, 291 service virtualization, 291 Worklight and Liberty
integration, 290 event handling, 159 - 160 Expires directive, 297 external data (JavaScript), 269
F facets, modifying, 70 feature detection
multichannel development, 15
MVC, 119 responsive design, 114
Fiberlink MaaS 360, 303 Fielding, Roy, 4 FIrebug debugger, 272 folder structure (hybrid-based
mobile app) common, 240 environment, 240 - 242
forms defi ned, 56 factors
client-side architectures, 108
larger, 62 much larger, 62 Worklight skins, 217
frameworks Apache Cordova, 11 , 217 Backbone, 230 banking example, 141 client-side architectures
choosing, 106 Dojo, 106 jQuery Mobile, 106 mobile, 104 - 105
grid-based, 112 Handlebars. See Handlebars JPA, 171 - 172
instances, fi nding, 172 lifecycle, 171 - 172 overview, 171
jQuery, 106 client-side architectures,
building, 114 future, 130 overview, 229
jQuery Mobile hybrid-based mobile app
default HTML content, 243
login pages, 251 overview, 229
mapping, 122 - 123 OSGi, 32 RequireJS
hybrid-based mobile app example fi le, 244 - 245
login pages, 251 overview, 229
Underscore, 230 unit testing, 270
front-end/back-end interactions sequence diagram, 174 - 176
G Garrett, Jesse James, 3 gateways (security), 288 get() method
data source, retrieving, 38 ProspectDAO example,
39 - 40 getAccount object, 156 getAccounts() method, 234 , 249 getCurrentAccount()
method, 249 getTransactions() method,
200 , 234 global variables
(JavaScript), 263 GreetingResource class, creating,
71 - 72 grids
desktop/mobile, building, 157 - 158
frameworks, 112 implementing, 154
H Handlebars
account template, 251-252 expression language, 252 hybrid-based mobile app
defi ning templates, 243 dynamic page, rendering,
246 - 247 menu template, 254 - 255 overview, 230 view, 252
handleChallenge() method, 250 handling
errors, 120 - 121 events, 159 - 160
headers, versioning, 294 Hello World application, 68 - 74
Application subclass, 73 - 74 facets, modifying, 70 GreetingResource class,
creating, 71 - 72 testing, 78 - 79 web project, creating, 68 - 70 WebSphere Liberty server,
creating, 74 - 78
342 Index
Hewitt, Joe, 272 history
Ajax, 3 - 4 application servers, 1 classic web architecture, 1 Java EE, 1 Modern Web Applications
advantages, 6 competition, 6 data fl ows, 5 mobile technologies, 6
open source frameworks, 3 RIA, 5 WAS, 29 - 31 Web 2.0, 4
HTML consistency rules, 261 - 262 CSS media queries, 111 - 112 Dojo example
applications, initializing, 134 - 135
body content, 135 - 136 confi guring Dojo, 132 explanation, 130 HTML declaration, 132 loading dojo, 134 styling, 132
HTML 5, 9 hybrid-based mobile apps
main fi le, 242 - 243 invalid, fi nding, 262 lexical analyzer, 262 XML, compared, 261
HTTP adapters, 222 hybrid applications, 11 , 227
AccountController, 248 - 249 Adapters. See adapters design, 227 dynamic pages, rendering,
246 - 247 HTML page implementing a
jQuery page, 246 - 247 init() method, 246 login page, 251 - 252 LoginController, 249 - 250 main HTML fi le, 242 - 243
menu template, 254 - 255 view, 252 - 254
projects, importing, 230 - 231 require.js fi le, 244 - 245 router logic, 248 running
Android environments, 258 - 259
iOS Simulator, 257 Macs, 256 - 257 Mobile Browser
Simulator, 256 preview mode, 255
UI design, 227 Worklight folder
structure, 232 common, 240 environment, 240 - 242
Worklight Server artifacts, 238 - 239
I IaaS (Infrastructure as a Service),
311 IBM design websites, 51 implementing
adapter logic, 234 - 235 ESB, 292 grids, 154 JAX-RS
components as EJB 3.1, 196 - 200
resources, 87 MVC patterns, 118 views with templates,
162 - 163 Import Project Wizard, 230 importing sample projects, 140 ,
189 , 230 - 231 improving performance, 294 - 295
caching, 296 - 297 response, 297 - 298 server-side, 298 - 302
pagination, 295 - 296 Infrastructure as a Service
(IaaS), 311
init() method, 246 initialize() method, 248 , 252 initializing applications
banking example, 143 Dojo toolkit, 134 - 135
Inspector (Chrome DevTools), 279
installing Android
Developer Tools, 325 - 326 Development Kit, 324
Apache Derby, v10, 330 - 331 Eclipse Juno IDE, v4.3,
317 - 318 Java Runtime Environment,
v1.7, 316 source code for book
examples, 319 - 321 WebSphere Liberty Profi le
Developer Tools, v8.5.5, 318 - 319
WebSphere Liberty Profi le, v8.5.5, 329
Xcode, 327 instance variable tokens, 138 instantiating widgets, 139 integrated SDKs, 216 interaction patterns, 55 - 57 interactive user interfaces,
mapping, 123 interface transformation
virtualization, 291 internationalization, 163 iOS
SDK, 6 Simulator, 257
isCustomResponse() method, 250
J J2EE evolution, 30 Java
annotations, 169 adding to classes, 74 Consumes, 90 - 91 JAXB, 83 - 86 , 88 - 90 JAX-RS, 81
Index 343
Path, 81 PathParam, 82 Produces, 81
JAX-RS application layers,
181 - 182 defi ned, 67 entity parameters,
handling, 91 goals, 67 - 68 Hello World application,
68 - 74 resources/applications, 68
JSON, 88 annotations, 88 - 90 Consumes annotation,
90 - 91 entity parameters,
handling, 91 generating from back-end
data sources, 172 singletons, 92 - 94 stubbed, locating, 141 testing resource methods
within browsers, 94 - 95 Runtime Environment (JRE),
v1.7, installing, 316 Java EE, 1
application layers, 179 DAO, 183 database scheme, 182 domain objects, 183 JAX-RS services, 181 - 182 utility classes, 185
Contexts and Dependency Injection (CDI), 171 , 196 - 200
EJBs. See EJBs evolution, 30 - 31 JPA, 171 - 172
instances, fi nding, 172 lifecycle, 171 - 172 overview, 171
servers confi guring, 186 - 189 creating, 168
test-driven development. See test-driven development
typical application architecture, 179
v6 Web profi le specs, 167 - 168
v7/v8.5 specs, 168 JavaScript
debugging AMD, 263 - 264 context, 264 - 267 CSS, 267 - 268 external data, 269 global variables, 263 JSLint tool, 263
Object Notation (JSON). See JSON
templates, 117 JavaScript: The Good Parts
(Crockford), 262 JavaServer Faces (JSF), 3 JAXB annotations
JSON, 88 - 90 XML, 83 - 86
JAX-RS Account Service, 196 - 200 annotations
Path, 81 PathParam, 82 Produces, 81
application layers, 181 - 182 defi ned, 67 entity parameters,
handling, 91 goals, 67 - 68 Hello World application,
68 - 74 Application subclass,
73 - 74 facets, modifying, 70 GreetingResource class,
creating, 71 - 72 testing, 78 - 79 web project, creating,
68 - 70 WebSphere Liberty
server, creating, 74 - 78 implementing as EJB 3.1
components, 196 - 200 JSON annotations, 88 - 90
providers, confi guring, 196 resources, 68 , 87 Response, 97 - 98 singletons, 93 Transaction Service, 200 - 201 web APIs, 211
JMS adapters, 222 JPA persistence framework,
171 - 172 instances, fi nding, 172 lifecycle, 171 - 172 overview, 171
jQuery, 106 client-side architectures,
building, 114 future, 130 overview, 229
jQuery Mobile hybrid-based mobile app, 243 login pages, 251 overview, 229
JRE (Java Runtime Environment), v1.7, installing, 316
JSF (JavaServer Faces), 3 jsFiddle tool, 285 - 286 JSLint website, 263 JSON (JavaScript Object
Notation), 88 annotations, 88 - 90 Consumes annotation, 90 - 91 defi ning
Account list example, 178 DoradoBank example, 26 Transaction list example,
179 entity parameters,
handling, 91 generating from back-end
data sources, 172 singletons, 92 - 94 stubbed, locating, 141 testing resource methods
within browsers, 94 - 95 JSP (JavaServer Pages), 33 JUnit
test cases, running, 209 testing tool, 98 - 100
344 Index
L larger form factor, 62 layouts
CSS media queries example, 109 - 110 HTML, 111 - 112
ranges, 112 shells, 117
lexical analyzer (HTML), 262 Liberty profi le
applications deploying, 43 testing, 44 - 45
compatibility, 34 Developer Tools,v8.5.5,
installing, 318 - 319 enterprise infrastructure
architecture DMZ, 287 - 288 ESB integration, 290 - 292 security gateway, 289 web API and secure
gateway, 289 Worklight as channel
entry point, 289 WXS caching servers, 292
installing, 329 JAX-RS Hello World
application, 68 - 74 Application subclass,
73 - 74 facets, modifying, 70 GreetingResource class,
creating, 71 - 72 testing, 78 - 79 web project, creating,
68 - 70 WebSphere Liberty
server, creating, 74 - 78 overview, 33 - 34 reliability through
clustering, 292 RESTful web services
DAOs, 86 - 87 JAXB annotations, 83 - 86 JSON. See JSON servers, creating, 74 - 78
sample server.xml, 34 - 36
servers applications, running, 209 architecture, 36 confi guring, 186 - 189 creating, 42 - 43 , 185
testing installation, 329 - 330 Web 1.0 pattern example,
36 - 41 data source, retrieving,
38 - 39 Data Transfer Object, 37 get() method, 39 - 40 HTML forms page posting
to Java Servlet, 37 servlet doPost() method,
37 - 38 WXS server-side
caching, 300 lifecycles
JPA, 171 - 172 widget events, 136
linked list interaction pattern, 56 list to list interaction pattern, 56 listings
Account class, 84 - 85 Account DAO, 206 Account domain object, 202 Account JSON stub data, 178 Account Service, 196 - 200 Account Test
Admin test case, 193 createTransaction test
case, 193 - 195 AccountDao class, 86 account.html, 247 AccountList component, 152 AccountList event
handling, 159 AccountList HTML, 154 AccountList.js, 155 AccountList mobile response,
159 AccountList rendering
logic, 157 AccountResource class, 87 AccountTest class, 192 adapter logic, 234 app initialization, 143 app.js init method, 144
application controller template, 148
ApplicationController class, 146
ApplicationController.js, 150 banking example client-side
architecture, 142 - 143 BankingApplication class, 74 BankingTransaction class, 88 BankingTransactionDao
class, 92 BankRules class, 208 Bijit superclass, 147 CSS media query, 110 CSS3 rules with vendor
prefi xes, 268 defi ne() method in AMD, 128 getAccount object, 156 GreetingResource class, 72 HTML for media query, 111 JAXRS MWBApplication
class, 196 Liberty profi le sample server.
xml, 34 loading
dojo, 134 transaction details, 163
login.html, 251 menu template, 254 MenuRenderer.js, 253 module/method names in
login, 278 require() method in
AMD, 126 require statements,
nesting, 135 require.js confi g fi le, 245 responsive design ranges, 112 server confi guration, 34, 187 servlets and JSP features
required, 33 SimpleAccountResource
class, 80 stub URLs, 145 Transaction DAO, 207 Transaction domain object,
203-205 Transaction JSON stub
data, 179
Index 345
Transaction Service, 200 translation fi le, 164 translation substitution, 164 Web 1.0 Liberty profi le
example data source, retrieving, 38 get() method, 39 index.html fi le, 37 Prospect class, 37 servlet doPost() method,
37 - 38 widgets
module example, 137 parsing, 134 templating, 138
lists, 56 loadAccountList() method, 155 loading
AccountList component, 152 - 153
dojo, 134 modules, 115 transaction details, 163
localserver mode, setting, 164 location virtualization, 291 logging
Chrome console methods, 277 module/method names,
278 multiple arguments, 279 output, 279
logging in, 165 , 251 - 252 login() method, 250 LoginController.js, 249 - 250
M MaaS 160, 303 Macs
app caches, disabling, 281 hybrid-based mobile apps,
running, 256 - 257 iOS
SDK, 6 Simulator, 257
master detail interaction pattern, 56
MEAP (Mobile Enterprise Application Platform) vendors, 11
media queries (CSS) example, 109 - 110 HTML, 111 - 112
menu template, 254 - 255 MenuRenderer.js, 253 Message Driven Beans, 169 methods
accountLoaded(), 249 AccountTest class, 190 constructor(), 136 createHandler(), 250 defi ne()
AccountController.js, 249 AMD, 127 - 128
destroy(), 136 doPost(), 38 get()
data source, retrieving, 38 ProspectDAO example,
39 - 40 getAccounts(), 234 , 249 getCurrentAccount(), 249 getTransactions(), 200 , 234 handleChallenge(), 250 init(), 246 initialize(), 248 , 252 isCustomResponse(), 250 loadAccountList(), 155 login(), 250 postCreate(), 136 postMixinProperties(), 136 render(), 252 require(), 126 - 127 resources
content types, 96 - 97 testing within browsers,
94 - 95 runAccounts(), 248 runLogin(), 251 wlCommonInit(), 246
Micro Responsive Design, 113 - 114
mobile applications bank example
account summary view, 60
larger form factor, 62 transaction details, 61 transaction summary
view, 60 banking account list
example, 161 characteristics, 11 - 13 context, 11 deployment
application sharing, 220 authentication, 218 device runtime, 216 - 217 enterprise resources,
exposing, 218 native device
functionality, accessing, 217
push notifi cations, 218 server-side functionality,
accessing, 218 Worklight component
interactions, 220 - 221 Worklight Console, 219 Worklight skins, 217
frameworks, 104 - 105 grids, building, 157 - 158 hybrid-based, 11
AccountController, 248 - 249
adapter fi les, 233 adapter logic,
implementing, 234 - 235 adapter XML, 233 Android environments,
258 - 259 common folder, 240 design, 227 dynamic pages, rendering,
246 - 247 environment folders,
240 - 242 Handlebars template, 252 Handlebars View, 252 HTML page
implementing a jQuery page, 246 - 247
init() method, 246 iOS Simulator, 257
346 Index
launching from Macs, 256 - 257
login page, 251 - 252 LoginController, 249 - 250 main HTML fi le, 242 - 243 menu template, 254 - 255 menu view, 252 - 254 Mobile Browser
Simulator, running, 256 preview mode, 255 projects, importing,
230 - 231 require.js fi le, 244 - 245 router logic, 248 security confi guration,
235 - 236 testing adapters, 236 - 238 Worklight folder
structure, 232 Worklight Server artifacts,
238 - 239 mobile web advantages, 9 - 10 native versus mobile web,
10 - 11 remote debugging, 284
Chrome, 285 Safari, 284
targeted versus multichannel, 57 - 58
testing/debugging app caches, disabling, 281 cross-domain Ajax
security, disabling, 283 nonwrapped
simulator, 283 web menu (banking
example), 150 Mobile Browser Simulator, 256 mobile devices
browsers, 8 desktop web and mobile
convergence. See multichannel design
desktops, compared, 7 development styles
business factors, 13 - 15 summary, 7
fueling Modern Web Applications, 6
runtime, 216 - 217 Worklight, 18 - 19
Mobile Enterprise Application Platform (MEAP) vendors, 11
mobile-fi rst development, 214 - 215 , 308 - 309
mobile security attack paths, 303 authentication, 304 authorization, 304 BYOD (bring your own
device), 303 layers, 302 protection, 303
Model component, 116 Model-View-Controller. See
MVC Modern Web Applications
advantages, 6 competition, 6 data fl ows, 5 mobile technologies, 6
Modern Web Development with IBM WebSphere website, 98 , 315
modules loading, 115 mapping, 122 widgets, 137 - 138
much larger form factor, 62 multichannel design, 15 - 16 ,
52 - 53 , 108 channel shifting, 53 coherence, 53 complementarity, 53 Enterprise expectations, 52 mobile applications, 57 - 58 screen sharing, 53 simultaneity, 53 synchronization, 53 user expectations, 52
multiple language programming, 310
MVC (Model-View-Controller), 55 , 116 - 120
confi guration component, 117 feature detection, 119
implementing, 118 JavaScript templates, 117 layout shells, 117 Model, 116 screen navigation/history,
118 security component, 117 storing/retrieving data, 117 View component, 116
MWBApplication class, 196
N native device functionality,
accessing, 217 native mobile applications, 8 ,
10 - 11 native shell, mapping, 122 navigation routing, 116 nesting require statements, 135 Network tab (Chrome
DevTools), 275 - 276 networking (DMZ)
overview, 287 secure gateway, 288 server roles, 288
O O’Reilly, Tim, 4 objects
Account domain, 202 - 203 context, 156 getAccount, 156 POJOs, 32
annotated classes, creating, 83 - 86
EJB 3, 169 Transaction domain, 203 - 205
online LINT checker website, 268
open source frameworks, 3 Backbone, 230 Handlebars. See Handlebars jQuery
client-side architectures, building, 114
future, 130 overview, 229
Index 347
jQuery Mobile hybrid-based mobile app
default HTML content, 243
login pages, 251 overview, 229
RequireJS hybrid-based mobile app
example fi le, 244 - 245 login pages, 251 overview, 229
Underscore, 230 Oracle JRE download, 316 organizing teams, 19 - 20 OSGi framework, 32
P PaaS (Platform as a Service), 311 packages
Dojo toolkit dijits, 124 Dojo, 124 dojox, 124 util, 125
managers, 122 packaging applications, 216 page-oriented user interfaces,
53 - 54 pagination, 295 - 296 parameters
entity, handling, 91 information sources, 82
parsing widgets, 134 Path annotation, 81 PathParam annotation, 82 patterns
design, 55 interaction, 55
applying, 57 composite, 56 CRUD, 56 Display Form, 56 forms, 56 Linked List, 56 List to List, 56 lists, 56 Master Detail, 56
Search Form, 56 Search List, 56 Simple List, 56 Table List, 56 Update Form, 56 Validating Form, 56 Validating Form
Wizard, 56 MVC, 55
performance analyzer browser plug-ins, 280
performance, improving, 294 - 295
caching, 296 - 297 response, 297 - 298 server-side, 298 - 302
pagination, 295 - 296 persistence, 171 - 172 Plain Old Java Object. See
POJOs Platform as a Service (PaaS), 311 plug-ins
Android ADT Eclipse plug-in, installing, 325 - 326
browsers, 279 - 280 performance
analyzers, 280 REST Client, 280 web developer, 280
POJOs (Plain Old Java Objects), 32
annotated classes, creating, 83 - 86
EJB 3, 169 polyglot programming, 310 postCreate() method, 136 Postman REST Client
plug-in, 280 postMixinProperties()
method, 136 predictive caching, 301 preview mode, launching, 255 primary Dojo macros, 128 procedures (Worklight), 222 Produces annotation, 81 Profi les tab (Chrome
DevTools), 277 programming model changes,
31 - 33
progressive enhancement, 309 projects, importing, 140 , 189 ,
230 - 231 Prospect class, 37 protecting mobile devices
authentication, 304 authorization, 304 endpoint management, 303
protocol and interaction virtualization, 291
push notifi cations, 218
Q - R QUnit, 270 ranges (screen design), 112 reliability through
clustering, 292 remote debugging, 284
Chrome, 285 Safari, 284
render() method, 252 Representational State Transfer.
See REST require() method, 126 - 127 require statements, nesting, 135 RequireJS
hybrid-based mobile app example fi le, 244 - 245
login pages, 251 overview, 229
resources classes
creating, 71 - 72 parameter information
sources, 82 Path annotation, 81 Produces annotation, 81
content types, 96 - 97 JAX-RS, 68 , 87 methods, 94 - 95 semantic changes, 293 structure changes, 293 URIs, versioning, 293 - 294
Resources tab (Chrome DevTools), 275
response caching, 297 - 298 Response class (JAX-RS), 97 - 98
348 Index
responsive design, 109 CSS media queries, 109 - 110 example, 109 feature detection, 114 grid-based frameworks, 112 HTML for CSS media
queries, 111 - 112 Micro Responsive Design,
113 - 114 multichannel
development, 15 ranges, 112 UI design phase, 113
REST (Representational State Transfer), 4
APIs. See REST APIs Client, 94
browser plug-in, 280 resource methods, testing,
94 - 95 website, 94
defi ned, 17 endpoints, testing. See
test-driven development JAX-RS
defi ned, 67 goals, 67 - 68 Hello World application,
68 - 74 resources/applications, 68
misconceptions, 17 philosophies, 65 servers
confi guring, 186 - 189 creating, 168
services advantages over
Worklight, 223 - 224 disadvantages over
Worklight, 225 - 226 JAX-RS Account Service,
196 - 200 provider, confi guring,
196 Transaction Service,
200 - 201 pagination, 295 - 296 Web application, 195
User Model, 173 web APIs, creating, 18 web services. See web
services REST APIs
application layers bank example, 180 DAO, 183 database schema, 182 domain objects, 183 Java EE architecture, 179 JAX-RS services, 181 - 182 utility classes, 185
calling with Apache Wink client API, 192
defi ning, 26 , 176 - 178 front-end/back-end
interactions sequence diagrams, 174 - 176
retrieving data sources, 38 - 39 RIA (Rich Internet
Applications), 5 routing, mapping, 123 runAccounts() method, 248 runLogin() method, 251 running applications
Android environments, 258 hybrid-based mobile app, 255 iOS Simulator, 257 Mobile Browser
Simulator, 256
S SaaS (Software as a Service),
311 Safari remote debugging, 284 screens
design ranges, 112 navigation, 118 sharing, 53
search interaction patterns , 55 forms, 56 lists, 56
security authentication
adapter-based, 235 - 236 mobile, 218 , 304
authorization, 304 client-side architectures, 117 gateways, 288 mobile
attack paths, 303 authentication, 304 authorization, 304 BYOD (bring your own
device), 303 endpoint
management, 303 layers, 302
sequence diagrams, 174 - 176 server folder (Worklight Server),
238 - 239 server-side caching, 298 - 302
Liberty profi le, 300 Worklight, 299
server-side functionality, accessing, 218
servers application, 1 applications, running, 209 architecture, 36 confi guring, 186 - 189 creating, 42 - 43 , 185 DMZ roles, 288 installing
Apache Derby, v10, 330 - 331
WebSphere Liberty Profi le, v8.5.5, 329
Liberty, creating, 74 - 78 starting, 78 WAS. See WAS Worklight. See Worklight WXS caching, 292
services Account, 196 - 200 back-end, invoking, 156 - 157 JAX-RS, 181 - 182 REST. See REST, services Transaction, 88 - 90 versioning, 292
headers, 294 resource semantic
changes, 293
Index 349
resource structure changes, 293
URIs, 293 - 294 virtualization, 291 web
architecture, 66 - 67 content negotiation, 96 - 97 debugging, 98 Enterprise services,
101 - 102 JAX-RS Response, 97 - 98 JSON. See JSON XML. See XML, web
services servlets
doPost() method, 38 features required, 33
Session Beans, 169 sharing applications, 220 shells (Worklight), 223 - 224 simple list interaction pattern, 56 SimpleAccountResource class
creating, 80 JUnit testing, 99 - 100
simulators, testing/debugging, 283
simultaneity (multichannel design), 53
singletons, 91 - 94 , 169 skins (Worklight), 217 Software as a Service
(SaaS), 311 source code for book examples,
installing, 319 - 321 Sources tab (Chrome DevTools),
276 - 277 spikes, testing, 285 - 286 SQL adapters, 222 starting servers, 78 Struts, 3 stub fi les, 145 Studio. See Worklight, Studio styles (mobile)
business factors, 13 - 15 HTML 5, 9 summary, 7 web applications, 8
Sync, mapping, 123
synchronization, 53 systems of engagement, 307 - 308
cloud computing, 310 - 313 mobile-fi rst development,
308 - 309 polyglot programming, 310 web APIs, managing, 309
T T-WAS (Traditional WAS), 34 table list interaction pattern, 56 targeted mobile applications,
57 - 58 teams, organizing, 19 - 20 templates
application controllers, 148 - 149
attach points, 149 Handlebars
accounts, 252 defi ning, 243 dynamic pages, rendering,
246 - 247 menu, 254 - 255
JavaScript, 117 mapping, 122 transaction detail, 162 - 163 views, implementing,
162 - 163 widgets, 138
test-driven development, 98 Account Test
AccountTest class defi nition, 192
createTransaction test case, 193 - 195
methods, 190 reading/retrieving
accounts test case, 192 test cases, 191
architecture, 190 frameworks, mapping, 122 spikes, 271 test cases, running, 209
testing. See also debugging adapters, 236 - 238 Android development kit/
tools installation, 326 - 327
applications REST service greeting,
78 - 79 sampleServer, 44 - 45 Worklight, 216
HTML consistency rules, 261 - 262 invalid code, fi nding, 262
JavaScript AMD, 263 - 264 context, 264 - 267 CSS, 267 - 268 external data, 269 global variables, 263
JAX-RS annotations banking example, 82
jsFiddle tool, 285 - 286 JUnit testing tool, 98 - 100 Liberty Profi le installation,
329 - 330 mobile web applications
app caches, disabling, 281 cross-domain Ajax
security, disabling, 283 nonwrapped
simulator, 283 resource methods within
browsers, 94 - 95 spikes, 285 - 286 unit testing. See unit testing Worklight Studio
installation, 323 Xcode, 327 - 328
Timeline tab (Chrome DevTools), 277
Traditional WAS (T-WAS), 34 Transaction DAO, 207 - 208 transaction details (banking
example) loading, 163 template, 162 - 163
Transaction service, 88 - 90 , 200 - 201
translation fi les, 164
350 Index
U UCD (User-Centered
Design), 20 development team
collaboration, 20 DoradoBank example
design process, 22 - 25 development,
introducing, 25 interaction patterns, 55
applying, 57 composite, 56 CRUD, 56 Display Form, 56 forms, 56 Linked List, 56 List to List, 56 lists, 56 Master Detail, 56 Search Form, 56 Search List, 56 Simple List, 56 Table List, 56 Update Form, 56 Validating Form, 56 Validating Form
Wizard, 56 JSON models, defi ning, 26 mobile apps, 57 - 58 multichannel, 52 - 53
channel shifting, 53 coherence, 53 complementarity, 53 Enterprise
expectations, 52 screen sharing, 53 simultaneity, 53 synchronization, 53 user expectations, 52
REST APIs, defi ning, 26 UI design. See UI design user task analysis, 22 website, 22
UI design, 49 - 50 account summary view, 60 application layers. See
applications, layers
bank example account summary
view, 60 bank use case diagram, 58 larger form factor, 62 much larger form
factor, 62 transaction details, 61 transaction summary
view, 60 design artifacts, creating, 51 design patterns, 55 hybrid application
design, 227 interaction patterns, 55
applying, 57 composite, 56 CRUD, 56 Display Form, 56 forms, 56 Linked List, 56 List to List, 56 lists, 56 Master Detail, 56 Search Form, 56 Search List, 56 Simple List, 56 Table List, 56 Update Form, 56 Validating Form, 56 Validating Form
Wizard, 56 learning about users, 50 - 51 mobile apps, 57 - 58 MVC, 55 page-oriented, 53 - 54 process, 49 - 50 responsive design, 113
Underscore, 230 unit testing
assertions, 269 banking application, 272 DOH test, 270 frameworks, 270 importance, 270 test spikes, 271
update form interaction pattern, 56
URIs, versioning, 293 - 294 User-Centered Design. See UCD user experience (UX) designs.
See UCD User Model, 173
application layers. See applications, layers
Canonical Model, compared, 173
front-end/back-end interactions sequence diagrams, 174 - 176
JSON model, defi ning Account list example, 178 Transaction list example,
179 REST APIs, defi ning,
176 - 178 util package, 125 utility classes, 185 UX (user experience) designs.
See UCD
V validating form interaction
patterns, 56 variables
dojoConfi g, 133 JavaScript global, 263
versioning, 292 headers, 294 resources
semantic changes, 293 structure changes, 293
URIs, 293 - 294 views
components, 116 implementing with templates,
162 - 163 virtualization, 291
W WAS (WebSphere Application
Server), 18 , 29 history, 29 - 31
Index 351
Liberty profi le compatibility, 34 deploying applications, 43 overview, 33 - 34 sample server.xml, 34 - 36 server architecture, 36 servers, creating, 42 - 43 testing applications, 44 - 45 Web 1.0 pattern example,
36 - 41 programming model changes,
31 - 33 web
APIs. See web APIs developer plug-in, 280 projects, creating, 68 - 70 mobile convergence. See
multichannel design services. See web services
Web 1.0 Liberty profi le example, 36 - 41
Data Transfer Object data source, retrieving,
38 - 39 defi ning, 37 get() method, 39 - 40
HTML forms page posting to Java Servlet, 37
servlet doPost() method, 37 - 38
Web 2.0, 4 web APIs
Account domain object, 202 - 203
banking example Account DAO, 205 - 207 Account Service, 196 - 200 Account Test. See
AccountTest class applications, running, 209 bank rules, creating,
208 - 209 test cases, running, 209 Transaction DAO,
207 - 208 Transaction domain
object, 203 - 205 Transaction Service,
200 - 201
choices, 210 - 211 JAX-RS, 211 managing, 309 REST principles, 18 security gateway
architecture, 289 web services (RESTful)
architecture, 66 - 67 effective
characteristics, 67 prospect URI example, 66
content negotiation, 96 - 97 debugging, 98 Enterprise services, 101 - 102 JAX-RS Response, 97 - 98 JSON
annotations, 88 - 90 Consumes annotation,
90 - 91 entity parameters,
handling, 91 singletons, 92 - 94 testing resource methods
within browsers, 94 - 95 XML-based
DAOs, 86 - 87 JAXB annotations, 83 - 86
websites Backbone, 230 Bootstrap, 148 CDI, 171 cssvalidator plug-in, 268 Curl, 94 design, 51 DGrid, 154 Dijit templates, 149 Dojo
Deferred, 144 object orientation, 146 router, 150 toolkit, 123 widget superclass, 146
Eclipse download, 317 Handlebars, 230 , 252 jQuery, 229 jQuery Mobile, 229 jsFiddle, 285 JSLint, 263
Modern Web Development with IBM WebSphere, 98 , 315
Oracle JRE download, 316 RequireJS, 229 RESTClient, 94 T-WAS, 34 UCD, 22 Worklight
security framework, 235 tutorials, 233
WebSphere, 18 Application Server. See
WAS eXtreme Scale. See WXS Liberty profi le. See Liberty
profi le widgets
attach points, 149 banking account list
application account list component,
152 - 153 HTML, 154 AccountList.js, 155 - 156 application controller
template, 148 - 149 ApplicationController
class, 146 attach points, 149 back-end services,
invoking, 156 - 157 Bijit superclass, 147 - 148 bookmarking,
implementing, 150 - 152 context object, 156 desktop mode, 160 event handling, 159 - 160 grids, building, 157 - 158 grids, implementing, 154 internationalization, 163 loading account lists, 155 localserver mode,
setting, 164 logging in, 165 mobile version, 161 real services, 165
352 Index
transaction detail template, 162 - 163
transaction details, loading 163
translation fi le, 164 creating, 136
dependencies, adding, 139 instantiating, 139 lifecycle events, 136 module basis example,
137 - 138 templates, 138
parsing, 134 superclass website, 146
wlCommonInit() method, 246 Worklight, 18 - 19 , 213
adapters, 218 advantages, 224 - 225 Application Center, 220 application structure, 223 - 224 Console, 219 deployment architecture
application sharing, 220 authentication, 218 component interactions,
220 - 221 Console, 219 device runtime, 216 - 217 enterprise resources,
exposing, 218 native device
functionality, accessing, 217
push notifi cations, 218 server-side functionality,
accessing, 218 skins, 217
development, 215 - 216 Environment Optimization
technology, 216 integrated SDKs, 216 packaging, 216 Studio, 215 testing applications, 216
disadvantages, 225 elements, 213 - 214
Application Center, 214 Console, 214
Device Runtime Components, 213
Server, 213 Studio, 213
enterprise infrastructure architecture
as channel entry point, 289
DMZ, 287 - 288 ESB integration, 290 - 292 security gateway, 289 Web API and secure
gateway, 289 WXS caching servers, 292
IBM MobileFirst, 214 - 215 Mobile Browser
Simulator, 256 Mobile Web App, 281 overview, 213 procedures, 222 security framework
website, 235 Server
architecture, 221 - 222 hybrid app artifacts,
238 - 239 mobile application
deployment, 218 - 219 shells, 223 - 224 Studio
application development, 215
architecture, 215 installing, 321 - 323 packaging
applications, 216 testing installation, 323 Worklight Server artifacts,
deploying, 239 testing/debugging
app caches, disabling, 281 cross-domain Ajax
security, disabling, 283 nonwrapped
simulator, 283 tutorials website, 233 web APIs, 211 WXS caching, 299
WXS (WebSphere eXtreme Scale)
caching, 298 - 302 Liberty profi le, 300 predictive, 301 servers, 292 Worklight, 299
overview, 298
X - Z Xcode
hybrid-based mobile apps, running, 256 - 257
installing, 327 testing, 327 - 328
XDoclet, 32 XHR (XMLHttpRequest)
object, 3 XML
HTML, compared, 261 web services
DAOs, 86 - 87 JAXB annotations, 83 - 86
Worklight adapters, 233