Related Books of Interest

Mastering XPages XPages Portable IBM’s Best-Selling Guide to XPages Command Guide Development—Now Updated and A Practical Primer for XPages Expanded for Lotus Notes/Domino 9.0.1 Application Development, Debugging, By Martin Donnelly, Mark Wallace, Tony McGuckin and Performance ISBN-10: 0-13-337337-1 By Martin Donnelly, Maire Kehoe, Tony ISBN-13: 978-0-13-337337-0 McGuckin, Dan O’Connor Three key members of the IBM XPages team have ISBN-10: 0-13-294305-0 brought together comprehensive knowledge for ISBN-13: 978-0-13-294305-5 delivering outstanding solutions. They have added A perfect portable XPages quick reference several hundred pages of new content, including for every working developer. Straight from the four new chapters. Drawing on their unsurpassed experts at IBM®, XPages Portable Command experience, they present new tips, samples, and Guide offers fast access to working code, best practices refl ecting the platform’s growing tested solutions, expert tips, and example- maturity. Writing for both XPages newcomers and driven best practices. Drawing on their experts, they cover the entire project lifecycle, unsurpassed experience as IBM XPages lead including problem debugging, performance developers and customer consultants, the optimization, and application scalability. 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.

Sign up for the monthly IBM Press newsletter at ibmpressbooks.com/newsletters Related Books of Interest

Mobile Strategy XPages Extension Library How Your Company Can Win by A Step-by-Step Guide to the Embracing Mobile Technologies Next Generation of XPages Components By Dirk Nicol By Paul Hannan, Declan Sciolla-Lynch, Jeremy ISBN-10: 0-13-309491-X Hodge, Paul Withers, Tim Tripcony ISBN-13: 978-0-13-309491-6 ISBN-10: 0-13-290181-1 Mobile Strategy gives IT leaders the ability to ISBN-13: 978-0-13-290181-9 transform their business by offering all the XPages Extension Library is the fi rst and only guidance they need to navigate this complex complete guide to Domino development with landscape, leverage its opportunities, and protect this library; it’s the best manifestation yet of their investments along the way. IBM’s Dirk Nicol the underlying XPages Extensibility Framework. clearly explains key trends and issues across Complementing the popular Mastering XPages, the entire mobile project lifecycle. He offers it gives XPages developers complete information insights critical to evaluating mobile technolo- for taking full advantage of the new components gies, supporting BYOD, and integrating mobile, from IBM. cloud, social, and big data. Throughout, you’ll fi nd Combining reference material and practical use proven best practices based on real-world case cases, the authors offer step-by-step guidance for studies from his extensive experience with IBM’s installing and confi guring the XPages Extension enterprise customers. Library and using its state-of-the-art applications infrastructure to quickly create rich web applica- tions with outstanding user experiences.

Visit ibmpressbooks.com for all product information Related Books of Interest

SOA Governance Achieving and Sustaining Business and IT Agility Brown, Laird, Gee, Mitra ISBN: 0-13-714746-5

WebSphere Application Server Administration Executing SOA Using Jython A Practical Guide for the Service- Gibson, McGrath, Bergman Oriented Architect ISBN: 0-13-358008-3 by Norbert Bieberstein, Robert G. Laird, Dr. Keith Jones, and Tilak Mitra Application Architecture ISBN: 0-13-235374-1 for WebSphere ISBN-13 978-0-13-235374-1 A Practical Approach to Buiding In Executing SOA, four experienced SOA WebSphere Applications implementers share realistic, proven, “from-the- Bernal trenches” guidance for successfully delivering on ISBN: 0-13-712926-2 even the largest and most complex SOA initiative. WebSphere Engineering This book follows up where the authors’ best- A Practical Guide for WebSphere selling Service-Oriented Architecture Compass Support Managers and Senior left off, showing how to overcome key obstacles Consultants to successful SOA implementation and identifying Ding best practices for all facets of execution— ISBN: 0-13-714225-0 technical, organizational, and human. Among the issues it addresses: introducing a services IBM WebSphere DataPower discipline that supports collaboration and SOA Appliance Handbook information process sharing; integrating services Hines, Rasmussen, Ryan, with preexisting technology assets and strategies; Kapadia, Brennan choosing the right roles for new tools; shifting ISBN: 0-13-343041-3 culture, governance, and architecture; and bringing greater agility to the entire organizational lifecycle, not just isolated projects. Dynamic SOA and BPM Best Practices for Business Process Management and SOA Agility Fiammante ISBN: 0-13-701891-6

Sign up for the monthly IBM Press newsletter at ibmpressbooks.com/newsletters This page intentionally left blank Modern Web Development with IBM® WebSphere® This page intentionally left blank Modern Web Development with IBM® WebSphere®

Kyle Brown , Roland Barcia, Karl Bishop , Matthew Perrins

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 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 corpsales@ pearsoned.com 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 ...... 1 How the Web Has Changed...... 1 The Mobile Effect ...... 7 Mobile Application Development Styles ...... 7 Building for the Mobile Experience ...... 11 Choosing a Mobile Development Approach...... 13 The Convergence of Desktop Web and Mobile: Multichannel Development ...... 15 REST and Web APIs ...... 17 IBM WebSphere and IBM Worklight ...... 18 The Process of Building Modern Web Applications...... 19 Introducing the Team ...... 19 Following a User-Centered Design and Development Process ...... 20 Introducing User-Centered Design ...... 22 Applying the Design Process: Descriptions from Our Example...... 22 Introducing Development into the Process ...... 25 Division of Labor: Defining the User Model and REST Interfaces ...... 25 Summary ...... 27 Endnotes ...... 27

Chapter 2 WAS and the Liberty Profile ...... 29 How We Got Here ...... 29 A Brief History of WAS ...... 29 What Changed in the Programming Model?...... 31 What Is Liberty? ...... 33 Some Coding Considerations and a Servlet and JDBC Example ...... 36 Deploying the Example Using the Liberty Profile ...... 41 Server Creation and Structure...... 42 Deploying an Application on a Server ...... 43 Contents xiii

Testing the Sample Application ...... 44 Running the Example Within Eclipse...... 45 Summary ...... 48 Endnotes ...... 48

Chapter 3 Design ...... 49 Agile UI Design Process ...... 49 More on User Centric Design ...... 51 Design for Multichannel ...... 52 Page-Oriented User Interfaces ...... 53 Patterns for User Interface Design Web ...... 55 View Interaction Patterns ...... 55 Targeted Mobile Apps vs. Multichannel Applications ...... 57 UI Design Example ...... 58 Summary ...... 63

Chapter 4 REST Web Services in WebSphere Liberty ...... 65 What Is REST? ...... 65 The Pieces of a RESTFul Web Service ...... 66 Introducing JAX-RS ...... 67 Basic Concepts: Resources and Applications ...... 68 A JAX-RS “Hello World” in WebSphere Liberty ...... 68 Creating the WebSphere Liberty Server ...... 74 Starting the Server and Testing the Application ...... 78 More JAX-RS Annotations ...... 80 Testing the New Example...... 82 JAXB and More Interesting XML-Based Web Services...... 82 The JAXB Annotations...... 83 A Trivial DAO (and Its Use)...... 86 JSON Serialization ...... 88 A Simple Transaction Example with JAX-RS ...... 88 Handling Entity Parameters with POST and the Consumes Annotation ...... 90 The Use of Singletons in Application Classes ...... 91 Testing POST and Other Actions with RESTClient...... 94 More on Content Negotiation ...... 95 Introducing the JAX-RS Response ...... 97 Hints on Debugging: Tips and Techniques...... 98 Simple Testing with JUnit ...... 98 RESTful SOA ...... 101 Summary ...... 102 Endnotes ...... 102 xiv Contents

Chapter 5 Application Architecture on the Glass...... 103 Why Well-Designed Applications Matter ...... 103 Defining a Client-Side Architecture ...... 104 Responsive Design ...... 109 Client-Side Architecture ...... 114 Application Controller ...... 115 Model-View-Controller ...... 116 Error Logging and Management...... 120 Data Storage and Caching...... 121 Configuration ...... 121 Introduction to the Dojo Toolkit ...... 123 Dojo ...... 124 Dijit...... 124 DojoX ...... 124 Util ...... 125 Why Use Dojo ...... 125 Asynchronous Module Definition ...... 126 Future of Dojo ...... 129 Using Dojo in Your Application ...... 130 Section: HTML Declaration ...... 132 Section: Styling...... 132 Section: Configure Dojo ...... 132 Section: Load Dojo ...... 134 Section: Initialize Application ...... 134 Section: Body Content ...... 135 Creating Your Own Widgets ...... 136 Building the Application ...... 140 Summary ...... 166

Chapter 6 Designing and Building RESTful Applications with Modern Java EE ...... 167 Modern Java EE ...... 167 EJB 3.1 and CDI ...... 168 JPA ...... 171 Application Architecture for Modern RESTful Systems...... 172 Division of Labor: Defining the User Model and REST Interfaces ...... 174 Application Layers ...... 179 Building the Application ...... 185 Loading the Example and Setting Up Liberty...... 185 Test-Driven Development ...... 190 Building REST Services ...... 195 Domain Model ...... 201 Contents xv

Building DAO and Business Logic...... 205 Running the Application...... 209 A Discussion on Choices...... 210 Summary ...... 211

Chapter 7 Introduction to IBM Worklight ...... 213 What Is IBM Worklight?...... 213 Elements of IBM Worklight ...... 213 The IBM Worklight Product Family ...... 214 Developing with IBM Worklight ...... 215 IBM Worklight Deployment Architecture ...... 216 IBM Worklight Server Architecture ...... 221 The Structure of a Worklight Application...... 223 What This Means for You ...... 224 Summary ...... 226

Chapter 8 Building a Worklight Hybrid App with Open Source Frameworks...... 227 Design for the Hybrid Application ...... 227 Overview of Frameworks ...... 228 jQuery ...... 229 jQuery Mobile...... 229 Require.js ...... 229 Backbone and Underscore ...... 230 Handlebars ...... 230 Building a Hybrid App with Worklight...... 230 Setting Up the Project ...... 230 Worklight Adapter Code...... 233 Worklight Hybrid App Folder Structure...... 240 Examining the Application ...... 242 Running the Example ...... 255 Summary ...... 260

Chapter 9 Testing and Debugging ...... 261 HTML ...... 261 JavaScript ...... 262 Global Variables ...... 263 Asynchronous Module Definition (AMD) ...... 263 Context ...... 264 CSS ...... 267 Data...... 269 Unit Testing...... 269 The Browser as a Test Platform...... 272 xvi Contents

Exploring Chrome’s DevTools...... 273 Essential Browser Plug-ins ...... 279 IBM Worklight Specific Concerns ...... 281 Disabling AppCache for Mobile Web Apps...... 281 Disabling Security for Cross-Domain Ajax in Mobile Apps ...... 283 Remote Debugging ...... 284 Safari Remote Debugging...... 284 Chrome Remote Debugging ...... 285 Online Code Snippit Runners ...... 285 Summary ...... 286

Chapter 10 Advanced Topics ...... 287 Understanding Where Your Application Fits ...... 287 Achieving Reliability Through Clustering ...... 292 Versioning ...... 292 Versioning in the URI...... 293 Versioning in the Header ...... 294 Mechanisms for Improving Performance ...... 294 Pagination ...... 295 Caching Overview ...... 296 Response Caching...... 297 Server-Side Caching with WXS ...... 298 Security Issues for Modern Web Applications ...... 302 Summary ...... 304 Endnotes ...... 305

Chapter 11 Key Takeaways of Modern Web Development ...... 307 The Engaging Enterprise ...... 307 Mobile-First Development ...... 308 Web APIs ...... 309 Polyglot Programming ...... 310 Cloud Computing ...... 310 Summary ...... 313 Endnote ...... 313

Appendix A Installation Instructions ...... 315 Development Machine Installation ...... 315 Installing Java Runtime Environment, v1.7 ...... 316 Installing Eclipse Juno IDE, v4.3 ...... 317 Installing IBM WebSphere Liberty Profile Developer Tools, v8.5.5 ...... 318 Installing the Source Code for the Book Examples ...... 319 Contents xvii

Optional Development Tooling for Mobile Web Apps...... 321 IBM Worklight Studio v6.0 ...... 321 Android Development Tools and Eclipse Plug-in ...... 324 OSX XCode IDE ...... 327 Server Installation ...... 328 IBM WebSphere Liberty Profile, v8.5.5...... 329 , v10 ...... 330 Downloading and Installing Example Source Code ...... 333 Summary ...... 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 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 C HAPTER 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.

65 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 Noun (URI) Verb (Action) Adjectives (Formats) Description) List all the prospects. .../prospects GET JSON, XML Get a specific prospect. .../prospects/ GET JSON, XML {id} Add a contact. .../prospects POST JSON, XML Delete a specific .../prospects/ DELETE JSON, XML contact. {id}

• 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 foll