Showing posts with label JAX-RS. Show all posts
Showing posts with label JAX-RS. Show all posts

Wednesday, November 25, 2015

Book Review: Digital Java EE 7 Web Application Development

Packt Publishing recently (September 2015) published Peter Pilgrim's Digital Java EE 7 Web Application Development with the subtitle "Develop Java enterprise applications to meet the emerging digital standards using Java EE 7." Digital Java EE 7 Web Application Development contains 9 chapters and 4 appendices spanning over 400 pages. The book's subtitle is "Develop Java enterprise applications to meet the emerging digital standards using Java EE 7."

Preface

The Preface of Digital Java EE 7 Web Application Development states that the book is "a continuation of the first book Java EE 7 Developer Handbook" with Digital Java EE 7 Web Application Development focusing on "the Java presentation tier." The Preface adds that "the book was written for the developers who want to become superior and adept at building a web application on JVM with the standard Java EE 7 platform" and with specific focus on JavaServer Faces with some coverage of JavaScript and AngularJS.

The Preface contains short summaries (2-3 sentences each) of each of the book's chapters and appendices. It also lists the software necessary to run the examples provided in the book: Java 8, GlassFish 4.1, Gradle 2.6, Chrome DevTools, Firefox Developer Tools, "Chris Pederick's Web Developer and User Agent Switcher extensions", and "a decent Java Editor or IDE for coding."

In describing "who this book is for," the Preface of Digital Java EE 7 Web Application Development states, "this book is pitched at intermediate Java developers" with "a good command over the programming language" that includes Java SE knowledge of "classes, inheritance, and Java Collections" and Java EE knowledge of "Java persistence, Java servlets, and deployment of the WAR files to an application server."

Chapter 1: Digital Java EE 7

The initial chapter of Digital Java EE 7 Web Application Development begins with a high-level introduction to working in the digital domain and looks at how Java fits inside the digital domain. There is specific focus on recent changes in Java 8 including removal of PermGen, introduction of the G1 garbage collector and introductory code listing and explanatory text related to lambda expressions.

Chapter 1 also looks at JavaScript with specific focus on JavaScript libraries such as jQuery, AngularJS, and GruntJS. The chapter provides a brief overview of Java EE 7 features that are applicable in the digital design world and introduces application servers that implement Java EE 7 including GlassFish 4.1, Payara Server, and WildFly. There is also a brief introduction (with code listing) to JavaServer Faces.

Chapter 2: JavaServer Faces Lifecycle

JavaServer Faces (JSF) is the exclusive topic of Chapter 2 of Digital Java EE 7 Web Application Development. The chapter introduces JavaServer Faces with a historical perspective and references terminology such as responsive design, mobile web design, Digital by Default, and Default to Open. A brief history of JSF is outlined and some key new features of JSF 2.2 are listed. Arguments for choosing JSF over other Java-based web frameworks are also made and mostly center around JSF being a standard.

The second chapter introduces Model-View-Controller (MVC) and describes how JSF implements MVC. The chapter provides a high-level overview of Facelets and looks at the JSF request processing lifecycle. The chapter provides multiple JSF code listings and demonstrates JSF features such as JSF annotations, expression language, web descriptor, and JSF XML namespaces. After providing another JSF code example, Chapter 2 returns to more in-depth coverage of expression language.

Chapter 3: Building JSF Forms

Like the second chapter, Digital Java EE 7 Web Application Development's third chapter is JSF-centric, but does include some HTML5/CSS/Bootstrap code in the example that is built throughout the chapter. This chapter begins with an example of implementing a CRUD-oriented application using a JSF Facelet with Bootstrap via passthrough. Several JSF tags and tag libraries are introduced as they are applied in the example being built up in Chapter 3. The example constructed in Chapter 3 also demonstrates use of Java Persistence API (JPA) as functionality to allow contacts to be created, read, updated, and deleted is added.

One of the things that can be confusing to someone new to JavaServer Faces is the difference between the older JSF managed beans and the newer CDI-based beans. The third chapter concludes with a discussion that addresses this.

Chapter 4: JSF Validation and AJAX

The fourth chapter of Digital Java EE 7 Web Application Development begins with an explanation of why validation is important in web applications and then introduces and contrasts server-side validation with client-side validation. The chapter then details using the h:message and h:messages JSF tags to display errors.

Chapter 4's coverage of validation in JSF introduces "two main ways of achieving validation": Java EE 7's Bean Validation 1.1 and "traditional" JSF validation. The chapter provides a code example, a table of relevant annotations, and explanatory text in its introduction of bean validation. Explanatory text and code listings are also provided in the introduction to JSF validation.

This fourth chapter also introduces applying the attributes requiredMessage, validatorMessage, and conversionMessage for custom messages. The chapter looks at overriding validation messages globally via properties files and demonstrates adding a custom validation method to a rendering tag.

The section of Chapter 4 on custom validators demonstrates creating a custom validator by writing a class that implements javax.faces.validator.Validator and annotating it with @javax.faces.validator.FacesValidator. The "Converters" section of Chapter 4 describes converters as "JSF classes that convert between strings and objects" and then provides detailed discussion and code examples implementing a custom converter.

Chapter 4 also looks at "validating immediately with AJAX." This section introduces Ajax and JSF's "built-in support for AJAX requests and responses." It introduces <f:ajax>, provides multiple code listings demonstrating use of it, provides a table of its attributes, and looks at how it relates to the JSF lifecycle.

One of Chapter 4's major sections is "Handling views" and this concluding section of the chapter covers invoking and passing parameters to controller methods, invoking an action event listener, redirecting pages, and debugging JSF with <ui:debug>.

Chapter 5: Conversations and Journeys

Chapter 5 of Digital Java EE 7 Web Application Development focuses on "JSF conversation scope." The chapter begins by looking at how JSF integrates Context and Dependency Injection (CDI) context and dependency injection. The chapter defines "conversational scope" as "defined by a lifecycle that spans many HTTP requests to the server." The @javax.enterprise.context.ConversationScoped annotation and the CDI-injected javax.enterprise.context.Conversation interface are introduced and demonstrated early in this chapter before coverage of the lifecycle of a conversation scoped bean.

There are several screen snapshots and code listings in this chapter. These payday loan application examples include application of Bootstrap CSS and JSF 2.2's support for HTML5-friendly pages with new namespace http://xmlns.jcp.org/jsf. They illustrate applying Ajax, jQuery, and the HTML5 Range element.

The final major section of the fifth chapter covers JSF custom components. An example of a custom component implemented with an XHTML-defined Facelet view backed by a backing bean is provided. Another portion of this section introduces the JSF 2.2 ability to "generate the custom tag without specifying any XML declaration."

Chapter 6: JSF Flows and Finesse

Digital Java EE 7 Web Application Development's sixth chapter emphasizes what I think may be the most interesting feature of JSF 2.2: Faces Flows. The chapter begins by explaining the use cases and sample applications that inspired and can make most use of Faces Flow before delineating some key characteristics of Faces Flow. Several early sections use code listings to demonstrate use of annotations (such as @javax.faces.flow.FlowScoped) and other Faces Flow concepts in simple flows.

Chapter 6 demonstrates use of the <error-page> element to declare "an association between an exception type and a page view" that allows for nicer presentation of the "one of the most notorious exceptions" encountered in JSF-based applications (javax.faces.application.ViewExpiredException).

The sixth chapter also looks at complex flows. It demonstrates and describes flows that switch on different cases (conditional) and nest flows. In addition to the inline explanatory examples, the chapter includes a "a real-world example" with significant discussion on security-related aspects.

Faces Flows is not the only JSF 2.2 feature covered in Chapter 6. The chapter also introduces Resource Library Contracts. Several nuances are demonstrated with code listings and there is a section on using Resource Library Contracts in conjunction with Faces Flows. The chapter concludes with a bullet list of tips for using Faces Flows.

Chapter 7: Progressive JavaScript Frameworks and Modules

Chapter 7 of Digital Java EE 7 Web Application Development begins with the observation that "in the contemporary way of building a website, there is no escape from the language of JavaScript because it is a de facto standard of modern web browsers." Although earlier chapters touched on JavaScript and related technologies, this is the first chapter that focuses on something other than JSF. The focus of the chapter is JavaScript and JavaScript libraries and frameworks.

The seventh chapter begins with an introduction to the basics of JavaScript. After covering some of the basics and gotchas of JavaScript and introducing some JavaScript features in comparison to similar Java features, the chapter moves onto introducing jQuery (and sizzle) in more detail. Along with demonstrating use of jQuery for DOM manipulation and simple animation, the chapter also demonstrates including jQuery code in a JSF application.

RequireJS, Underscore, and Grunt are also introduced in Chapter 7. There are several pages devoted to each that introduce some key features and uses of each framework.

Chapter 8: AngularJS and Java RESTful Services

The eighth chapter of Digital Java EE 7 Web Application Development shifts from JSF to an "alternate design mode." I like the author's articulation (probably because it coincides with my own observations) of where JSF fits best and where this alternate design mode fits best. Pilgrim writes:

The design philosophy behind building an application on a single page such that it resembles a desktop application is in marked contrast to the JavaServer Faces' original design of navigation links between pages. ... JSF lends itself to applications that are extremely stateful in nature and design, where the customer journey is based on page-to-page navigation.

After successfully explaining why JSF in not a good fit for the single-page design model, the author lists some advantages and disadvantages of the single-page model. An example of a single-page application for this chapter is introduced and is related to managing case worker information. This example is defined in more detail after the AngularJS coverage.

Chapter 8 introduces one of the trendiest and most popular web development frameworks in AngularJS. The introduction is fairly thorough for only being part of a single chapter. Significantly more details of AngularJS are illustrated with a return to the caseworker application implemented with AngularJS. The casework sample application demonstrates use of Java EE features such as JPA, REST-based web services with JAX-RS, and WebSocket in addition to AngularJS.

Chapter 9: Java EE MVC Framework

The final chapter of Digital Java EE 7 Web Application Development is a future-looking chapter that looks past Java EE 7 and introduces the JSR 371: Model-View-Controller (MVC 1.0) Specification. The chapter explains why this specification is being planned for Java EE 8 and also introduces a reference implementation of it (Ozark). Because Java EE 8 (JSR 366) is still forthcoming, Pilgrim warns the reader of this chapter, "the information here is subject to change because MVC is evolving."

This ninth chapter introduces the new package called javax.mvc and the @javax.mvc.Controller annotation. The chapter then explains and illustrates applying MVC 1.0 with JAX-RS annotations. The examples and explanations also cover using JSF for the view portion and using the javax.mvc.Models interface for the model portion of an MVC 1.0-based application.

Chapter 9 introduces JavaScript-based Handlebars.js (and Mustache) and then segues from there into an introduction of the Java port of this. Several pages are devoted to building up the example of the application using Ozark and Handlebars for Java.

The final chapter concludes with a look at a couple ways in which the Java MVC 1.0 specification might still change and with a discussion of design considerations when using Java MVC.

The Appendices

Appendix A ("JSF with HTML5, Resources, and Faces Flows") is a "quick reference" on the JSF library. The first part of this appendix is a standard library reference with emphasis on Java EE 6 (JSF 2.0) and Java EE 7 (JSF 2.2) versions of JavaServer Faces. The second part covers Faces Flows with a thorough reference.

Appendix B ("From Request to Response") covers common topics associated with a web application's architecture. These topics include HTTP (protocol itself, advancements, request methods and response codes), standard Java EE web architecture (servlet + CDI + EJB), extended Java EE web architectures (NoSQL, Model-View-ViewModel, Java Temporary Caching, embedded server/containerless system, microservices), and brief discussion addressing the question, "Is it important to be known as a full stack developer?"

Appendix C ("Agile Performance – Working inside Digital Teams") consists on ten pages that look at structure of agile digital development teams and roles on those teams.

Appendix D ("Curated References") is over six pages of "references around the digital software development" that are categorized "into concepts and themes" of "Service delivery", "Agile and leadership", "Architecture", "User interface", and "Java EE and JVM technology." Because these references include URLs, it is easy to click on these in the electronic versions to be taken directly to the referenced resource.

What is Digital Java EE 7 Web Application Development and Who Is It Best Suited For?

One of the most valuable insights I believe I can provide to someone trying to decide whether to purchase or borrow this book is to articulate what this book covers and who it is best suited for. I attempt that here.

  • Digital Java EE 7 Web Application Development provides significant coverage of JavaServer Faces (JSF).
    • Chapters 2 through 6 are almost exclusively JSF-focused and JSF has significant presence in Chapter 1 and Chapter 9.
    • It's not just JSF, however, and covers using HTML5 and related popular frameworks and libraries with JSF.
    • Chapter 8 (single-page applications with AngularJS) is not JSF at all.
  • Digital Java EE 7 Web Application Development focuses on newer JSF features.
    • As its title implies, the focus of this book is on Java EE 7 and JSF 2.2 with some mention of Java EE 6 (JSF 2.0).
    • This is probably NOT the book you want to get to learn JSF for the first time, but rather is more suited for someone with minimal JSF experience through JSF 2.0 who wants to learn what's available in JSF 2.2 and Java EE 7.
  • Digital Java EE 7 Web Application Development provides broad coverage of developing Java EE 7 web application user interfaces.
  • Digital Java EE 7 Web Application Development is most likely to appeal to these types of developers:
    • Intermediate-level (or advanced) Java developers (as described in the book's preface) who have only basic familiarity with JSF and want to learn more about newer (Java EE 7/JSF 2.2) JSF features.
    • Java developers with only limited awareness of modern web client technologies and frameworks who want to learn how to use JSF with HTML5 and related technologies.
    • Java developers who want a broad view of the currently favored and standard Java EE 7 technologies for web development and want an introductory chapter on Java EE MVC coming with Java EE 8.
  • Digital Java EE 7 Web Application Development may not meet expectations of these types of developers:
    • Developers looking for an introduction to JavaServer Faces; this book is better suited to developers with at least minimal JSF experience as it's not an introductory book and it mostly focused on newer JSF features.
    • Developers looking for a reference on HTML5, JavaScript, CSS or related frameworks and libraries such as AngularJS, jQuery, and Bootstrap; although this book does introduce using these technologies with JSF, the coverage of these particular technologies is mostly introductory.
    • Developers looking for a book on developing Java-based web applications with JAX-WS (SOAP/WSDL-based web services), Java servlets, or one of the many available non-standard Java/JVM web frameworks; this book does not cover these older and/or non-standard technologies and instead focuses it coverage on JSF 2.2 and JAX-RS.

Other General Observations

The following are some general observations and opinions of mine formed while reading the PDF version of Digital Java EE 7 Web Application Development provided to me by Packt Publishing.

  • Digital Java EE 7 Web Application Development includes numerous code examples
    • Code listings tend to build upon same simple example applications that highlight benefits and advantages of the approach being demonstrated.
    • Code listings are black font on white background with no color syntax highlighting and no line numbers even in the electronic (PDF) version of the book that I read.
    • I liked that there are extensive code listings and understand that printed books would not be able to have color syntax highlighting, but having color syntax in the code examples (especially the larger ones) or otherwise emphasized code would have helped with code readability.
    • I recommend acquiring code listings in Pilgrim's GitHub repository so that an IDE or text editor can be used to view the code.
  • There are several color screen snapshots in the PDF version of Digital Java EE 7 Web Application Development to help illustrate the web pages rendered by JSF and related web technologies. There are also color graphics for illustrating concepts in the electronic version.
  • Although Digital Java EE 7 Web Application Development is a Java EE book, it does a nice job of inserting some Java SE 7 JDK libraries in the examples. In particular, the Java 8 date/time library is used multiple times and Chapter 1 introduces lambda expressions.
  • For the most part, Digital Java EE 7 Web Application Development reads fairly well. However, as with several other Packt Publishing titles I have reviewed, it could have used more editing. There are several typos in Digital Java EE 7 Web Application Development, but these rarely prevent the content from being understood. To help convey the type of typos for you to judge how they might impact your ability to understand what is being communicated, I include some examples here:
    • "SERVERITY_WARNING"
    • "these tags render the content from the javax.faces.HtmlMessages and javax.faces.HtmlMessages components respectively"
    • "The JavaScript support functions as a first-class citizen and rules on a and supports the declaration of functions..."
    • "JSF 1.0 was created in the early noughties,..."
    • "...new package structure reserved for MVC under javax.mvc. The @javac.mvc.Controller annotation..."
  • Each of the chapters has a set of questions and exercises at the end of the chapter. I didn't run through any of these and cannot comment on the benefits of them. I also am not aware of any answers or solutions being provided for any of the exercises or questions.
  • Pilgrim references his other Packt title, Java EE 7 Developer Handbook, several times in this book for readers who need additional background Java EE details, particularly in areas outside of the user interface.
    • Reviews for the earlier book probably provide good indicators of what one can expect from Digital Java EE 7 Web Application Development. Indeed, I noticed that several of the positive and negative comments on Amazon.com apply to the book I'm reviewing as well. As of this writing, there are 10 reviews of Java EE 7 Developer Handbook on Amazon.com with an average 3.8 (out of 5) rating.
  • Find the author's own description of his book in the blog post My Digital Java EE 7 book is now published.

Conclusion

Digital Java EE 7 Web Application Development provides a survey of the most popular Java EE 7 approaches for developing web applications. JavaServer Faces receives the lion's share of the discussion with focus particularly on Java EE 7's version of JSF (2.2). Digital Java EE 7 Web Application Development introduces JavaScript and AngularJS and discusses using HTML5 technologies, libraries, and frameworks with JSF. There is also forward-looking chapter on Java EE 8's forthcoming Java EE MVC. Digital Java EE 7 Web Application Development is a book largely on modern JSF, but it's not accurate to say it's only a JSF book and it's probably not the best introductory book for those who have never used JSF. Instead, this book is best suited for Java developers with some awareness of JSF, but who want to learn more about JSF 2.2 and integrating JSF with other non-Java web languages, libraries, and frameworks.

Monday, November 24, 2014

Book Review: RESTful Java Patterns and Best Practices

Bhakti Mehta's RESTful Java Patterns and Best Practices was recently published by Packt Publishing. Consisting of six chapters and an appendix spanning approximately 125 substantive pages, its subtitle is, "Learn best practices to efficiently build scalable, reliable, and maintainable high performance RESTful services."

Preface

The Preface of RESTful Java Patterns and Best Practices begins with a description of why REST is important today. It includes several short summaries of each of the book's chapters. The Preface explains that Maven 3 and GlassFish 4 are required to build and run the book's examples and states that the book is designed as "a perfect reading source for application developers to get familiar with REST."

Chapter 1: REST – Where It Begins

RESTful Java Patterns and Best Practices's initial chapter provides a single paragraph on SOAP/WSDL-based web services before turning attention to REST-based web services. The basic characteristics of and increased "-ilities" provided by REST are described. The Richardson Maturity Model is also examined in some detail. I'm not sure that the Richardson Maturity Model clears things up or muddies them by encouraging interchangeable use of the terms HTTP and REST.

The first chapter includes brief descriptions of the characteristics of safe methods and of idempotent methods and describes which HTTP methods fit each category. The chapter then lists several "design principles for building RESTful services" before describing each in greater detail. This is section provides a brief and highly readable introduction to the basics of REST.

Chapter 1's introduction of the Java API for RESTful Web Services (JAX-RS) includes simple examples of turning POJOs into REST resources using JAX-RS annotations such as @GET, @POST, @Path, @Produces, @Consumes, and @ValidateOnExecution.

Chapter 1 provides a nice introduction to the Client API that is new to JAX-RS 2.0. It also briefly discusses some other approaches one can use to communicate and work with REST-based services: curl, Postman on Chrome, Advanced REST Client for Google Chrome, and JSONLint. Both curl and Postman get extra attention including a color screen snapshot of Postman in the electronic edition I reviewed.

The first chapter concludes with a bullet-format list of "best practices when designing resources," a list of related online resources, and a Summary. Overall, this first chapter is a nice high-level introduction to REST and to Java's approach to REST via JAX-RS. The code examples are simple and short and easy to understand. Just enough detail is provided to get a feel for REST and JAX-RS.

Chapter 2: Resource Design

Chapter 2 of RESTful Java Patterns and Best Practices delves more deeply into HTTP and REST concepts such as content negotiation (including contrasting use of HTTP headers versus URL patterns), alternative resource representation (MessageBodyReader and MessageBodyWriter, StreamingOutput, and ChunkedOutput), Jersey's JSON support (ObjectMapper, @XMLRootElement, JsonArray, and JsonObject), API versioning (comparing URI, request query parameter, and Accept header approaches), HTTP response codes, and the JAX-RS classes Response and ResponseBuilder.

The second chapter provides greater details regarding application of JAX-RS to REST-based application implementation. The examples are relatively short and clear and illustrate well the points being made.

Chapter 3: Security and Traceability

The third chapter opens up with two paragraphs explaining why security and traceability are important in today's REST-based applications. The specific security and traceability topics discussed in this chapter are logging in REST-based applications, exception handling in REST-based applications, validation patterns, and federated identity.

The section on logging from a REST-based application demonstrates writing of a servlet filter (annotated with @WebFilter and implementing Filter) that can log certain metadata about each request as each request occurs. This section also outlines some logging best practices that I'd say are general logging best practices rather than REST-specific logging best practices.

Chapter 3's section on validating services states, "JAX-RS supports the Bean Validation to verify JAX-RS resource classes." The text and accompanying code samples demonstrate use of bean validation with standard annotations such as @ValidateOnExecution, @Valid, and @NotNull and a custom annotation @VerifyValue. This section also demonstrates with code and explanation how to create a custom exception mapper (implementation of ExceptionMapper that "catch[es] thrown application exceptions and write[s] specific HTTP responses.").

Part of Chapter 3 focuses on authentication and authorization. This section introduces Security Assertion Markup Language (SAML) and SAML Web Browser Profile for authentication and OAuth (open authorization) for authorization. This section has some nice graphics (with a bit of color in the PDF version) depicting how authentication with SAML and authorization with OAuth work at a high level.

Chapter 3's coverage or authorization includes more details on characteristics of OAuth 2.0. Access and refresh tokens are covered as is the level of support for OAuth 2.0 provided by Jersey (the Jersey implementation supports client side only and Authorization Code Grant Flow).

The third chapter includes a section titled "Best practices for OAuth [2.0] in the REST API." Although these seem to be generally applicable to use of OAuth whether REST is involved or not, I liked the table presenting different situations and when SAML or OAuth is preferable. There is a very brief section in Chapter 3 that introduces OpenID Connect, which the author describes as "a simple REST- and JSON-based interoperable protocol built on top of OAuth 2.0."

Before concluding with the summary and recommended reading sections typical of chapters in RESTful Java Patterns and Best Practices, the third chapter briefly outlines "REST architectural components" to be covered in more detail later. One "recommended reading" that I found particularly interesting is OAuth 2.0 and the Road to Hell.

Chapter 4: Designing for Performance

RESTful Java Patterns and Best Practices's fourth chapter advertises itself as covering "advanced design principles related to performance that every developer must know when building RESTful services." Discussion of strong and weak HTTP caching headers is preceded by an overview of general caching principles. A code listing and accompanying explanation demonstrate how to specify HTTP caching headers in JAX-RS responses. Similarly, this section also looks at the ETag response-header field and how to apply it to a JAX-RS response. The section of Chapter 4 on caching concludes with a brief description of RESTEasy's extension to JAX-RS caching.

"Asynchronous and long-running jobs in REST" is the second major topic of Chapter 4. This section uses code listings, textual explanations, and sequence diagrams to demonstrate use of JAX-RS 2.0 support for asynchronous processing with constructs such as AsyncResponse, @Suspended, CompletionCallback, ConnectionCallback, InvocationCallback, and Java SE Future interface.

The "Asynchronous resources best practices" section of Chapter 4 briefly describes "best practices when working with asynchronous RESTful resources." These tend to be best practices for working with HTTP asynchronously whether in REST or not.

There is a section in Chapter 4 that discusses dealing with partial updates in a REST application using PATCH, PUT, or POST. This section demonstrates creation of an annotation called @PATCH to annotate JAX-RS methods to be used for patch functionality.

The final section of Chapter 4 of RESTful Java Patterns and Best Practices before its summary and recommended reading section is on JSON Patch. This section provides a brief overview of JSON Patch and provides code listing and explanations of how to use JSON Patch.

Chapter 5: Advanced Design Principles

The promise of RESTful Java Patterns and Best Practices's fifth chapter is to cover "advanced design principles that every developer must know when designing RESTful services." The covered topics are rate-limiting patterns, response pagination, internationalization and localization, REST pluggability and extensibility, and some miscellaneous topics. The section on rate-limiting pagination is relatively lengthy and includes code snippets and discussion as well as an outline of some best practices for reducing and avoiding rate-limiting pagination.

"Response pagination" is covered in the fifth chapter, which looks at three types of response pagination: Offset-based pagination, Time-based pagination, and Cursor-based pagination. The chapter then provides an example of implementing offset-based pagination with JAX-RS.

Chapter 5's section on internationalization and localization describes the setting of localization parameters on HTTP headers, on query parameters, and as part of REST responses. Discussion in this section on runtime content negotiation covers HTTP headers Accept-Language and Content-Language and application of the JAX-RS Variant class.

The "Miscellaneous topics" section of Chapter 5 discusses Hypermedia as the Engine of Application State (HATEOAS), which I believe is one of the most commonly misunderstood and under-appreciated features of REST for those new to REST. This chapter's introduction, which includes examples, is a relatively straightforward and concise introduction to the topic. After introducing HATEOAS, the chapter uses an example of PayPal's REST API support for HATEOAS to illustrate real-world application of HATEOAS.

Another Chapter 5 "Miscellaneous Topic" addresses REST extensibility. This is only covered very briefly (single paragraph) and makes assertions about REST being more maintainable and readable (presumably than SOAP-based web services) with lightly offered justification for these claims. Given how little concrete evidence (and no practical examples) is provided, this section is not very compelling.

Chapter 5 concludes with a brief discussions of topics related to documenting and testing REST-based applications. The most appealing part of this coverage for me was the reference to tools that can be used for testing and documenting REST-based applications. This section introduces REST Assured, which it describes as "the Java DSL for easy testing of RESTful services," and provides a simple illustrative example of this in action. The coverage of Swagger does not illustrate its use, but does describe it as "a language-agnostic framework implementation for describing, producing, consuming, and visualizing RESTful web services."

Chapter 6: Emerging Standards and the Future of REST

Although the Fielding dissertation that codified the REST concept was published in 2000, it continuing rising popularity has meant new developments in understanding and applying of the REST architectural style and in the available related tooling. This chapter begins by describing real-time APIs and describing polling and the disadvantages of polling.

Chapter 6 provides brief explanations of how PubSubHubbub and streaming can each be used to address the limitations of polling. Both of these approaches are explained with text and simple graphics. The section on streaming discusses server-sent events (SSE) and their nonstandard support in Jersey.

RESTful Java Patterns and Best Practices's final chapter also introduces WebHooks, which it defines as "a form of user-defined custom HTTP callbacks." This section uses text description, simple graphics, and coverage of implementing case studies to explain this topic. The WebSockets protocol is also covered in the sixth chapter and is described as "a protocol that provides full-duplex communication channels over a single TCP connection." WebSockets is explained with text descriptions, simple graphics, a table, and a code listing. A couple paragraphs each are also dedicated to introducing (at a conceptual level) XMPP and BOSH over XMPP.

Chapter 6 includes a section with text and a table that compares and constrasts WebHooks, WebSockets, and Server-Sent Events. Chapter 6's section "REST and Micro Services" briefly describes "different advantages of Micro Services as compared to monolithic services."

As is the case with the previous five chapters, Chapter 6 ends with a "Recommended Reading" section and a "Summary." The "Summary" is mostly a summary of the chapter rather than the book, though there is a reference to another book co-authored by this book's author: Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON. The summary for the overall book is left to the Appendix, which is really just another chapter and which I review later in this post.

The sixth and final chapter of RESTful Java Patterns and Best Practices is a high-level overview of trending considerations for REST-based applications. This chapter has very little Java-specific (or JAX-RS-specific) content.

Appendix

Although RESTful Java Patterns and Best Practices's table of contents lists six chapters and an appendix, the Appendix feels just like the six chapters. It not only has "Recommended Reading" and "Summary" sections like its preceding chapters, but it even includes text that refers to "this chapter." The chapter/appendix introduces three REST APIs: REST API from GitHub, Open Graph API from Facebook, and REST API from Twitter. For me, the most interesting aspect of these introductions was how the author illustrated some of the patterns covered previously in the book from each covered API's perspective. This provides reinforcement with concrete APIs of some of the previously discussed concepts and patterns.

The Appendix's "Summary" summarizes the appendix and the entire book.

General Observations

  • The code listings in RESTful Java Patterns and Best Practices are black text on white background with no color syntax (even in the PDF version) and no line numbers. Most of the code listings are short enough that color syntax and line numbers are not as important as they otherwise might be.
  • I liked the approach taken in RESTful Java Patterns and Best Practices of presenting small snippets of code to illustrate points being made and referencing the code available for download for additional and context code.
  • There are several illustrative graphics in RESTful Java Patterns and Best Practices, a few of of them with multiple colors in the PDF edition and some of them in grayscale, and many of them black font on white background, even in the PDF edition.
  • There are some typos in RESTful Java Patterns and Best Practices. They're generally minor and I provide some examples here to demonstrate their nature:
    • One sentence states, "JAX-RS 2.0 had newer Client APIs for accessing RESTful resources."
    • The section introducing JAX-RS annotations discusses @PATH when it really should be @Path.
    • The section on JSON and Jersey references JSONArray and JSONObject when JsonArray and JsonObject are intended.
    • The acronym PPI when spelled out only has an opening parenthesis and not a closing parenthesis.
  • I liked how each chapter included a "Recommended Reading" section with several freely available online resources, most of which had been referenced earlier in the chapter.
  • I liked the Appendix's use of three popular REST APIs to illustrate some of the concepts and patterns introduced in the book's six chapters.
  • In some cases, I would have liked to see more Java/JAX-RS implementation details for certain patterns, especially in the sixth chapter.
  • Other reviews of RESTful Java Patterns and Best Practices are available and worth checking out for a more complete overall picture of the book based upon multiple perspectives:

Conclusion

RESTful Java Patterns and Best Practices introduces basic REST concepts, patterns, and practices and how to apply many of those patterns and concepts with JAX-RS. This book is probably best suited for those looking for introductory information on a broad set of considerations pertinent to REST applications and implementing those considerations with Java and JAX-RS. For those seeking more detailed coverage of REST principles and JAX-RS application of those principles, RESTful Java with JAX-RS 2.0 might be more appropriate.

Wednesday, November 27, 2013

Book Review: Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON

I was particularly interested in accepting Packt Publishing's offer to provide a book review of Masoud Kalali's and Bhakti Mehta's Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON because its title mentions three things I have had good experience with (REST, JAX-RS 2.0, and JSON) as well as a concept that I only have basic familiarity with but wanted to learn more about (WebSockets). For this review, I was provided with an electronic copy of this book with about 100 pages of "regular" text and code examples.

Preface

The Preface of Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON is a good place to start if you are thinking of purchasing this book and want to get an overview of what it entails. The Preface breaks down what is in each of the five chapters with three or four sentence descriptions of each chapter.

It is also in the Preface that the reader learns that the book assumes use of Maven (final chapter only) and GlassFish Server Open Source Edition 4 (most chapters) for building and running the examples. The recent news that Oracle will not provide commercial support for GlassFish 4 has certainly added tarnish to the idea of using GlassFish 4, but it is still a valid application server to use for Java EE illustrative purposes as it remains freely available and is going to continue to be the reference implementation of the Java EE 8 specification.

Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON's Preface also states "who this book is for": "This book is ... for application developers who are familiar with Java EE and are keen to understand the new HTML5-related functionality introduced in Java EE 7 to improve productivity. To take full advantage of this book, you need to be familiar with Java EE and have some basic understanding of using GlassFish application server." I agree that readers of this book will be much better off if they have a basic understanding of Java SE and Java EE principles. Examples of this are terms that are assumed to be implicitly understood such as POJO (Plain Old Java Object) and StAX. Perhaps the most important assumed knowledge is awareness of what JSON is and how it differs from and compares to XML.

Chapter 1: Building RESTful Web Services Using JAX-RS

The initial chapter of Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON begins with a brief introduction to the basic characteristics and principles of the REST architectural style before quickly moving onto "the basic concept of building RESTful Web Services using the JAX-RS 2.0 API." The chapter states that the "Java API for Representational State Transfer (JAX-RS) specification defines a set of Java APIs for building web services conforming to the REST style." Note that JAX-RS 2.0 is standardized via JSR 339 and is more commonly as "The Java API for RESTful Web Services.

Chapter 1 provides step-by-step instructions for converting Java POJOs into RESTful resources via application of JAX-RS annotations such as @Path (defining resource), @GET (defining methods), and @Produces (defining MIME type). This section continues these step-by-step instructions by illustrating how to write an Application subclass and define subresources. Along the way, this chapter also demonstrates using curl to communicate with an HTTP-exposed service from the command line.

After covering converting a POJO to a resource and listing additional JAX-RS annotations in a handy table, the first chapter moves onto discussion of the client API for JAX-RS (this standardized client API for JAX-RS is new to 2.0). Entities, which are passed as part of requests and responses, are also covered along with custom entity providers (implementations of MessageBodyReader and MessageBodyWriter). Use of JAXB with JAX-RS is also introduced.

One part of this chapter that I found particularly interesting and useful is the inclusion of a highlighted section on "Tips for debugging errors with MessageBodyReader and MessageBodyWriter." I would like to see more books have sections like this.

Chapter 1's section on "using the Bean Validation API with JAX-RS" introduces the @ValidationOnExecution annotation as part of Java EE's Bean Validation support. The chapter's Java validation coverage also talks about extracting status responses from Response.readEntity(GenericType<T>) to handle errors.

Chapter 2: WebSockets and Server-sent Events

As the chapter's title suggests, Chapter 2 is an introduction to WebSockets and Server-Sent Events (SSEs), with Chapter 3 going into more details on these subjects. This second chapter begins with an overall view of polling between a client and server and then illustrates an example of this using an Ajax (XMLHttpRequest) JavaScript client example.

After outlining the drawbacks of polling mechanisms between clients and servers, the chapter moves onto coverage of long polling. The XMLHttpRequest of Ajax fame is then used again, but this time with significantly more explanation. The chapter includes a discussion on the disadvantages of long polling.

Chapter 2 introduces concepts that attempt to address the drawbacks and limitations of polling. Server-sent Events (SSE) (or EventSource) are described as "an HTML5 browser API that makes event pushing between server and client available to web application developers." The authors add, "The major SSE API that is considered the foundation of SSE in the client side for JavaScript developers is the EventSource interface." Code listings are provided to illustrate SSE implemented via Java servlet on the server side and JavaScript on the client side along with a JSP example that embeds JavaScript.

WebSockets are the theme of the remainder of Chapter 2 and are described as a "component of HTML5" that "adds a brand new method for interaction between clients and servers to address the scalability and flexibility required for modern web-scale applications by introducing a full duplex event-based communication channel between clients and servers." Chapter 2 mentions that modern browsers support WebSockets and discusses operations available on a JavaScript WebSockets object.

The authors mention that Java EE 7 provides "full support for HTML5, SSE and WebSockets" and references JSR 356 ("Java API for WebSocket").

This information-packed second chapter begins to wind down with a table comparing characteristics (browser performance, communication channel, and complexity) of the three covered communication approaches (long polling, Server-Sent Events, and WebSockets). I liked the fact that the chapter then concludes with example use cases/scenarios where each of the three approaches to asynchronous web communication is best suited.

I found it a bit odd that the second chapter has the side note referencing Jersey as the JAX-RS reference implementation rather than the first chapter (which was devoted to JAX-RS) including that side note. A more appropriate side note for this chapter references the article Memory Leak Patterns in JavaScript.

Chapter 3: Understanding WebSockets and Server-sent Events in Detail

Chapter 3 dives more deeply into the concepts introduced in Chapter 2. These more in-depth topics related to WebSockets include encoders and decoders in the Java API for WebSockets (@ServerEndpoint), Java WebSocket Client API (@ClientEndpoint), sending blob/binary data rather than text (JSON/XML), WebSockets security (including example in GlassFish), and three best practices for WebSockets applications. The more in-depth topics on Server-sent Events covered in the third chapter include an example of developing a Server-sent Event client using Jersey API and three "best practices for applications based on Server-sent Events."

The third chapter introduces JSON and JSON-P.

Chapter 4: JSON and Asynchronous Processing

The fourth chapter of Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON covers JSR 353 ("Java API for JSON Processing") and "related APIs." The chapter explains that Java EE 7 adds JSON support that replaces less standard open source Java JSON processing products such as google-gson and Jackson.

Chapter 4 provides a nice overview of the JSON API and includes a table that lists the classes provided along with a description of the classes and how those classes are used. The authors state that "JSONObject is the entry point to the entire JSON API arsenal," but it is the Json class that provides factory methods for creating instances of other classes in the JSON API. The chapter covers generating JSON documents (JsonGeneratorFactory and JsonGenerator), parsing JSON documents (JsonParser), using JSON object model to generate JSON (JsonBuilderFactory and JsonObject), and using JSON object model to parse JSON (JsonReader and JsonObject). A quick paragraph contrasts when to use the streaming approaches versus the object model approaches for generating and parsing JSON; the trade-off is similar to that between StAX and DOM (memory considerations versus ease of use).

The next section of Chapter 4 covers Servlet 3.1 enhancements with specific focus on NIO additions to servlets (ReadListener and WriteListener) and WebSockets support in servlets. Changes to servlets to support this new functionality are covered and include ServletOutputStream, ServletInputStream, @WebServlet asyncSupported attribute, asynchronous request and response processing, and JAX-RS 2.0 filters and interceptors.

The authors introduce asynchronous support with EJB 3.1 and 3.2 and include an interesting observation: "In Java EE 6, the @Asynchronous [annotation] was only available in full profile while in Java EE 7 the annotation is added to the web profile as well."

One of the interesting side notes of this chapter is mention that key JSON API classes can be used with the Automatic Resource Management (try-with-resources) mechanism introduced with Java SE 7.

Chapter 5: RESTful Web Services by Example

While the first four chapters of Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON are packed with new information and details related to writing RESTful web services with Java EE, JAX-RS 2.0, WebSockets, and JSON, the fifth and final chapter provides two examples of applying these concepts and technologies to representative use cases. The samples in this chapter are built with Maven and deployed to GlassFish.

As the authors advertised at the beginning of the chapter, these two samples do illustrate integrated application of topics covered in the prior chapters of the book. The first sample employs Server-sent Events, Asynchronous Servlet, JSON-P API, JAX-RS 2.0, EJB Timers (@Schedules) and the Twitter Search API (including Twitter's OAuth support and Twitter4j).

The second Chapter 5 example demonstrates integration and application of WebSockets, JAX-RS/HTTP "verbs" (GET, DELETE, POST), using JSON-P for writing JSON documents, and leveraging asynchronous benefits. I like the approach this book has taken of using four information-heavy chapters to introduce concepts and then devoting the entire final chapter to examples of how to integrate these concepts into realistic sample applications.

Miscellaneous Observations

The following are some miscellaneous observations I have made regarding Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON.

  • Covers a lot of material in a relatively small number of pages.
  • Has some interesting and useful emphasized side notes.
  • Lacks a lot of color in the graphics and screen snapshots, meaning the printed book probably does not lose much in way of presentation when compared to the electronic versions.
  • There are some type-setting issues, especially in code samples, where some spaces are missing that would normally separate types, variable names, and so forth.
  • Although Maven and GlassFish are used in the book, many of the examples could be tweaked to build with a Ant, Gradle, or other build system and to be deployed to an application server other than GlassFish.
  • Some experience with Java EE, HTML, and REST/HTTP concepts is assumed. More experience in these areas will obviously make the book more approachable, but only basic familiarity is needed to understand the concepts in this book.
Conclusion

This book is what its title and its preface describe: a book that details how to develop RESTful services with JAX-RS 2.0, WebSockets, JSON, and more. As the authors state in the Preface, this best is best suited for developers with at least minimal Java EE knowledge as there is some assumed knowledge in a book that covers this much in a little over 100 pages.

Thursday, October 6, 2011

JavaOne 2011: REST and Hypermedia as the Engine of Application State with Standard Java APIs

For my last technical session of JavaOne 2011, I wanted to attend something "easy" with a short title because of the mental fatigue and crammed brain resulting from four days of blistering rate of technical information coming my way. With that in mind, I chose to walk across the hall from Hilton San Francisco's Golden Gate 6/7/8 to Golden Gate 3/4/5 for the presentation "REST and Hypermedia as the Engine of State with Standard Java APIs" (24609). Although I have worked with REST and JAX-RS/Jersey, the abstract of this presentation caught my eye. In addition, I believe that HATEOAS may be the least understood, most confusing, and most misused term (or unused portion) in all of REST-dom.

The presenters of "REST and HATEOAS with Standard Java APIs" (Mattias Hellborg Arthursson and Kalle Stenflo, both from Jayway) stayed away from using the acronym HATEOAS because no one seems to know how to pronounce. Because I'm typing it rather than saying it, I'm using the abbreviation from here on out. Their agenda showed items to be covered including REST, JAX-RS, RESTful JAX-RS ("true REST with hypermedia"), and "Generic JavaScript Client."

Stenflo briefly discussed the history of REST based on Fielding's famous dissertation. He mentioned that the "architectural style" of REST had been misused and hijacked by several to be a structural style. Stenflo then went on to discuss the basics of REST with definitions of terms like "resource." He also discussed the HTTP "verbs" and stated that "REST is about using the web the way it was intended." Stenflo discussed "self-descriptive messages" that "contain all information needed to complete a task" (this statelessness is what makes horizontal scaling easier).

Stenflo had multiple slides titled "HATEOAS: Hypermedia as the Engine of Application State." This concept allows for "discoverable resource interaction" and "allows resources to evolve over time." Stenflo explained that the consumer is provided with the correct link for a given resource.

Arthursson stated that if you're doing REST with Java, "you should probably be using JAX-RS." Arthursson introduced some of the key annotations that JAX-RS provides such as @Path, @GET, @POST, @PUT, and @DELETE. He feels (as do I) that the JAX-RS is one of the best JSRs in recent years. The Expert Group for JAX-RS 2.0 is about to publish a draft and the new version will focus on improvements requested from the community. These features include a common client API (that would be very nice) and "support for hypermedia" (JAX-RS currently does not support HATEOAS)

Until JAX-RS 2.0 implementations are available (and the spec is not even written yet!), we need a way to handle hypermedia in Java-based REST style applications. Arthursson introduced some approaches from RESTeasy Atom link, Jersey linking, and "purely annotation-based" approaches that are "more readable, "more versatile," and require DTOs to have "knowledge of hypermedia." His understanding is that the JSR Expert Group is leaning toward the annotation-based approach as well.

Arthursson introduced jax-rs-hateoas as an open source JAX-RS 1.x extension. The README for jax-rs-hateoas states:

JAX-RS-HATEOAS is a small extension to JAX-RS to enable hypermedia in JAX-RS 1.x applications.

Adding hypermedia to your existing application is easily done in four steps:
* Extend HateoasApplication (or JerseyHateoasApplication)
* Add a RequestContextFilter in your web.xml (enables the framework to get access to the full request URIs)
* Add @Linkable annotations to all methods that should be linkable.
* Use HateoasResponse instead for building responses with HATEOAS links.
The normal Response methods (ok, created, entity, etc.) will now return a HateoasResponseBuilder.
The HateoasResponseBuilder contains methods to easily add links to your responses:
** link(String linkId, Object... params) - adds a link to the referenced linkId
(as defined by an @Linkable annotation).
** selfLink(String linkId, Object... params) - adds a link to the referenced linkId with a 'self' rel
(rather than the default rel defined in the referenced @Linkable annotation
** ...etc

Arthursson covered these steps in his slides and then moved to an IDE (SpringSource Tool Suite) to show a live example. His examples demonstrated the ability to use @Linkable from jax-rs-hateoas to provide hypermedia in responses (such as HateoasResponse). The jax-rs-hateoas project seems pretty easy to use and it was stated that it's pretty small and is designed to allow developers to customize their hypermedia as necessary.

Following Arthursson's IDE-based demonstration, Stenflo took back over to demonstrate a JavaScript client that is a "single-page JavaScript application." He stated that it's useful for a developer to test out his or her REST API. The demonstrated client works on hypermedia returned to the client.

The speakers referenced several projects that attendees might find useful in Jayway's Github respository. They specifically referenced rest-assured in addition to jax-rs-hateoas and also stated that the demonstrated JavaScript client is available in the demos section (there is also a core download).

A good question was whether XML was supported in jax-rs-hateoas (only JSON was demonstrated). At this point, only JSON (the "cool stuff") is supported, but they acknowledged that XML needs to be supported.

This was an interesting presentation and looks like a promising solution for bridging the gap between today and JAX-RS 2.0 in terms of appropriately using HATEOAS in REST-based applications using JAX-RS. The project is still young, but could end up filling a niche in the Java/REST world. In the end, it's likely that JAX-RS 2.0 will make this obsolete, but that could be years from now.

Monday, September 20, 2010

JavaOne 2010: Advanced Java API for RESTful Web Services (JAX-RS)

The JavaOne 2010 presentation "Advanced Java API for RESTful Web Services (JAX-RS)" was advertised as "Full" and that turned out to be the case.  Some attendees arrived as late as ten to fifteen minutes after the start, which was obviously not a good idea for such a popular session.  It was standing-room-only for this presentation. Paul Sandoz and Roberto Chinnici alternated in presenting.  I'll refer to them interchangeably here as "they" to avoid the likely mixing up of their names.

JAX-RS is the next release in the JSR-311 specification.  JAX-RS 1.1 is part of Java EE 6, but is not (seemingly inexplicably) part of the Web profile.  The main purpose of JAX-RS 1.1 is to integrate with other Java EE 6 technologies.  They listed seven implementations of JAX-RS: Jersey (reference implementation), Apache CXF, Apache Wink, eXo, RESTEasy, Restlet, Triaxrs.

After a brief "bootstrap" review of JAX-RS, they went into runtime resource resolution.

A section of this presentation was devoted to integration with CDI (JSR 299). When using EJBs with CDI, the general rule is to "annotate with @Path to convert class of a managed component into a root resource."  The presenters also had a bullet emphasizing that "Root resource classes need to be annotated with CDI scope to become CDI managed." This step is necessary due to slightly different models between CDI and JAX-RS. They demonstrated the steps necessary to convert to a CDI resource, including use of the @Inject annotation.  Normal JAX-RS classes may not work properly with CDI; need to use the steps they outlined instead.

Another topic covered in this presentation was runtime content negotiation.  A convenient approach for this in JAX-RS uses the Variant builder class.

One of the sections of this presentation that I found most interesting was that which covered handling of generic type erasure.  The speakers and their slides apologized many times for JAX-RS's and Java's erasure of generic parameterized types.  They showed that type is retained when returned in collection directly, but is lost inside a Response object. The work-around is to use GenericEntity with a method-less implementation. There is talk of JAX-RS 2 providing a JResponse, but will still need to use verbose syntax like JResponse.<List<bean>>. This is probably the best that can be done until we have Java runtime generics reification.

The presenters discussed one of my favorite things about JAX-RS: its elegant handling of exception mapping. They demonstrated that, without mapping, the web container provides a 500 HTTP status code for runtime exceptions. They pointed out that a web application's error page can be used to handle these. Checked exceptions also propagate through, but are wrapped in ServletExcepton. They showed how the exceptions can be mapped to specific HTTP status codes and associated descriptive text instead of the normal Java stack trace.

Before ending this post, I have some general observations. I was not surprised to see the speakers use Curl as a command-line demonstrator in some of their JAX-RS demonstrations.  I was also not surprised that this was a popular session with a waiting line and was almost completely filled to capacity.  The presentation included a lot of code and demonstrations.  Although I had read about and even used several of the covered topics, it was nice to see them all presented again in an organized fashion and to hear from people who live this stuff.  I was especially happy to see that someone else was as bothered by lack of Java runtime generic reification as I am.

Monday, February 15, 2010

JAX-RS and HTTP Responses

HTTP Status Codes are a big part of the HTTP protocol that most of us have seen countless times in our web browsing and development. We are used to seeing 404 (Not Found), 200 (OK), and so forth. Because HTTP is often closely tied with REST style applications, it is not surprising that JAX-RS provides tremendous support for returning appropriate HTTP responses from REST-based web services. In this blog post, I look at the tip of the iceberg in terms of JAX-RS support for HTTP-based service responses.

The code listing that follows would not generally be a useful piece of functionality, but it is used here to demonstrate how easy it is with JAX-RS to generate HTTP responses with specific HTTP status codes.


@Path("/responses")
public class ResponseMaker
{
/**
* Generates an HTTP response based on the String provided as part of this
* resource's URI.
*
* @param responseString Portion of this resource's URI from which the
* particular response will be generated.
* @return Response based on provided URI portion.
*/
@GET
@Path("/{responseString}")
@Consumes("text/plain")
@Produces("text/html")
public Response getResponse(
@PathParam("responseString") final String responseString)
{
final String desiredResponse = responseString != null
? responseString.trim().toUpperCase()
: Status.BAD_REQUEST.name();
Status status = null;
try
{
status = Status.valueOf(desiredResponse);
}
catch (IllegalArgumentException illegalArgEx)
{
status = Status.BAD_REQUEST;
}
return Response.status(status).type(MediaType.TEXT_HTML_TYPE).build();
}
}


The above code uses JAX-RS annotations to indicate which HTTP method corresponds to the Java method in the code listing (@GET indicates HTTP GET method). This simple method accepts a String and, if the String matches one of the Response.Status enum value's string representations, that Status is set. Otherwise, a default of BAD_REQUEST is selected. The Response is built with that status and with a MediaType of TEXT_HTML_TYPE.

I use RESTClient as an easy client tool to demonstrate this simple JAX-RS web service in action. The next two screen snapshots show what RESTClient sees (and what any other client would see) in terms of responses to certain provided URIs (shown at top of GUI).






JAX-RS also makes it easy to turn encountered exceptions into HTTP response codes indicating the error. The next piece of code demonstrates this.


/**
* Return an exception-based HTTP response based on the provided number
* indicating a particular exception to be used. The HTTP method PUT would
* normally likely not be the method used for this type of operation, but
* it makes it easy to differentiate from the other method in this class
* already tied to @GET and also accepting a single String.
*
* There are four cases in which a particular exception is used to build the
* response and that exception and a particular Response.Status are provided,
* telling the JAX-RS provider which HTTP status to tie to that particular
* thrown exception. In the default/general case when one of the first four
* are not used, no specific Response.Status is used, so the general 500
* Internal Server Error will be returned to the client along with the'
* exception's stack trace as the body.
*
* @param exceptionNumberType A number used to determine which type of
* exception is used for the basis of the response.
* @return Response based on the described exception type.
*/
@PUT
@Path("/{exceptionNumberType}")
@Consumes("text/plain")
public Response causeException(
@PathParam("exceptionNumberType") final int exceptionNumberType)
{
Exception exception;
Status status = null;
switch (exceptionNumberType)
{
case 1 : exception = new NullPointerException("1. Null Encountered.");
status = Status.NOT_FOUND;
break;
case 2 : exception = new IllegalArgumentException("2. Bad argument");
status = Status.PRECONDITION_FAILED;
break;
case 3 : exception = new RuntimeException("3. Runtime Exception");
status = Status.BAD_REQUEST;
break;
case 4 : exception = new NumberFormatException("4. Bad Numeric Format");
status = Status.NOT_ACCEPTABLE;
break;
default : exception = new Exception("General Exception");
}
throw status != null
? new WebApplicationException(exception, status)
: new WebApplicationException(exception);
}


I included some verbose comments on this method to describe how it behaves in greater detail. This method primarily demonstrates how the WebApplicationException is useful in turning Java exceptions into HTTP responses. I only use two of this exception's eight constructors in this example, but they demonstrate the difference between providing a particular HTTP Response.Status with the exception (and counting on the JAX-RS provider to place the results of Response.Status.getReasonPhrase() in the response body) or allowing the JAX-RS provider to associated a Response.Status with the exception (500) and showing the entire stack trace of the exception.

This difference is demonstrated in the next three screen snapshots. Two are of exceptions for which a particular (largely nonsensical here and only meant to illustrate how to do this) HTTP status code is associated with the exception and one is for the case where the JAX-RS provider assigns 500 implicitly and puts the exception's stack trace in the response body rather than the Response.Status.getReasonPhrase().







In this post, I have attempted to demonstrate how easy JAX-RS makes it to specify HTTP responses based on regular and exceptional conditions. I have only touched on a small part of the extensive JAX-RS support for building appropriate responses.