Thursday, November 28, 2013

Uncompressing 7-Zip Files with Groovy and 7-Zip-JBinding

This post demonstrates a Groovy script for uncompressing files with the 7-Zip archive format. The two primary objectives of this post are to demonstrate uncompressing 7-Zip files with Groovy and the handy 7-Zip-JBinding and to call out and demonstrate some key characteristics of Groovy as a scripting language.

The 7-Zip page describes 7-Zip as "a file archiver with a high compression ratio." The page further adds, "7-Zip is open source software. Most of the source code is under the GNU LGPL license." More license information in available on the site along with information on the 7z format ("LZMA is default and general compression method of 7z format").

The 7-Zip page describes it as "a Java wrapper for 7-Zip C++ library" that "allows extraction of many archive formats using a very fast native library directly from Java through JNI." The 7z format is based on "LZMA and LZMA2 compression." Although there is an LZMA SDK available, it is easier to use the open source (SourceForge) 7-Zip-JBinding project when manipulating 7-Zip files with Java.

A good example of using Java with 7-Zip-JBinding to uncompress 7z files is available in the StackOverflow thread Decompress files with .7z extension in java. Dark Knight's response indicates how to use Java with 7-Zip-JBinding to uncompress a 7z file. I adapt Dark Knight's Java code into a Groovy script in this post.

To demonstrate the adapted Groovy code for uncompressing 7z files, I first need a 7z file that I can extract contents from. The next series of screen snapshots show me using Windows 7-Zip installed on my laptop to compress the six PDFs available under the Guava Downloads page into a single 7z file called Guava.7z.

Six Guava PDFs Sitting in a Folder
Contents Selected and Right-Click Menu to Compress to 7z Format
Guava.7z Compressed Archive File Created

With a 7z file in place, I now turn to the adapted Groovy script that will extract the contents of this Guava.7z file. As mentioned previously, this Groovy script is an adaptation of the Java code provided by Dark Knight on a StackOverflow thread.

unzip7z.groovy
//
// This Groovy script is adapted from Java code provided at
// http://stackoverflow.com/a/19403933


import static java.lang.System.err as error

import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.RandomAccessFile
import java.util.Arrays

import net.sf.sevenzipjbinding.ExtractOperationResult
import net.sf.sevenzipjbinding.ISequentialOutStream
import net.sf.sevenzipjbinding.ISevenZipInArchive
import net.sf.sevenzipjbinding.SevenZip
import net.sf.sevenzipjbinding.SevenZipException
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream
import net.sf.sevenzipjbinding.simple.ISimpleInArchive
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem


if (args.length < 1)
{
   println "USAGE:  unzip7z.groovy <fileToUnzip>.7z\n"
   System.exit(-1)
}

def fileToUnzip = args[0]

try
{
   RandomAccessFile randomAccessFile = new RandomAccessFile(fileToUnzip, "r")
   ISevenZipInArchive inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile))

   ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface()

   println "${'Hash'.center(10)}|${'Size'.center(12)}|${'Filename'.center(10)}"
   println "${'-'.multiply(10)}+${'-'.multiply(12)}+${'-'.multiply(10)}"

   simpleInArchive.getArchiveItems().each
   { item ->
      final int[] hash = new int[1]
      if (!item.isFolder())
      {
         final long[] sizeArray = new long[1]
         ExtractOperationResult result = item.extractSlow(
            new ISequentialOutStream()
            {
               public int write(byte[] data) throws SevenZipException
               {
                  //Write to file
                  try
                  {
                     File file = new File(item.getPath())
                     file.getParentFile()?.mkdirs()
                     FileOutputStream fos = new FileOutputStream(file)
                     fos.write(data)
                     fos.close()
                  }
                  catch (Exception e)
                  {
                     printExceptionStackTrace("Unable to write file", e)
                  }

                  hash[0] ^= Arrays.hashCode(data) // Consume data
                  sizeArray[0] += data.length
                  return data.length // Return amount of consumed data
               }
            })
         if (result == ExtractOperationResult.OK)
         {
            println(String.format("%9X | %10s | %s", 
               hash[0], sizeArray[0], item.getPath()))
         }
         else
         {
            error.println("Error extracting item: " + result)
         }
      }
   }
}
catch (Exception e)
{
   printExceptionStackTrace("Error occurs", e)
   System.exit(1)
}
finally
{
   if (inArchive != null)
   {
      try
      {
         inArchive.close()
      }
      catch (SevenZipException e)
      {
         printExceptionStackTrace("Error closing archive", e)
      }
   }
   if (randomAccessFile != null)
   {
      try
      {
         randomAccessFile.close()
      }
      catch (IOException e)
      {
         printExceptionStackTrace("Error closing file", e)
      }
   }
}

/**
 * Prints the stack trace of the provided exception to standard error without
 * Groovy meta data trace elements.
 *
 * @param contextMessage String message to precede stack trace and provide context.
 * @param exceptionToBePrinted Exception whose Groovy-less stack trace should
 *    be printed to standard error.
 * @return Exception derived from the provided Exception but without Groovy
 *    meta data calls.
 */
def Exception printExceptionStackTrace(
   final String contextMessage, final Exception exceptionToBePrinted)
{
   error.print "${contextMessage}: ${org.codehaus.groovy.runtime.StackTraceUtils.sanitize(exceptionToBePrinted).printStackTrace()}"
}

In my adaptation of the Java code into the Groovy script shown above, I left most of the exception handling in place. Although Groovy allows exceptions to be ignored whether they are checked or unchecked, I wanted to maintain this handling in this case to make sure resources are closed properly and that appropriate error messages are presented to users of the script.

One thing I did change was to make all of the output that is error-related be printed to standard error rather than to standard output. This required a few changes. First, I used Groovy's capability to rename something that is statically imported (see my related post Groovier Static Imports) to reference "java.lang.System.err" as "error" so that I could simply use "error" as a handle in the script rather than needing to use "System.err" to access standard error for output.

Because Throwable.printStackTrace() already writes to standard error rather than standard output, I just used it directly. However, I placed calls to it in a new method that would first run StackTraceUtils.sanitize(Throwable) to remove Groovy-specific calls associated with Groovy's runtime dynamic capabilities from the stack trace.

There were some other minor changes to the script as part of making it Groovier. I used Groovy's iteration on the items in the archive file rather than the Java for loop, removed semicolons at the ends of statements, used Groovy's String GDK extension for more controlled output reporting [to automatically center titles and to multiply a given character by the appropriate number of times it needs to exist], and took advantage of Groovy's implicit inclusion of args to add a check to ensure file for extraction was provided to the script.

With the file to be extracted in place and the Groovy script to do the extracting ready, it is time to extract the contents of the Guava.7z file I demonstrated generating earlier in this post. The following command will run the script and places the appropriate 7-Zip-JBinding JAR files on the classpath.

groovy -classpath "C:/sevenzipjbinding/lib/sevenzipjbinding.jar;C:/sevenzipjbinding/lib/sevenzipjbinding-Windows-x86.jar" unzip7z.groovy C:\Users\Dustin\Downloads\Guava\Guava.7z 

Before showing the output of running the above script against the indicated Guava.7z file, it is important to note the error message that will occur if the native operating system specific 7-Zip-JBinding JAR (sevenzipjbinding-Windows-x86.jar in my laptop's case) is not included on the classpath of the script.

As the last screen snapshot indicates, neglecting to include the native JAR on the classpath leads to the error message: "Error occurs: java.lang.RuntimeException: SevenZipJBinding couldn't be initialized automaticly using initialization from platform depended JAR and the default temporary directory. Please, make sure the correct 'sevenzipjbinding-.jar' file is in the class path or consider initializing SevenZipJBinding manualy using one of the offered initialization methods: 'net.sf.sevenzipjbinding.SevenZip.init*()'"

Although I simply added C:/sevenzipjbinding/lib/sevenzipjbinding-Windows-x86.jar to my script's classpath to make it work on this laptop, a more robust script might detect the operating system and apply the appropriate JAR to the classpath for that operating system. The 7-Zip-JBinding Download page features multiple platform-specific downloads (including platform-specific JARs) such as sevenzipjbinding-4.65-1.06-rc-extr-only-Windows-amd64.zip, sevenzipjbinding-4.65-1.06-rc-extr-only-Mac-x86_64.zip, sevenzipjbinding-4.65-1.06-rc-extr-only-Mac-i386.zip, and sevenzipjbinding-4.65-1.06-rc-extr-only-Linux-i386.zip.

Once the native 7-Zip-JBinding JAR is included on the classpath along with the core sevenzipjbinding.jar JAR, the script runs beautifully as shown in the next screen snapshot.

The script extracts the contents of the 7z file into the same working directory as the Groovy script. A further enhancement would be to modify the script to accept a directory to which to write the extracted files or might write them to the same directory as the 7z archive file by default instead. Use of Groovy's built-in CLIBuilder support could also improve the script.

Groovy is my preferred language of choice when scripting something that makes use of the JVM and/or of Java libraries and frameworks. Writing the script that is the subject of this post has been another reminder of that.

Happy Thanksgiving!

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.

Monday, November 25, 2013

Book Review: Developing Windows Store Apps with HTML5 and JavaScript

I recently accepted Packt Publishing's invitation to review Rami Sarieddine's book Developing Windows Store Apps with HTML5 and JavaScript. The Preface of the book describes the book as "a practical, hands-on guide that covers the basic and important features of a Windows Store app along with code examples that will show you how to develop these features." The Preface adds that the book is for "all developers who want to start creating apps for Windows 8" and for "everyone who wants to learn the basics of developing a Windows Store app."

Chapter 1: HTML5 Structure

Chapter 1 of Developing Windows Store Apps with HTML5 and JavaScript introduces "HTML5 structural elements" (semantic elements, media elements, form elements, custom data attributes) supported in the Windows 8 environment.

The section on semantic elements covers elements such as <header>, <nav>, <article>, and <address>. The section on media elements provides detailed coverage of the <video> and <audio> elements.

The section on form elements discusses the "new values for the type attribute are introduced to the <input> element." A table is used to display the various types (examples include tel, email, and search) with descriptions. There is discussion on these input types along with how to add validation to the input types.

Most of this initial chapter of Developing Windows Store Apps with HTML5 and JavaScript covers general HTML5 functionality, but there are a few references to items specific to Windows 8. For example, the last new material before the first chapter's Summary is on "using the Windows Library for JavaScript (WinJS) to achieve more advanced binding of data to HTML elements."

Chapter 2: Styling with CSS3

Like the first chapter, Chapter 2 focuses mostly on a general web concept, in this case Cascading Style Sheets (CSS). Sarieddine states that CSS is responsible for "defining the layout, the positioning, and the styling" of HTML elements such as those covered in the first chapter.

In introducing CSS, the second chapter of Developing Windows Store Apps with HTML5 and JavaScript provides an overview of four standard selectors (asterisk, ID, class, and element), attribute selectors (including prefix, suffix, substring [AKA contains], hyphen, and whitespace), combinator selectors (including descendant, child/direct, adjacent sibling, and general sibling), pseudo-class selectors, and pseudo-element selectors.

Chapter 2 does cover some Microsoft/Windows-specific items. Specifically, the chapter introduces the Grid layout and the Flexbox layout. The author explains that these have -ms prefixes because they are currently specific to Microsoft (Windows 8/Internet Explorer 10), but that they are moving through the W3C standardization process.

The second chapter of Developing Windows Store Apps with HTML5 and JavaScript covers animation with CSS and introduces CSS transforms before concluding with brief discussion of CSS media queries.

Chapter 3: JavaScript for Windows Apps

Developing Windows Store Apps with HTML5 and JavaScript's third chapter covers "features provided by the Windows Library for JavaScript (the WinJS library) that has been introduced by Microsoft to provide access to Windows Runtime for the Windows Store apps using JavaScript." The delivered implication of this is that this is the first chapter of the book that is heavily focused on developing specifically Windows Store Apps.

Sarieddine covers use of Promise objects to implement asynchronous programming in JavaScript's single-threaded environment rather than using callback functions directly. The author also covers use of the WinJS.Utilities namespace wrappers of document.querySelector and querySelectorAll. Coverage of the WinJS.xhr function begins with the description of it being a wrapper to "calls to XMLHttpRequest in a Promise object."

Chapter 3 concludes with a discussion of "standard built-in HTML controls" as well as WinJS-provided controls "new and feature-rich controls designed for Windows Store apps using JavaScript." This discussion includes how WinJS-provided controls are handled differently in terms of code than standard HTML controls.

This third chapter is heavily WinJS-oriented. It also includes the first non-trivial discussion and illustrations related to use of Visual Studio, a subject receiving even more focus in the fourth chapter.

Chapter 4: Developing Apps with JavaScript

Chapter 4 of Developing Windows Store Apps with HTML5 and JavaScript is intended to help the reader "get started with developing a Windows 8 app using JavaScript." It was early in this chapter that I learned that Windows Store apps run only on Windows 8. The chapter discusses two approaches for acquiring Windows 8 and downloading necessary development tools such as Visual Studio Express 2012 for Windows 8 from Windows Dev Center. The chapter discusses how to obtain or renew a free developer license via Visual Studio.

The fourth chapter also discusses languages other than HTML5/CSS3 that can be used to develop Windows Store apps. It then moves onto covering development using Visual Studio templates. Several pages are devoted to discussion on using these standard templates and there are several illustrations of applying Visual Studio in this development.

Chapter 5: Binding Data to the App

The fifth chapter of Developing Windows Store Apps with HTML5 and JavaScript discusses "how to implement data binding from different data sources to the elements in the app." As part of this discussion of data binding, the chapter covers the WinJS.Binding namespace ("Windows library for JavaScript binding") for binding styles and data to HTML elements. Examples in this section illustrate updating of HTML elements' values and styles.

Interestingly, it is in this fifth chapter that the author points out that "Windows 8 JavaScript has native support for JSON." The chapter's examples also discuss and illustrate use of Windows.Storage.

Chapter 5's coverage of formatting and displaying data introduces "the most famous controls" of ListView and FlipView and then focuses on ListView. This portion of the chapter then moves on to illustrate use of WinJS templates (WinJS.Binding.Template). The final topic of Chapter 5 is sorting and filtering data and more example code is used here for illustration.

Chapter 6: Making the App Responsive

Chapter 6 focuses on how to make a Windows 8 application "responsive so that it handles screen sizes and view state changes and responds to zooming in and out." The chapter begins by introducing view states: full screen landscape, full screen portrait, snapped view, and filled view. The chapter discusses snapping (required for apps to support) and rotation (recommended for apps to support). It then moves onto covering use of "CSS media queries" and "JavaScript layout change events."

Chapter 6 also introduces semantic zoom, described on the Guidelines for Semantic Zoom page as "a touch-optimized technique used by Windows Store apps in Windows 8 for presenting and navigating large sets of related data or content within a single view." Sarieddine describes semantic zoom as a technique "used by Windows Store apps for presenting—in a single view—two levels of detail for large sets of related content while providing quicker navigation." There are several pages of code illustrations and explanatory text on incorporating semantic zoom in the Windows 8 application.

Chapter 7: Making the App Live with Tiles and Notifications

The seventh chapter of Developing Windows Store Apps with HTML5 and JavaScript introduces the concept of Windows 8 tiles. The chapter discusses the app tile ("a core part of your app") and live tiles ("shows the best of what's happening inside the app"). Windows 8 Badges and Notifications are also covered in this chapter.

Chapter 8: Signing Users In

Chapter 8 is focused on authentication in a Windows 8 app. The chapter discusses use of the Windows 8 SDK and "a set of APIs" that "allow Windows Store apps to enable single sign on with Microsoft accounts and to integrate with info in Microsoft SkyDrive, Outlook.com, and Windows Live Messenger."

The eighth chapter's coverage includes discussion of open standards supported by Live Connect: OAuth 2.0, REST, and JSON. The chapter also covers reserving an app name on the Windows store, working with Visual Studio 2012 for Windows 8, and working with Live SDK downloads.

Chapter 9: Adding Menus and Commands

Chapter 9 of Developing Windows Store Apps with HTML5 and JavaScript focuses on adding menus and commands to the app bar. This coverage includes discussion on where to place the app bar and how the UX guidelines recommend placing the app bar on the bottom because the navigation bar goes on top of a Windows 8 app.

Chapter 10: Packaging and Publishing

Developing Windows Store Apps with HTML5 and JavaScript's tenth chapter introduces the Windows Store and likens it to "a huge shopping mall" in which the reader's new app would be like "a small shop in that mall." The author states that the Windows Store Dashboard is "the place where you submit the app, pave its way to the market, and monitor how it is doing there."

The first step in the process of submitting a Windows app to the Windows Store for certification was covered in the chapter on authentication (Chapter 8) and this chapter picks up where that left off. Steps covered in this chapter include providing the application name, setting the "selling details," adding services, setting age and rating certifications, specifying cryptography and encryption used by the app, uploading app packages generated with Visual Studio, adding app description and other metadata about the app, and notes to testers evaluating app for Windows Store.

The chapter moves from coverage of the Windows App submission process using Windows Store Dashboard to using Visual Studio's embedded Windows Store support. Of particular interest in this section is coverage of how to use Visual Studio to package a Windows 8 app so that the "package is consistent with all the app-specific and developer-specific details that the Store requires."

The majority of this chapter's examples depend on having a Windows Store developer account. The chapter also includes a reference to a page on avoiding common certification failures.

Chapter 11: Developing Apps with XAML

All of the earlier chapters of Developing Windows Store Apps with HTML5 and JavaScript focused on developing Windows Store apps with traditional web development technologies HTML, CSS, and JavaScript, but the final chapter looks at using different platforms for creating Windows Store Apps. Although most of this chapter looks at developing Windows Store apps using the alternate development platform of XAML/C#, there is brief discussion of more general considerations when using alternate platforms for developing Windows Store apps. The chapter specifically mentions multiple approaches using C++ and C# to develop Windows Store apps.

Using Extensible Application Markup Language (XAML) for developing Windows 8 applications is described similar to the approach used for JavaScript as discussed earlier in this book. One of the examples demonstrates using Visual Studio standard Windows Store App templates such as Blank App (XAML), Grid App (XAML), and Split App (XAML). The chapter dives into basics of developing an XAML-based Windows Store app and introduces XAML based on HTML and XML concepts and differences.

The final chapter has a "Summary" section, but the final paragraph of that chapter is actually a summary of the entire book. A potential purchaser of this book could read this final paragraph on page 158 to get a quick overview of what the book covers.

Targeted Audience

Developing Windows Store Apps with HTML5 and JavaScript is well-titled in terms of describing what the book is about. The book clearly fulfills its objective of demonstrating how to use HTML5 and JavaScript to develop Windows Store Apps. Although the book does briefly discuss other technologies and platforms for building Windows Store Apps, these discussions are very brief and and mostly references rather than detailed descriptions.

The reader most likely to benefit from this book is a developer interested in applying HTML, JavaScript, and CSS to develop Windows Store apps. The book does provide introductory material on these technologies for those not familiar with them, but at least some minor HTML/CSS/JavaScript experience would be a benefit for the reader.

This book would obviously not be a good fit for someone wishing to learn how to develop apps for any environment other than the Windows Store and it would only be of marginal benefit to readers wanting to develop Windows Store apps with technologies other than HTML, JavaScript, and CSS.

Conclusion

Developing Windows Store Apps with HTML5 and JavaScript delivers on what its title advertises. It provides as comprehensive of an introduction as roughly 160 pages allows to developing and deploying Windows Store apps using JavaScript and HTML. Packt Publishing provided me a PDF for this review and one of the advantages of the electronic form is the numerous screen snapshots of Windows 8 apps and Visual Studio are in full color. I especially liked that little time was wasted in the book and it efficiently covered quite a bit of ground in a relatively short number of pages.

Additional Information

Here are some additional references related to this book including other reviews of this book.

Monday, November 18, 2013

Native Java Packaging with NetBeans 7.4

One of the new features of NetBeans 7.4 that made the "NetBeans 74 NewAndNoteworthy" page is "Native Packaging," which is described on that page as "JavaSE projects now support creation of native bundles taking use of the native packaging technology provided by JavaFX."

I will use a very simple example to demonstrate this native packaging functionality in NetBeans 7.4. The next code listing is for this enhanced Hello World example.

EnhancedHelloWorld.java
package dustin.examples;

import static java.lang.System.out;

/**
 * Slightly enhanced "Hello World" example.
 * 
 * @author Dustin
 */
public class EnhancedHelloWorld
{
   /**
    * Main function.
    * 
    * @param args the command line arguments; name being addressed, if any.
    */
   public static void main(String[] args)
   {
      final String addresseeName = args.length > 0 ? args[0] : "World";
      out.println("Hello, " + addresseeName);
   }
}

The next image shows this same code in the NetBeans 7.4 source code editor.

To use the Native Packaging feature, I can right-click on the project and select Properties as shown in the next image.

Clicking on "Properties" leads to the appearance of the "Project Properties" window. This window, as shown in the next screen snapshot, allows the developer to expand the "Build", select "Deployment", and check the box next to the label "Enable Native Packaging Actions in Project Menu." Selecting this option configures NetBeans 7.4 to support native packaging for that NetBeans project.

With NetBeans 7.4 native packaging enabled, I can now right-click on the project and have a new option called "Package as" available. When I select that "Package as" option, I see the following choices: "All Artifacts", "All Installers", "Image Only", "EXE Installer", and "MSI Installer". Note that my NetBeans 7.4 IDE is running on a Windows machine, so the EXE and MSI installers make sense. Sections 6.4.1 and 6.4.2 of the Deploying JavaFX Applications document cover the EXE and MSI installer packages respectively.

When I select EXE as the installer package, I see it processing the native packaging per the message in the bottom right corner of the IDE. This is shown in the next screen snapshot.

The first time I tried this, I ran into an error reported by NetBeans with the message: "JavaFX native packager requires external Inno Setup 5+ tools installed and included on PATH to create EXE installer. See http://www.jrsoftware.org/". Going to the referenced Jordan Russell Software site allows me to download Inno Setup 5.5.4 (isetup-5.5.4.exe). In my case, I downloaded the self-extracting EXE and ran it. I then added the full path to the directory into which Inno Setup 5.5.4 was installed to my PATH environmental variable and restarted NetBeans 7.4.

With Inno Setup installed on my system, the Inno Setup 5.5.4 installer compiler runs when NetBeans's EXE native packaging is selected. When NetBeans and Inno Setup complete, a relatively large EXE file exists in the project's directory as shown in the next screen snapshot.

I can run this executable, of course, by simply typing its name at the command prompt. The next screen snapshot demonstrates that running this executable leads to a popup window requesting approval to install the Java application.

When the "Install" button is clicked, the installation begins and this is demonstrated in the next screen snapshot.

The executable installer installs the Java application as another executable. In this case, this application is installed in C:\Users\Dustin\AppData\Local\EnhancedHelloWorld as shown in the next screen snapshot.

The generated directory shown in the screen snapshot above includes a "runtime" directory with the necessary JRE to run this application even on machines that don't have a JRE installed. The Java application itself is stored as a JAR in the "app" directory. Both of these subdirectories are shown in the next two screen snapshots.

The generated directory includes two .exe files. One is EnhancedHelloWorld.exe, which is the Java application executable. The other .exe file is unins000.exe. Running this latter .exe file cleanly uninstalls the application from the computer.

The next screen snapshot shows that I am able to start the application from my Window Start in addition to clicking on the generated executable file.

Although the Java code sample I started with can be built as an executable application using NetBeans 7.4 as shown in this post, it is far more interesting to use a Java application with a user interface because standard output is not written anywhere visible to the user. For example, one could build an executable application with NetBeans 7.4 based on the Java class HelloWorldSwing.

My examples in this post have been entirely Java SE (no JavaFX), but have taken advantage of NetBeans 7.4's support of native packaging via mechanisms generated for JavaFX deployments. Therefore it's not surprising that the JavaFX documentation on Self-Contained Application Packaging is useful for understanding the options available. Native packaging with NetBeans 7.4 is also demonstrated in Native Packaging in NetBeans IDE.

Addendum

Based on feedback comments to this post, I have added this clarifying section.

The primary use of native packaging would be for situations where one wants to make a Java-based application available to customers who might not have an appropriate Java Runtime Environment installed on their machines. This approach "packages" the application with the necessary runtime support classes. As grelf.net points out, it is easier if all the customers already have appropriate versions of the JRE installed on their machines. In that case, the deployment might be as simple as delivering an executable JAR.

The feedback from iyoskusmana reminded me of two other points I wanted to make clearer. The example Java code I started my post with works in the sense of giving me something to build and deploy from NetBeans 7.4. The downside of that particular code, however, is that its standard output does not get written to anywhere the user of the application can see. Although it does run, there is not much evidence of that. This is why it is better to use a Swing-based GUI application such as the suggested HelloWorldSwing.

It is also important to set the class whose "main" function should be used by the natively packaged application in the Project Properties "Run" section (MainClass field). In other words, treat the native application deployment like you would an executable JAR and specify to NetBeans which of the classes in that JAR is the one whose "main" function should be executed when the application is executed.