Modern Web Development with IBM® WebSphere - Pearsoncmg

10 downloads 41 Views 1MB Size Report
Chapter 11 Key Takeaways of Modern Web Development . ...... Chapter 10 , “Advanced Topics,” covers other topics rele
Related Books of Interest

Mastering XPages IBM’s Best-Selling Guide to XPages Development—Now Updated and Expanded for Lotus Notes/Domino 9.0.1

XPages Portable Command Guide

By Martin Donnelly, Mark Wallace, Tony McGuckin

A Practical Primer for XPages Application Development, Debugging, and Performance

ISBN-10: 0-13-337337-1 ISBN-13: 978-0-13-337337-0

By Martin Donnelly, Maire Kehoe, Tony McGuckin, Dan O’Connor

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

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 exampledriven 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 specific XPages development problems. Using their easy-to-adapt code examples, you can develop XPages solutions with outstanding performance, scalability, flexibility, efficiency, 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 Embracing Mobile Technologies

A Step-by-Step Guide to the Next Generation of XPages Components

By Dirk Nicol

By Paul Hannan, Declan Sciolla-Lynch, Jeremy Hodge, Paul Withers, Tim Tripcony

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 technologies, supporting BYOD, and integrating mobile, cloud, social, and big ) int accountId){ if (accountId==123) return "123" + "Savings" + "110.00"; else return "No account having that id"; } }

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 identifies 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 documents 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: @XmlElement public int foo;

Your XML output then is of the form 123. 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: 123.

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 project, 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; @XmlRootElement public 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"); } @XmlElement public 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; } @XmlElement public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } @XmlElement public 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 properties 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 segment of XML generated would be of this form somevalue

instead of the default: somevalue

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 attention 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 developments 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 ) return dao.get(id); } }

int 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 nothing 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 several 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 earlier 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 POSTing 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

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; }

89

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 previous 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) @POST public 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). Likewise, 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 interesting 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 @PathParam 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

) ➥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 corresponds 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 errorhandling 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 redirect (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(); else return 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 examples. 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 executing (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 Programming 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 import import import import import

java.io.BufferedReader; java.io.IOException; java.io.InputStreamReader; java.net.MalformedURLException; java.net.URL; java.net.URLConnection;

import org.junit.Test; public class SimpleAccountResourceTest { @Test public void testGetAccounts() { String address = "http://localhost:9080/ ➥RestServicesSamples/banking/simple/accounts"; StringBuffer result = new StringBuffer(); String expectedResult = "123"+ "234"; 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 GETs 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 AccountResourceTest 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 examine 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 technologies 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 Enterprise developers could soon suffer the same fate. You have to be smart about what you’re building 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 integration. 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 exploitation, 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 abstracting 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 messaging. 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 Edition). IBM Press 2004.

This page intentionally left blank

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 file, 164 accountLoaded() method, 249 AccountResource class, 87 Accounts test spike, 272 AccountTest class Admin test case, 192 createTransaction test case, 193-195 definition, 192 methods, 190 test cases, 191, 209 adapters (Worklight), 218, 221-222 files, 233 logic, implementing, 234-235 security configurations, 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

335

Ajax (Asynchronous JavaScript and XML), 3-4 AMD (Asynchronous Module Definition), 126 define() 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

JAX-RS, 81 Path, 81 PathParam, 82 Produces, 81 Apache Cordova, 11, 217 Derby database server configuration, 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 profile, 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

Index

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 configuration 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 Definition. 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 files, 233 logic, implementing, 234-235 security configuration, 235-236 testing, 236-238 XML, 233 application controller, 146, 148-149 application layers, 180 DAO, 183 database schema, 182

Index

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, defining, 26 menu template, 254-255 mobile web menu, 150 REST APIs, defining, 176-178

337

REST services Account Service, 196-200 JAXRS providers, configuring, 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 Profiles 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

definition, 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 configuration file, 144 index.html file, 141-143 stub files, 145 building principles, 114 configuration layer, 121 data storage and caching, 121 defining, 104-108 design, 103 error handling, 120-121 frameworks, mapping, 122-123

Index

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 files, 333 coherence (multichannel design), 53 combination multichannel development, 16 common folder (hybrid-based mobile app), 240 compatibility (Liberty profile), 34 complementarity (multichannel design), 53 composite, 56 configuring 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 defining, 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 flows (Modern Web Applications), 5 sources, retrieving, 38-39 storage, 121 Data Tier application layers bank example, 180 DAO, 183

Index

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 defining, 178-179 generating from back-end data sources, 172 REST APIs, defining, 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 Profiles 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

339

remote, 284 Chrome, 285 Safari, 284 tips and techniques, 98 define() method AccountController.js, 249 AMD, 127-128 demilitarized zone. See DMZ deploying applications Eclipse, 45-48 Liberty profile, 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 Profile 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

display form interaction pattern, 56 DMZ (demilitarized zone) overview, 287 secure gateway, 288 server roles, 288 DOH (Dojo Objective Harness), 125, 270 Dojo AMD define() 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, loading163 translation file, 164 benefits, 125

Index

client-side architectures, building, 114 Deferred Objects, 144 dojo router website, 150 future, 129 HTML example applications, initializing, 134-135 body content, 135-136 configuring 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 dojoConfig 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 files, 233

DoradoBank.html file, 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 specification 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-first development, 308-309 polyglot programming, 310 web APIs, managing, 309 enterprise infrastructure architecture DMZ overview, 287 security gateway, 288 server roles, 288

Index

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

341

forms defined, 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, finding, 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 file, 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 defining 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

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 flows, 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 configuring Dojo, 132 explanation, 130 HTML declaration, 132 loading dojo, 134 styling, 132 HTML 5, 9 hybrid-based mobile apps main file, 242-243 invalid, finding, 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 file, 242-243

Index

menu template, 254-255 view, 252-254 projects, importing, 230-231 require.js file, 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 Profile Developer Tools, v8.5.5, 318-319 WebSphere Liberty Profile, 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

Path, 81 PathParam, 82 Produces, 81 JAX-RS application layers, 181-182 defined, 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, finding, 172 lifecycle, 171-172 overview, 171 servers configuring, 186-189 creating, 168 test-driven development. See test-driven development

343

typical application architecture, 179 v6 Web profile 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 defined, 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, configuring, 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, finding, 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 defining 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

L larger form factor, 62 layouts CSS media queries example, 109-110 HTML, 111-112 ranges, 112 shells, 117 lexical analyzer (HTML), 262 Liberty profile 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

Index

servers applications, running, 209 architecture, 36 configuring, 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 prefixes, 268 define() method in AMD, 128 getAccount object, 156 GreetingResource class, 72 HTML for media query, 111 JAXRS MWBApplication class, 196 Liberty profile 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 config file, 245 responsive design ranges, 112 server configuration, 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

Transaction Service, 200 translation file, 164 translation substitution, 164 Web 1.0 Liberty profile example data source, retrieving, 38 get() method, 39 index.html file, 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

345

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 define() 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 notifications, 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 files, 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

launching from Macs, 256-257 login page, 251-252 LoginController, 249-250 main HTML file, 242-243 menu template, 254-255 menu view, 252-254 Mobile Browser Simulator, running, 256 preview mode, 255 projects, importing, 230-231 require.js file, 244-245 router logic, 248 security configuration, 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

Index

fueling Modern Web Applications, 6 runtime, 216-217 Worklight, 18-19 Mobile Enterprise Application Platform (MEAP) vendors, 11 mobile-first 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 flows, 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 configuration 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

jQuery Mobile hybrid-based mobile app default HTML content, 243 login pages, 251 overview, 229 RequireJS hybrid-based mobile app example file, 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

347

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 Profiles 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 notifications, 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 file, 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

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 defined, 17 endpoints, testing. See test-driven development JAX-RS defined, 67 goals, 67-68 Hello World application, 68-74 resources/applications, 68 misconceptions, 17 philosophies, 65 servers configuring, 186-189 creating, 168 services advantages over Worklight, 223-224 disadvantages over Worklight, 225-226 JAX-RS Account Service, 196-200 provider, configuring, 196 Transaction Service, 200-201 pagination, 295-296 Web application, 195

Index

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 defining, 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 profile, 300 Worklight, 299 server-side functionality, accessing, 218 servers application, 1 applications, running, 209 architecture, 36 configuring, 186-189 creating, 42-43, 185 DMZ roles, 288 installing Apache Derby, v10, 330-331 WebSphere Liberty Profile, 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

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 files, 145 Studio. See Worklight, Studio styles (mobile) business factors, 13-15 HTML 5, 9 summary, 7 web applications, 8 Sync, mapping, 123

349

synchronization, 53 systems of engagement, 307-308 cloud computing, 310-313 mobile-first 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 defining, 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 definition, 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, finding, 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 Profile 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 files, 164

350

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, defining, 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, defining, 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

Index

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, defining Account list example, 178 Transaction list example, 179 REST APIs, defining, 176-178 util package, 125 utility classes, 185 UX (user experience) designs. See UCD

V validating form interaction patterns, 56 variables dojoConfig, 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

Liberty profile 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 profile example, 36-41 Data Transfer Object data source, retrieving, 38-39 defining, 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

351

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 profile. See Liberty profile 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

transaction detail template, 162-163 transaction details, loading163 translation file, 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 notifications, 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

Index

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 profile, 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

Suggest Documents