Thursday, October 30, 2014

Book Review: Play Framework Essentials

This post is a review of Julien Richard-Foy's recently published Play Framework Essentials (Packt Publishing). Play Framework Essentials consists of seven chapters and approximately 180 pages of substantive content. The book's subtitle is, "An intuitive guide to creating easy-to-build scalable web applications using the Play framework."

Preface

The Preface of most Packt Publishing books is a great place to start when trying to decide whether to read a Packt Publishing book. This is because the Packt Publishing Prefaces, including the Preface of Play Framework Essentials, frequently summarize each of the chapters of the book (one to three sentences per chapter in this case), describe what is needed for using the book's examples (Play 2.3.x, JDK 6 or newer, and a web browser in this case), and who the target audience is ("Java or Scala developers who already have some knowledge of web development" in this case).

Chapter 1: Building a Web Service

With a title that include the word "essentials", one might expect the book to be light of "fluffy" text and this is the case with Play Framework Essentials. The initial chapter of Play Framework Essentials starts off fast with a very brief description of what the Play Framework is before diving immediately into the first example that shows the Scala and Java versions of the service layer. The chapter then explains how to bootstrap a Play Framework application with Typesafe Activator.

The remainder of the chapter demonstrates building a simple application with the Play Framework. Along the way, the chapter introduces sbt (described as "a build tool for Scala projects"), Human-Optimized Config Object Notation (HOCON) for configuration, URL routing in Play, curl (for testing connectivity to session via HTTP), building HTTP responses with HTTP status codes, serializing data in JSON (includes mention of significant differences between implementing in Java or Scala), reading JSON data, validating JSON data.

Chapter 2: Persisting Data and Testing

Chapter 2 of Play Framework Essentials begins with a coverage of Play's support for integrated testing with specs2 (Scala) and JUnit (Java). There is a section that describes Play's use of Scala's reverse routing. The test-focused portion of the second chapter ends with discussion regarding effective writing of HTTP tests and "running a fake Play application."

The second half of Play Framework Essentials's second chapter is focused on database persistence with specific focus on use of Play's JDBC plugin and JPA plugin. After looking at use of JDBC-based persistence, the chapter moves to coverage of using Slick (Scala) and JPA (Java).

Part of Chapter 2's coverage of database persistence with Play discusses use of GlobalSettings to use startup of a Play application to enable database fixtures. Play's database evolutions support is also covered. Chapter 2 concludes with a section on using H2 as an in-memory database for testing code related to relational databases.

Chapter 3: Turning a Web Service into a Web Application

The third chapter of Play Framework Essentials is about building a web application with user interface from a web service. The chapter introduces the template engine Twirl and provides several examples of syntax and constructs used with the template.

The middle portion of Chapter 3 deals with HTML forms. In particular, it covers generation of forms and reading and validating form data. Discussion touches on Play's HTML helpers and how these can be customized. The chapter's section on form validation specifically covers both the Java validation API and the Scala validation API. The chapter introduces Scala-based content negotiation and provides examples of how to write "some helper functions similar to the Scala content negotiation API" for Java.

Play Framework Essentials's third chapter concludes with an introduction of Selenium as an approach to "programmatically drive a web browser" and an introduction of FluentLenium as "a library that provides a fluent interface for the [Selenium] WebDriver." This section of the chapter demonstrates their use with Java and Scala to test the web interface.

Chapter 4: Integrating with Client-side Technologies

Chapter 4 of Play Framework Essentials continues from where Chapter 3 left off. While Chapter 3 discussed converting web services into web applications, Chapter 4 covers integrating traditional web client-side technologies with the applications built on top of the Play framework. The author points out an interesting observation regarding Play and these client-side technologies: "The Play framework essentially focuses on the server-side part of your application and gives you freedom on which client-side technology to use." Chapter 4 focuses on the features that Play does provide to assist with the development of the client.

The first client-side-supporting feature of Play discussed in Chapter 4 is serving of static (or public) assets. JavaScript reverse routing is another Play feature covered in this chapter.

The fourth chapter introduces sbt-web as "an sbt plugin family" that "can manage ... processing steps" such as generating JavaScript from higher-level languages (sbt-coffeescript and sbt-less) and concatenating (sbt-rjs), minifying (sbt-uglify), and compressing (sbt-gzip) code. It demonstrates examples of each of these functions implemented using an sbt plugin. The chapter also discusses using sbt-web plugin's support of WebJars as "a repository of client-side artifacts" and using the sbt-mocha plugin to "run Mocha tests from the sbt test runner."

Play Framework Essentials's fourth chapter ends with a more substantial "Summary" section than one typically sees in books. In fact, it includes a useful graphical representation of how the plugins covered in the chapter fit together is the "assets processing pipeline."

Chapter 5: Reactively Handling Long-running Requests

Chapter 5 of Play Framework Essentials "presents the challenges of stream processing and the way the Play framework solves them." The chapter begins by referencing Benjamin Erb's diploma thesis Concurrent Programming for Scalable Web Architectures and introducing Play's "evented execution model." The author explains how the Scala model can be better, but warns that caution needs to be used to explicitly ensure that threads are not blocked. He introduces Play's support for Scala's Future API to allow for asynchronous blocks. The author also describes the need to use a distinct execution context to handle blocking functionality such as JDBC interaction with a relational database. This section is also useful because it introduces and briefly explains Akka.

Another significant section of Chapter 5 introduces Iteratee, which the author describes as "an incremental computation" and which he warns should be used only with Scala (not with Java). Enumerators are introduced by comparing them to iteratees: "Streaming results using enumerators Iteratees make it possible to consume streams of data in a non-blocking way. Conversely, enumerators produce data streams in a non-blocking way."

The Summary of Chapter 5 states, "This chapter detailed a lot of things on the internals of the framework." That might be an understatement. There is a lot of detailed description of the internal workings of the Play Framework in this chapter. I felt like this chapter really points out some of the distinguishing features of Play.

Chapter 6: Leveraging the Play Stack – Security, Internationalization, Cache, and the HTTP Client

Play Framework Essentials's sixth chapter begins by articulating the topics covered in the chapter: security (authentication, cross-site scripting, cross-site request forgery, HTTPS), cache, internationalization, and HTTP client. The section of authentication explains and illustrates using Java and Scala examples how Play supports session scope/cookies in conjunction with authentication. The sections on cross-site scripting (XSS) and cross-site request forgery (CSRF) explain tactics that can be used to avoid those vulnerabilities.

The portion of Chapter 6 covering CSRF delves into Play's support for HTTP request filters. It uses this introduction to Play filters to look at Play's CSRF Filter, which is described as a filter that "automatically checks that the CSRF token of a form submission corresponds to the one in the client's session."

Chapter 6's section on HTTPS states that Play's default is to "use only HTTP." This section then demonstrates configuring HTTPS via system property specification.

Chapter 6 describes Play's cache support (which is built upon Ehcache): "Play provides a minimal cache library and some controller level caching features that can help you leverage both client-side and server-side caches." The coverage of Play's cache support includes Java and Scala examples and talks about client-side and server-side caching. The chapter's discussion of Play Framework's internationalization support also covers both Scala and Java examples.

The sixth chapter concludes with sections on calling remote web services and begins with an introduction of OAuth 2.0. The chapter then proceeds to discuss how to connect to the reader's "preferred social network" using an OAuth client to call the HTTP API of the preferred social network.

Chapter 7: Scaling Your Codebase and Deploying Your Application

The final chapter of Play Framework Essentials "presents common code patterns you want to use in order to keep a productive code base." The chapter begins by discussion how to apply Play's action builders to make an "action's logic reusable and composable." The chapter then goes on to discuss use of dependency injection to achieve greater modularity. An example using Guice is presented as part of this discussion on dependency injection. The section of Chapter 7 on mocking applies Mockito.

Chapter 7 also looks at separating application code into separate independent artifacts with specific focus on splitting the controller into multiple artifacts. Th chapter then moves onto deployment with brief sections on deploying to traditional infrastructure and deploying to the cloud. There is also a section on distinguishing between development and production modes using different configuration files or system properties.

General Observations
  • Play Framework Essentials provides examples in both Scala and Java. There are a couple of advantages of this. The first is that it allows developers to use the language they are more comfortable with or are allowed or expected to use when using Play. The second advantage is that it allows Java developers to learn more about Scala by comparing Scala examples to Java examples. The only downside is that explanations take longer when both languages are used, but I consider the value of examples in both languages greater than the cost. It is fairly easy to skip over the examples written in the language that is not of interest. I also like that the author mentions when certain features are only available in Scala or in Java.
  • The code listings in Play Framework Essentials tend to be well-formatted. The biggest downside of these code listings is their lack on line numbers and the black text on white background (no color syntax highlighting).
  • Play Framework Essentials includes several graphics depicting architecture and other high-level concepts. Although these generally serve their purpose of illustrating what is being described, it would have been nice to have some color in more of these in the electronic version rather than the grayscale presentation of several of them. However, these grayscale images are sharp enough that I suspect they present well in printed copies.
  • Although Play Framework Essentials has under 200 pages and largely focuses on "essentials" of the Play Framework, I still felt like there was a lot of detail in this book. The book contains low-level and high-level details, but spends (or wastes, depending on your perspective) little time on introductory and historical details. All chapters are relatively technically detailed, but Chapters 5 through 7 are particularly detailed.
Conclusion

Play Framework Essentials does as its title suggests and introduces essential aspects of the Play Framework.

Friday, October 24, 2014

Book Review: Learning AngularJS for .NET Developers

The subtitle of Alex Pop's Learning AngularJS for .NET Developers (Packt Publishing) is "Build single-page web applications using frameworks that help you work efficiently and deliver great results." Learning AngularJS for .NET Developers consists of approximately 175 substantive pages divided into 6 chapters. This blog post is my review of Learning AngularJS for .NET Developers.

Preface

The "Preface" of Learning AngularJS for .NET Developers describes how web development has changed with focus on single-page applications behaving more like desktop applications and using approaches such as responsive web design and progressive enhancement.

The Preface also describes the objective of the Learning AngularJS for .NET Developers and the experience readers of the book should have before reading it:

The main focus of this book is on how to rapidly prototype and build modern web applications with AngularJS in the context of .NET development tools and frameworks. The book assumes the reader has already built websites, web applications, or web services using Microsoft technologies such as ASP.NET, ASP.NET MVC, Silverlight, or WCF and knows the fundamentals of HTML5, CSS3, JavaScript, jQuery, and ASP.NET MVC.

The "Who this book is for" section of the Preface reaffirms its intended audience: "The book is targeted at .NET developers who have already built web applications or web services and have a fundamental knowledge of HTML, JavaScript, and CSS. As is the case with other Packt Publishing books I have reviewed, the Preface of Learning AngularJS for .NET Developers provides short descriptions of each of the book's six chapters.

The final significant observation from Learning AngularJS for .NET Developers's Preface that is important to highlight here comes from its "What you need for this book" section. That section states that Visual Studio 2013 Professional is recommended, but that Visual Studio 2013 Express for Web is sufficient. Node.js, Node.js Tools for Visual Studio, and JDK 7 are recommended for testing. Later in the book, the author also recommends use of Google Chrome web browser with the AngularJS Batarang extension.

Chapter 1: Introducing AngularJS

The initial chapter of Learning AngularJS for .NET Developers is dedicated to AngularJS. The chapter includes a reference to the AngularJS 1.2.15 Documentation and to the AngularJS 1.2.15 API Documentation because a single chapter cannot cover all the details of AngularJS. The chapter then uses examples to introduce AngularJS concepts.

The first examples of Chapter 1 demonstrate fundamental characteristics of an AngularJS application by comparing a single example written in AngularJS to the same example implemented with jQuery and JavaScript. This comparison and the accompanying text are a nice method for introducing AngularJS, how it is different, and highlighting some of its advantages. The text description associated with the first comparison-oriented example introduces significant AngularJS concepts such as directives, expressions, and scopes.

Learning AngularJS for .NET Developers's first chapter includes sections on AngularJS architecture and the structure of an AngularJS application. The latter part includes discussion of AngularJS modules. The section on "JavaScript patterns and practices used in AngularJS applications" includes some nice explanations of JavaScript scope and hoisting issues and how these are often dealt with in AngularJS applications using JavaScript patterns such as Immediately-Invoked Function Expressions (IIFE) and revealing module pattern, using JavaScript strict mode, and using explicit dependency injection.

The lengthy first chapter (almost one-fourth of the entire book) of Learning AngularJS for .NET Developers moves onto an introduction of controllers and services in AngularJS and then moves onto more detailed description of directives that were introduced by example earlier in the chapter. In particular, this section covers specific built-in AngularJS directives ngRepeat and ngInclude before looking at creation of custom AngularJS directives. The chapter concludes with a discussion of AngularJS filters.

Chapter 2: Creating an AngularJS Client-side Application in Visual Studio

The initial chapter of Learning AngularJS for .NET Developers is completely focused on AngularJS and is useful to anyone using AngularJS regardless of whether they are using .NET or not. Chapter 2 is the first chapter of Learning AngularJS for .NET Developers that includes .NET-specific details. The author states that this chapter "assumes that you already know the fundamentals of .NET web development using Visual Studio."

The second chapter of Learning AngularJS for .NET Developers introduces using VisualStudio with an empty web project that doesn't require specification of any particular web framework. The chapter then explains and demonstrates use of NuGet to download packages. Several NuGet commands run in VisualStudio are demonstrated and a quick reference is made to the NuGet command line tool. The chapter briefly discusses Visual Studio extensions in general before specifically focusing on the Web Essentials 2013 and SideWafflet extensions which the author maintains turn Visual Studio into "a powerful AngularJS IDE."

Chapter 2 builds a client-side example based on AngularJS and Bootstrap. This example explanation begins by discussing "the organization of AngularJS code" as exemplified in the AngularJS starter project angular-seed. It provides a brief overview of other approaches for organizing an AngularJS application.

Learning AngularJS for .NET Developers's second chapter looks at integrating AngularJS with JavaScript with a section on integration with native JavaScript and a section on integration with third-party JavaScript frameworks. The section of Chapter 2 on routing describes how AngularJS supports two types of routing to allow a single page application to appear to update "seamlessly" in the web browser even for different URLs. The chapter concludes with a demonstration of building a client-side application with a bicycle rental management example.

Chapter 3: Creating .NET Web Services for AngularJS

Chapter 3 of Learning AngularJS for .NET Developers begins with a brief introduction to .NET's historical support for SOAP-based web services with ASP.NET Web Services and Windows Communication Foundation (WCF). Discussion then moves into a brief overview of REST and support for REST in AngularJS. This part of the chapter introduces Hypermedia as the Engine of Application State (HATEOAS), but then states that HATEOAS will not be used in the book's examples.

A section in Chapter 3 looks at different .NET-oriented RESTful web services frameworks that can be used with AngularJS (including ASP.NET Web API) before focusing on ServiceStack. The chapter lists advantages of ServiceStack, provides a brief overview of ServiceStack, and presents a small ServiceStack example application that demonstrates several key features of ServiceStack.

After introducing the use of ServiceStack to implement web services, the third chapter of Learning AngularJS for .NET Developers looks at invoking RESTful web services from AngularJS using the ngResource module. This section includes coverage of AngularJS's Promise API.

Chapter 4: Creating an AngularJS, ASP.NET MVC, ServiceStack Application

Chapter 4 of Learning AngularJS for .NET Developers begins with discussion of advantages of ASP.NET MVC and some primary features provided by ASP.NET MVC. The chapter demonstrates how to integrate ASP.NET MVC into the "Rent that Bike!" sample application started earlier in the book and with ServiceStack. The chapter also discusses the additional complexity associated with "changing an AngularJS application to use the HTML5 History API instead of hashbang URLs."

The fourth chapter of Learning AngularJS for .NET Developers examines "ASP.NET bundling bundling and minification features for AngularJS files." The chapter also briefly describes multiple approaches for securing AngularJS applications. ServiceStack.Mvc is introduced as a means for "deeper integration" of ServiceStack and ASP.NET MVC.

The focus of Chapter 4 switches from security to approaches to "ensure that AngularJS works well with the backend." Specific approaches include alerting users to existence of long-running operations and handling exceptions with $http interceptor and the $q promise.

There is a section in Chapter 4 on database persistence. The author mentions several .NET-oriented ORM and micro-ORM frameworks, but focuses on ServiceStack.OrmLite and introduces ServiceStack.OrmLite.Sqlite32 for use with SQLLite. I also liked the author's referencing of Firefox add-on SQLite Manager.

Chapter 5: Testing and Debugging AngularJS Applications

The fifth chapter of Learning AngularJS for .NET Developers reintroduces Node.js and also mentions Node.js Tools for Visual Studio as foundational for testing AngularJS applications. The chapter demonstrates coverage of installing Node.js, installing and configuring Karma, an overview of using Jasmine and injecting mocking with $httpBackend service.

Chapter 5 introduces Protractor, which it describes as "an AngularJS-friendly wrapper around the Selenium WebDriver browser automation framework." There is a section that discusses how to install Protractor, including installing the JDK for Selenium to use. The next section describes configuration of Protractor before discussing writing Protractor tests.

Learning AngularJS for .NET Developers's fifth chapter covers several more testing-related subjects. These include testing web service endpoints, using xBehave.net for behavior-driven development (BDD) tests, xUnit.net, the moq4 framework, debugging AngularJS applications with AngularJS Batarang, and using JavaScript frameworks to deal with HTML5 validation and older web browsers.

Chapter 6: Advanced AngularJS Topics

The final chapter of Learning AngularJS for .NET Developers covers four "advanced AngularJS topics": internationalization and localization (ngLocale and angular-dynamic-locale), AngularJS animations (ngAnimate), remote web services (JSON with padding [JSONP] and Cross-origin Resource Sharing [CORS]), and template caching ($templateCache).

General Observations
  • Learning AngularJS for .NET Developers includes several code listings. These are black font on white background (no color syntax) without line numbers. However, the code can also be viewed in Visual Studio or even via Plunker (which provides color coded syntax and line numbers) using URLs provided in the book's text. The book's code listings include bold highlighting of portions of the code that are the specific focus of the associated text.
  • Learning AngularJS for .NET Developers includes useful diagrams that help to understand AngularJS's architecture and lifecycle. A couple of these are black-only on white background even in the electronic (PDF) version I reviewed. Some descriptions differentiate portions of the graphic by referring to "darker" but this can be difficult to distinguish.
  • The PDF version of Learning AngularJS for .NET Developers includes color screen snapshots (such as of using Visual Studio); I assume this is true for other electronic formats.
  • The title of Learning AngularJS for .NET Developers advertises this as a book about using AngularJS with .NET. The author frequently mentions in the book that it is assumed that the reader knows certain background technologies and concepts when reading that chapter. Even though the title and the author's many statements make this very clear, I cannot overemphasize this point: Learning AngularJS for .NET Developers is best suited for .NET developers with basic web skills who want to learn and apply AngularJS. Developers wanting to learn to use AngularHS with Java EE or some other back-end technology should look elsewhere. That stated, the single chapter that focuses exclusively on AngularJS is a nice introduction to and high-level coverage of AngularJS.
  • By assuming readers' .NET experience, Learning AngularJS for .NET Developers is able to focus primarily on AngularJS and developing applications with AngularJS and integrating AngularJS with .NET.
  • Learning AngularJS for .NET Developers is generally well-written and the text is fairly easy to follow and understand.
  • As one would expect from a book on using AngularJS with .NET, Learning AngularJS for .NET Developers provides significant coverage of applying Visual Studio and integrating AngularJS with .NET. However, it also contains quite a bit of coverage on open source and third-party products that are commonly used in applications built with AngularJS and .NET.
Conclusion

Learning AngularJS for .NET Developers delivers on what its title advertises. Readers of Learning AngularJS for .NET Developers should expect to learn the basics of AngularJS and how to apply AngularJS to front-ends for their .NET applications. The book does assume some .NET knowledge and experience and does devote considerable attention to using .NET frameworks and Visual Studio. I also like that the book mentions several open source projects and demonstrates integrating those with the applications built with AngularJS and .NET.

Wednesday, October 22, 2014

Java Extension Mechanism Loads All JARs

The Java Extension Mechanism is described in the Java Tutorial as a "standard, scalable way to make custom APIs available to all applications running on the Java platform." As described in Understanding Extension Class Loading, "the extension framework makes use of the class-loading delegation mechanism" with extension classes loaded after the bootstrap classes in rt.jar (and related JARs) but before the classes loaded from the typical classpath.

The extension directory works a bit like the classpath in that its part of the class loading mechanism and classes available within JARs in the extension directory are made available to Java applications. There are some key, differences, however, and some of these are highlighted next.

Characteristic Classpath Extension Mechanism (Optional Packages)
Scope Typically Application-Specific
Potentially All JREs on Host
All JVMs Running in Specific JRE All Host's JREs
  • Solaris: /usr/jdk/packages/lib/ext
  • Linux: /usr/java/packages/lib/ext
  • Windows: %SystemRoot%\Sun\Java\lib\ext
How Specified .jar Files
  • Explicitly specified by name (including .jar)
  • Wildcard (*) matching all all JAR files with .jar extensions
.class Files
  • Directory containing .class files specified
All JAR files (even if extension other than .jar or no extension at all) in designated directories are loaded.
Class Loading Order After bootstrap and extensions loading. After bootstrap but before classpath.

One of the most significant observations worth some more emphasis is that the extension mechanism will pick up all JAR format files in the extension directory even if the file does not have a .jar extension. The implication of this is that while one can change the name of a JAR located in a classpath directory to have an extension other than .jar so that the wildcard does not pick it up, this technique will not work with the extension directory.

I'm going to use some simple examples in this post to demonstrate some of these differences. The next two code listings are for a very simple HelloWorld class and a main application class called Main that uses the HelloWorld class.

HelloWorld.java
public class HelloWorld
{
   @Override
   public String toString()
   {
      return "Hello, World!";
   }
}
Main.java
import static java.lang.System.out;

public class Main
{
   public static void main(final String[] arguments)
   {
      out.println(new HelloWorld());
   }
}

To demonstrate a primary difference between classpath and the extension mechanism (optional packages), I will archive the compiled HelloWorld.class file into a JAR called HelloWorld.jar and place it in a different directory than the compiled Main.class file.

To demonstrate the use of the traditional classpath, I place the HelloWorld.jar file in a directory called C:\hello and will access that JAR via wildcard (*) for Main to use. This is demonstrated in the next two screen snapshots.

The two previous images demonstrate that the Java Main application can still load the HelloWorld.class file even though I had deleted it from the current directory because the Java launcher was explicitly told (via the -classpath option) to look for it in C:\hello. Using the extensions mechanism (optional packages), it is possible to have the class loaded without it being in the same directory and without explicit classpath specification. This is shown in the next screen snapshot.

The previous screen snapshot demonstrates that the Java launcher doesn't even need the HelloWorld.class in the same directory or specified on its classpath when that class is inside a JAR that is in the extensions (optional packages) directory. This is often cited as a benefit of using the extensions mechanism because all applications using that JRE (or potentially all applications on the host) can see the same classes without need to explicitly specify them on the classpath.

With the traditional classpath approach of instructing an application to load classes from JARs, the JAR file containing the .class file needs to end with the .jar extension. The next screen snapshot demonstrates what happens when the HelloWorld.jar is renamed HelloWorld.backup in the same classpath-referenced directory.

The last image demonstrates that a NoClassDefFoundError is encountered when the JAR file in the classpath-referenced directory does not have a .jar extension. Perhaps a bit surprisingly, the extensions (optional packages) mechanism does not work the same way. Instead, all JAR files in the extensions specified directory are loaded regardless of their extension and regardless of even if they have a file extension. This is demonstrated in the next screen image.

The previous image demonstrates that renaming the JAR file that resides within the extensions directory to not have any file extension whatsoever does not prevent the classloader from loading the classes of that JAR. In other words, the classloading mechanism loads all JAR files in the specified extensions directory based on file type rather than on file name or extension. As the Optional Packages Overview summarizes, "There is nothing special about any particular JAR file itself or the classes it contains that makes it an installed optional package. It is an installed optional package by virtue of its location in jre/lib/ext."

There are some risks and downsides associated with placing too many class definitions in JARs inside the extensions directory. It can be maddening to wonder why NoSuchMethodErrors, for example, are occurring when one can see that a class specified explicitly on the classpath has the method in question. I have previously written about one of the many potential causes of NoSuchMethodError, but forgotten outdated and obsolete class definitions residing inside of JAR files in the extensions directory are another potential cause. This is demonstrated next.

The next two code listings show revised versions of Main.java and HelloWorld.java. In particular, HelloWorld has an all-new method that the new version of Main invokes. In this case, I'm going to leave the newly compiled HelloWorld.class file in the same directory when I run the Main to demonstrate that the old, busted version of HelloWorld.class in the JAR in the extensions directory takes precedence over the new hotness HelloWorld.class in the current directory.

Revised Hello World.java (New Method)
public class HelloWorld
{
   @Override
   public String toString()
   {
      return "Hello, World!";
   }

   public String directedHello(final String name)
   {
      return "Hello, " + name;
   }
}
Revised Main.java
import static java.lang.System.out;

public class Main
{
   public static void main(final String[] arguments)
   {
      final HelloWorld helloWorld = new HelloWorld();
      out.println(helloWorld);
      out.println(helloWorld.directedHello("Dustin"));
   }
}

The last image demonstrates that the now obsolete class definition of HelloWorld in the extensions directory takes precedence over the new class definition of HelloWorld in the same directory. Even when I specify the current directory on the classpath, the old version in the extensions directory takes precedence. This is shown in the next screen snapshot, which also shows that the JAR in the extensions directory that is "hiding" the newer JAR and its class's newer method is still not even named with a .jar extension.

The example just demonstrated is not even the most difficult situation a forgotten JAR in the specified extensions directory (or directories) can cause. In that example, at least I had a NoSuchMethodError to alert me to a problem. A potentially even more difficult situation to debug can exist when the old class definition has the same method signature but has an outdated method implementation. In such cases, there may be no error, exception, or throwable of any kind, but the application logic will simply not work correctly or as expected. The old functionality could exist in the code base for some time before it's even recognized as an issue, especially if unit tests and other testing is lacking.

Use of the extensions directory can make things easier on developers because classes in JAR files residing in the extensions directory (or directories) are available to all applications in the JRE associated with the extensions directory (or with all JREs on the host if the operating system-based host-wide extensions directory is used). However, there are definite risks associated with too liberal use of the directory. It can be easy to forget that outdated class definitions residing in JARs in that directory are preventing classloaders from loading the newer and seemingly obvious versions of the class definitions. When this happens, the very extensions (optional packages) mechanism that made developers' lives easier now make it more difficult.

Elliotte Rusty Harold provides a warning about use of the extensions (optional packages) mechanism, "While this seems convenient, it is also a long-term mistake... Sooner or later (probably sooner), you'll load the wrong version of a class from a place you aren't even thinking about and waste hours debugging." The Java Tutorial also recommends caution (I added the emphasis), "Since this mechanism extends the platform's core API, its use should be judiciously applied. Most commonly it is used for well standardized interfaces such as those defined by the Java Community Process, although it may also be appropriate for site wide interfaces."

Although the extensions (optional packages) mechanism is similar to the classpath mechanism and both are used as part of class loading, the differences between the two are important to note. In particular, it is important to remember that all JAR files (even if they don't have .jar file extensions) that reside in the directory referenced as an extension directory will be loaded. Renaming these JARs and even changing their file extension will not be sufficient to have the classloading ignore them. With classpath, on the other hand, renaming the JAR is sufficient to prevent loading when the classpath specifies individual JAR files explicitly and changing the file extension is typically sufficient to prevent loading even when the classpath uses the wildcard (*) to specify all JARs in a directory.

There are situations when the extensions (optional packages) mechanism is the appropriate choice, but these seem fairly rare. It is also important to keep in mind the extensions (optional packages) mechanism in mind when dealing with unexplained NoSuchMethodErrors so that one can check it out to see if the offender lives in that directory or directories.

Wednesday, October 15, 2014

Java Minor Releases Scheme Tweaked Again

In 2013, Oracle announced the Java SE - Change in Version Numbering Scheme. The announcement stated that Limited Update releases (those "that include new functionality and non-security fixes") and Critical Patch Updates (CPUs) [those "that only include fixes for security vulnerabilities"] would be released with specific version number schemes. In particular, Limited Use Releases would have version numbers with multiples of 20 while Critical Patch Updates would have version numbers that are multiples of 5 and come after the latest Limited Use Release version number. The purpose of this scheme change was to allow room for versions with numbers between these, which allows Oracle "to insert releases – for example security alerts or support releases, should that become necessary - without having to renumber later releases."

Yesterday's announcement ("Java CPU and PSU Releases Explained") states, "Starting with the release of Java SE 7 Update 71 (Java SE 7u71) in October 2014, Oracle will release a Critical Patch Update (CPU) at the same time as a corresponding Patch Set Update (PSU) for Java SE 7." This announcement explains the difference between a CPU and a PSU:

Critical Patch Update CPU "Fixes to security vulnerabilities and critical bug fixes." Minimum recommended for everyone.
Patch Set Update PSU "All fixes in the corresponding CPU" and "additional non-critical fixes." Recommended only for those needing bugs fixed by PSU additional fixes.

Yesterday's announcement states that PSU releases (which are really CPU+ releases) will be released along with their corresponding CPU releases. Because the additional fixes that a PSU release contains beyond what's in the CPU release are expected to be part of the next CPU release, developers are encouraged to experiment with PSU releases to ensure that coming CPU features work well for them.

Tuesday, October 14, 2014

NetBeans 8.0's Five New Performance Hints

NetBeans 8.0 introduces several new Java hints. Although there are a large number of these new hints related to Java Persistence API, I focus on five new hints in the Performance category.

The five new "Performance Hints" introduced with NetBeans 8.0 are:

  • Boxing of already boxed value
  • Redundant String.toString()
  • Replace StringBuffer/StringBuilder by String
  • Unnecessary temporary during conversion from String
  • Unnecessary temporary during conversion to String

Each of these five performance-related Java hints are illustrated in this post with screen snapshots taken from NetBeans 8.0 with code that demonstrates these hints. There are two screen snapshots for each hint, one each showing the text displayed when the cursor hovers over the line of code marked with yellow underlining and one each showing the suggested course of action to be applied to address that hint (shown when clicking on the yellow light bulb to the left of the flagged line). Some of the captured screen snapshots include examples of code that avoid the hint.

Boxing of Already Boxed Value

Redundant String.toString()

Replace StringBuffer/StringBuilder by String

Unnecessary Temporary During Conversion from String

Unnecessary Temporary During Conversion to String

Unless I've done something incorrectly, there appears to be a minor bug with this hint in that it reports "Unnecessary temporary when converting from String" when, in this case, it should really be "Unnecessary temporary when converting to String". This is not a big deal as the condition is flagged and the action to fix it seems appropriate.

Conclusion

The five performance-related hints introduced by NetBeans 8.0 and illustrated here can help Java developers avoid unnecessary object instantiations and other unnecessary runtime cost. Although the benefit of this optimization as shown in my simple examples is almost negligible, it could lead to much greater savings when used in code with loops that perform these same unnecessary instantiations thousands of times. Even without consideration of the performance benefit, these hints help to remind Java developers and teach developers new to Java about the most appropriate mechanisms for acquiring instances and primitive values.

Thursday, October 9, 2014

JavaOne 2014 Observations by Proxy

I wasn't able to attend JavaOne this year, but have been happy to see some online resources covering what happened at JavaOne 2014. In this post, I summarize some of the observations made at JavaOne 2014 and provide links to references providing these observations or providing more background details on those observations. The listed observations are in no particular order and many of them come from the JavaOne 2014 Keynote Addresses.

Rapid Adoption of Java 8

The Oracle Press Release associated with JavaOne 2014 states, "Since its launch in March 2014, Java SE 8 has achieved record adoption rates. Overall, adoption is up more than 20 percent compared to the same post-launch time period for Java SE 7."1 George Saab highlighted this rapid adoption with the observation in the Strategy Keynote that there are already eight Java 8 publications available in eight different languages.4.

Intel and Java

Intel was an "Innovation Sponsor" of JavaOne 2014 and, because of that, had a portion of the JavaOne 2014 "Java Partner Community Keynote" address. In this address, it was stated that Java runs 32 times faster on Intel since 20072. It was also announced that Intel has joined the OpenJDK as a Contributing Member.2,5

New OpenJDK Partners

The Oracle Press Release for JavaOne 2014 mentions other recently added new partners to the OpenJDK team: FreeBSD Foundation, GE Digital Energy, and Microsoft Open Technologies, Inc.1

JDK Modularity / Project Jigsaw

It was confirmed in the "Java Partner Community Keynote" address that Oracle does intend to deliver modularity with JDK 9.2,6 Modularization was scheduled for previous versions of Java, but has been kicked down the road from JDK 8 and from JDK 7 before that. The Oracle Press Release announcing JavaOne 2014 states, "Oracle has begun work on the JDK 9 Project in the OpenJDK Community. New features will focus on modularity, performance, stability, and portability."1

Project Valhalla and Project Panama

In the Community Keynote2,5, Brian Goetz cited Project Valhalla (experimental JVM and language features and not to be confused with a much older Project Valhalla) and Project Panama ("Interconnecting JVM and native code"). The promise of value types was also discussed in this part of the keynote.2,5

Eclipse's Open IoT Stack

The Eclipse Foundation announced the Open IoT (Internet of Things) Stack at JavaOne 2014.3

JavaOne 2014 Talks on Parleys.com

It was announced that JavaOne 2014 talks will be on Parleys.com.5

Miscellaneous Java Usage Statistics

Oracle likes to announce splashy statistics related to "Java" (the language and the platform). This year's edition was no different1:

  • 9 million developers worldwide
  • More than 3 billion devices are powered by Java technology
  • More than 125 million Java-based media devices have been deployed
  • Over 10 billion Java Cards have been shipped since its introduction
Duke Has An Alias: Fang

One of the more important revelations from JavaOne 2014 for some of us is that Duke was formerly known as Fang.5.

JavaOne 2015

JavaOne 2015 will be October 25–29, 2015, in San Francisco, California.

Online References to JavaOne 2014

Tuesday, October 7, 2014

Book Review: AngularJS Essentials

The subtitle of Rodrigo Branas's AngularJS Essentials (Packt Publishing) is, "Design and construct reusable, maintainable, and modular web applications with AngularJS." This post is a review of the electronic (PDF) format of this book on AngularJS.

AngularJS Essentials consists of eight chapters and roughly 150 pages of substantive content. The Preface of AngularJS Essentials briefly describes the content of each of the book's eight chapters and recommends that readers have access to an IDE or text editor and a web browser to implement the examples included in the book.

Chapter 1: Getting Started with AngularJS

Chapter 1 of AngularJS Essentials devotes its first page to a history of HTML and web development that had led to frameworks such as AngularJS. Branas then describes AngularJS as "an open source, client-side JavaScript framework that promotes a high-productivity web development experience." I think Branas articulates well what AngularJS brings to web development when he writes that AngularJS is based on the idea that "declarative programming is the best choice to construct the user interface" and "imperative programming is much better and preferred to implement an application's business logic." AngularJS achieves this, Branas states, by extending HTML.

Chapter 1's introduction to AngularJS's architecture describes it as supporting applications implementing a model-view-whatever (MVW) pattern. The chapter briefly talks about the view, model, and controller/services/filters aspect of an AngularJS application. This chapter is also the first place I have seen POJO used as an identifying acronym for Plain Old JavaScript Object rather than for the more well-known use as Plain Old Java Object.

The first chapter of AngularJS Essentials introduces a parking lot application example that is used throughout the book. As part of this initial code listing, the author describes how to download regular or minified versions of AngularJS from the AngularJS site or from the Google Content Delivery Network (CDN).

AngularJS Essential's initial chapter concludes with a section briefly describing four potential styles of code organization ("most used and discussed styles in the JavaScript community") for an AngularJS application.

Chapter 2: Creating Reusable Components with Directives

The second chapter of AngularJS Essentials begins with a single page background discussion on the Document Object Model (DOM) and explains how AngularJS looks for "attributes known as directives" in the constructed DOM tree. The author then describes a directive as an "extension of the HTML vocabulary that allows us to create new behaviors."

After briefly describing which constructs in the DOM a directive can be applied to, Chapter 2 moves onto coverage of AngularJS built-in directives (ngApp, ngController, ngBind, ngBindHtml, ngRepeat, ngModel, ngClick, ngDisable, ngClass, ngOptions, ngStyle, ngShow/ngHide, ngIf, ngInclude) with one to three paragraphs and (in most cases) a code listing covering each built-in directive.

After a brief section on reorganizing the book's sample application, AngularJS Essentials covers custom directive creation. This coverage begins with a demonstration of creation of a Directive Definition Object and discussion of template, templateURL, replace, restrict, scope, transclude, link, require, and controller. The chapter references, but does not describe in any detail, the $compile service.

AngularJS Animation is the concluding topic of Chapter 2.

Chapter 3: Data Handling

The third chapter of AngularJS Essentials introduces "data handling using AngularJS" and specifically focuses on expressions, filters, and form validation. The author describes an AngularJS expression as "a simple piece of code that will be evaluated by the framework and can be written between double curly brackets."

An AngularJS filter is described as "the perfect solution to easily perform any data manipulation." The chapter briefly discusses several provided AngularJS filters (currency, date, number, filter, json, limitTo, lowercase, uppercase, and orderBy) used in conjunction with expressions and also briefly describes using filters generally with a controller. Chapter 3 also provides an overview of and simple examples of custom filter creation.

The section of Chapter 3 on form validation describes and illustrates use of several built-in directives commonly used with form validation and the input element (ng-required, ng-minlength, and ng-pattern). This portion of the third chapter also describes and illustrates used of objects $pristine, $dirty, and $error.

Chapter 4: Dependency Injection and Services

Chapter 4 of AngularJS Essentials begins with a discussion of AngularJS's support of dependency injection and provides an example and associated discussion to illustrate why array notation is often the preferred approach for AngularJS applications that are to be minified.

Chapter 4's coverage of "creating services" begins by defining a service as "a singleton object that has its life cycle controlled by the framework" that "can be used by any other component such as controllers, directives, filters, and even other services." This section examines creating of an AngularJS service from a factory and includes discussion on the Revealing Module Pattern and the Immediately-Invoked Function Expression pattern.

Chapter 4 concludes with coverage of AngularJS built-in services. The chapter includes this sentence that made me chuckle (I have added the emphasis in italics): "Introduced a long time ago by Roy Fielding, the REST method, or Representational State Transfer, has become one of the most adopted architecture styles in the last few years." Fielding's thesis on REST is dated 2000, which by some people's perspective certainly qualifies as "a long time ago." In addition to very brief coverage of REST, the chapter briefly describes HTTP (especially status codes), JSON, and Ajax. The chapter also illustrates applying an HTTP facade, HTTP headers, caching, and interceptors in an AngularJS application.

Chapter 4 devotes a section to single page application development with AngularJS's $route service and $location service. The chapter also introduces logging with the $log service and scheduling times for specific behaviors to occur with $timeout and $interval services. The "Asynchronous with a promise-deferred pattern" section of Chapter 4 describes use of AngularJS's deferred API and promise API.

Chapter 5: Scope

AngularJS Essentials's fifth chapter open by describing Scope as "an object that acts as a shared context between the view and the controller that allows these layers to exchange information related to the application model." Similarly, the AngularJS Developer Guide describes Scope as "the glue between application controller and the view." The author of AngularJS Essentials adds, "Both sides are kept synchronized along the way through a mechanism called two-way data binding."

The section of Chapter 5 on two-way data binding illustrates use of $apply and $watch. Another section of Chapter 5 covers best practices related to use of AngularJS scope. There is also very brief coverage of $rootScope.

The "Scope Broadcasting" section of Chapter 5 looks at use of the $broadcast and on functions.

Chapter 6: Modules

The focus of AngularJS Essentials's sixth chapter is on AngularJS modules. This relatively short chapter demonstrates how to create modules by creating three modules for the book's sample application. The chapter concludes with a references to some of the most popular publicly available AngularJS modules.

Chapter 7: Unit Testing

Chapter 7 of AngularJS Essentials focuses on unit testing AngularJS applications. As part of this coverage, it describes use of the ngMock, Jasmine framework, and Karma test runner. The chapter illustrates testing AngularJS Services, Controllers, Filters, and Directives. It also demonstrates mocking with AngularJS. In particular, use of $httpBackend to mock a backend for testing components that depend on the $http service is illustrated. I appreciated AngularJS Essentials dedicating a chapter to unit testing and mocking with AngularJS.

Chapter 8: Automating the Workflow

Grunt and Bower are the focus of the eighth and final chapter of AngularJS Essentials. This chapter provides step-by-step instructions with examples for creating a distribution package and executing the workflow with Grunt. It also demonstrates managing packages with Bower.

General Observations
  • As its title implies, AngularJS Essentials focuses on the more important aspects of AngularJS. Although some web development history and general web development techniques are very briefly mentioned, they are generally minimalist in nature and allow the focus to be directly on AngularJS. AngularJS Essentials is much shorter than other books on the subject (one is nearly 700 pages long), but also does not spend numerous pages covering CSS, HTML, JavaScript and other technologies that are well covered in other books and are often already familiar to developers learning AngularJS.
  • Code listings in AngularJS Essentials are black font on white background even in the electronic copy I reviewed and do not have line numbers. Several of the code listings use bold emphasis to highlight the specific concept being illustrated with the code listing.
  • AngularJS Essentials includes a couple graphics depicting described topics. These are attributed to the AngularJS documentation as the source of the graphics.
  • With some frameworks, libraries, or languages, a good book is important because of a lack of available resources on the subject. That is not the case with the wildly popular AngularJS that not only includes good standard documentation, but enjoys a large community of users generating useful resources. These numerous good resources covering AngularJS online include AngularJS documentation such as Official AngularJS Tutorial, AngularJS Developer Guide, and AngularJS API Reference, as well as third-party resources such as ng-newsletter articles, Thinkster/Egghead, StackOverflow, and Dan Wahlin's AngularJS posts.
  • Book reviews are by their nature opinionated and different books sometimes appeal to different people. Additional reviews of AngularJS Essentials can be found on Amazon.com and GoodReads.com. I think the composite impression one gets from reading the reviews as currently available on these sites provides a fair overall representation of AngularJS Essentials and its strengths and weaknesses.
Conclusion

AngularJS Essentials introduces the essentials of AngularJS and spends minimal time covering preliminary and historical details. As "essentials" implies, it is not intended to be a thorough reference. For those comfortable with learning from online tutorials and web sites, AngularJS Essentials is probably unnecessary in the well-documented world of AngularJS. However, I can recommend AngularJS Essentials for those looking for a good complement to the numerous useful online resources on learning AngularJS. AngularJS Essentials can provide a single source of quick structure for learning about AngularJS and how AngularJS can be used for web development. AngularJS Essentials is best suited for readers who already have basic familiarity with web development technologies such as HTML, JavaScript, and CSS, and want a book focused almost entirely on AngularJS and tools and techniques that can be used with AngularJS.