Friday, August 31, 2012

JavaOne 2012 Announcements and Blog Postings

In the blog post Where's Ed at JavaOne 2012, JavaServer Faces specification lead Ed Burns points out that "JavaOne 2012 is just 19 business days away!" In that post, he shows a screen snapshot of the Google Calendar representation of his schedule for JavaOne 2012. With a slightly more than 4 weeks to JavaOne 2012, the posts and announcements related to "the biggest geekfest this side of Betelgeuse Five" are becoming more frequent and I look at some of those here.

NoSQL and Data Grids

Manik Surtani is the one calling JavaOne 2012 "the biggest geekfest this side of Betelgeuse Five" in the post JavaOne 2012, here I come. In that post, he discusses his Birds of a Feather presentation BOF5866 - JSR 347, Data Grids, and NoSQL and his Conference Session CON5875 - Making Apps Scale with CDI and Data Grids.

JSF and Java EE

In the previously cited Ed Burns post, he covers what he is attending and supporting at JavaOne 2012. These include manning the Java EE booth and attending/giving several presentations related to JSF.

OpenJDK

In his burek for breakfast blog post JavaOne 2012: OpenJDK Edition, Dalibor Topic observes a sort of Moore's Law-inspired "robilad's Law": "the number of sessions on OpenJDK at JavaOne keeps approximately doubling since 2009." He lists 19 sessions at JavaOne 2012 associated with OpenJDK.

NetBeans

As I wrote in a recent blog post, the NetBeans Community Day at JavaOne 2012 Conference has been announced. A collection of JavaOne 2012 sessions focused on NetBeans is available in NetBeans at the JavaOne 2012 Conference.

Mark Stephens has also written about the NetBeans Day at JavaOne 2012. About NetBeans, Stephens writes, "NetBeans has seen a huge amount of development in the last 12 months. ... And NetBeans provides far more than just an IDE to write Java code."

Java Champions

Markus Eisele has written about the Java Champions at JavaOne 2012. He breaks down sessions presented by Java Champions and Java Champion Alumni (those now working for Oracle).

JavaOne 2012 Keynotes

The JavaOne 2012 Keynotes have been announced. The Java Strategy Keynote, "Oracle's Java engineering luminaries will demonstrate Oracle's continued commitment and positive stewardship of Java, as well as provide a glimpse of the future which showcases the vast opportunities that Java provides." The listed "luminaries" are Cameron Purdy, Nandini Ramani, Hasan Rizvi, Georges Saab, and Henrik Stahl.

The Technical Keynote, often my favorite of the JavaOne keynotes, at JavaOne 2012 has the objective of "offer[ing] an integrated look into how the entire range of the Java portfolio is evolving to offer developers a high-performance, standards-based platform to meet the challenges of the next generation of enterprise computing." It's listed speakers are Richard Bair, Terrence Barr, Arun Gupta, and Mark Reinhold.

The Strategy Keynote and Technical Keynote open JavaOne 2012, but the Java Community Keynote starts the final day of the conference. This keynote focuses on the Java community and "will showcase several Java community luminaries and their bodies of work." The two listed to introduce these "community luminaries" are Sharat Chander and Donald Smith.

Thursday, August 30, 2012

NetBeans Community Day at JavaOne 2012

Geertjan Wielenga invited me to participate in the panel at NetBeans Community Day at JavaOne 2012 and I'm looking forward to that. I'll be participating in the "Community Session: For You -- By You: Growing the NetBeans Community" (UGF10364) discussion that is scheduled for 30 minutes from 2 to 2:30 pm on 30 September 2012 (just before the conclusion/wrap-up session).

The main topic of conversation in the "Community Session: For You -- By You: Growing the NetBeans Community" session definitely interests me and can be summed up as a discussion on "the various ways to keep the NetBeans community vibrant and to leave your mark on the [NetBeans] project." Those who submit patches and create plug-ins for NetBeans are obviously very significant to its success. However, I like that this session recognizes that there are numerous other ways to contribute to open source including "blogging, setting up user groups, organizing seminars or creating YouTube videos, and more." The session description makes a very important observation: "Regardless of programming expertise, there's something for everyone to do." I'll be specifically talking about writing about NetBeans on this blog.

There are several sessions focused on NetBeans and the NetBeans community at NetBeans Community Day at JavaOne 2012. These include the NetBeans Community Keynote (UGF10353), NetBeans and Java EE (UGF10361), NetBeans and Java FX (UGF10362), NetBeans Platform (UGF10363), and the "Closing/NetBeans Awards/Community Recognition."

The NetBeans Community Day at JavaOne 2012 page also links to a page with sessions of JavaOne 2012 with a NetBeans focus or emphasis. This page, NetBeans at the JavaOne 2012 Conference, lists approximately 30 sessions with a NetBeans emphasis.

One of the hallmarks of a strong open source project is its community and I look forward to learning more from fellow members of the NetBeans community.

Wednesday, August 22, 2012

NetBeans 7.2: Generating (Introduce) Local Extensions

I have already blogged on two refactoring options NetBeans 7.2 provides in my aptly named posts NetBeans 7.2: Refactoring Parameterized Constructor As Builder and NetBeans 7.2: Refactoring Constructor As Static Factory. In this post, I look at another refactoring option introduced with NetBeans 7.2 that may be the most time-saving of them all: Introduce Local Extension.

Martin Fowler's Refactoring Home Page includes a "catalog of common refactorings", including the Introduce Local Extension refactoring. This particular refactoring is described on that page in this way (presenting the issue and the solution), "[Issue] A server class you are using needs several additional methods, but you can't modify the class. [Solution] Create a new class that contains these extra methods. Make this extension class a subclass or a wrapper of the original."

One of the new refactorings available with NetBeans 7.2 is "Introduce Local Extension" and it can be easily accessed by right-clicking on the class that one wants to provide a local extension for, selecting the "Refactor" option to expand that drop-down menu, and selecting "Introduce Local Extension." Alternatively, one can simply highlight the class of interest and use the keyboard: Alt+Shift+X. The former (using the drop-down menus in conjunction with right and then left mouse clicks) is depicted in the following screen snapshot after hovering over usage of the Java Date class in the source code (which is listed after the screen snapshot).

The above screen snapshot shows the result of right-clicking on the Date type used for instance variable date in the following source code listing.

Main.java (Bare Bones Class for Demonstration Purposes)
package dustin.examples;

import java.util.Date;

/**
 *
 * @author Dustin
 */
public class Main
{
   private Date date;

   /**
    * @param arguments the command line arguments
    */
   public static void main(final String[] arguments)
   {
   }
}

When the "Introduce Local Extension" refactoring is selected either by mouse clicking as shown above or through use of Alt+Shift+X, a wizard screen like the following is presented.

In this case, because I used Alt+Shift+X while hovering over the Date data type, the wizard is ready to help me generate a local extension of Java's Date. Note that if I had been hovering over most other parts of this class, the wizard would instead start helping me generate a local extension of my Main class (the class loaded in the NetBeans editor window).

In compliance with earlier cited definition of implementations of the "Introduce Local Extension" refactoring, there are two ways the NetBeans 7.2 wizard allows for this: wrapper (composition) and subtype (implementation inheritance). If the "Wrapper" option is selected (as is the case here), then there are three more "Equality" options to choose from ("Delegate", "Generate", or "Separate"). I'll return to these later. For now, let's assume that "Subtype" is selected. The next screen snapshot shows how the other three options are no longer applicable and are grayed-out.

If I click the "Refactor" button at this point, my new class will also be named Date but will be dustin.examples.Date rather than java.util.Date. In this case, to avoid any confusion, I'm going to change the generated class's name to DustinDate.

It's also worth noting that there is a checkbox that allows me to indicate whether I want to replace the original class (Date in this case) with the refactored local extension. In other words, I can have the refactoring not only create the subtype local extension, but I can have NetBeans replace my use of Date in the Main source code with my new class. This is shown in the next screen snapshot.

The next screen snapshot shows the results of clicking the "Refactor" button and having DustinDate created as a subtype of java.util.Date. Note that the use of Date in Main has been automatically updated to use the newly generated DustinDate, leaving an unused import of java.util.Date behind.

The next code listing is the source code of DustinDate, which was generated solely by NetBeans as a Subtype "Introduce to Local Extension" refactoring of java.util.Date.

DustinDate.java (NetBeans-generated via Subtype "Introduce Local Extension")
package dustin.examples;

import java.util.Date;

/**
 *
 * @author Dustin
 */
public class DustinDate extends Date
{
   /**
    * Allocates a <code>Date</code> object and initializes it so that
    * it represents the time at which it was allocated, measured to the
    * nearest millisecond.
    *
    * @see     java.lang.System#currentTimeMillis()
    */
   public DustinDate()
   {
      super();
   }

   /**
    * Allocates a <code>Date</code> object and initializes it to
    * represent the specified number of milliseconds since the
    * standard base time known as "the epoch", namely January 1,
    * 1970, 00:00:00 GMT.
    *
    * @param   date   the milliseconds since January 1, 1970, 00:00:00 GMT.
    * @see     java.lang.System#currentTimeMillis()
    */
   public DustinDate(long date)
   {
      super(date);
   }

   /**
    * Allocates a <code>Date</code> object and initializes it so that
    * it represents midnight, local time, at the beginning of the day
    * specified by the <code>year</code>, <code>month</code>, and
    * <code>date</code> arguments.
    *
    * @param   year    the year minus 1900.
    * @param   month   the month between 0-11.
    * @param   date    the day of the month between 1-31.
    * @see     java.util.Calendar
    * @deprecated As of JDK version 1.1,
    * replaced by <code>Calendar.set(year + 1900, month, date)</code>
    * or <code>GregorianCalendar(year + 1900, month, date)</code>.
    */
   public DustinDate(int year, int month, int date)
   {
      super(year, month, date);
   }

   /**
    * Allocates a <code>Date</code> object and initializes it so that
    * it represents the instant at the start of the minute specified by
    * the <code>year</code>, <code>month</code>, <code>date</code>,
    * <code>hrs</code>, and <code>min</code> arguments, in the local
    * time zone.
    *
    * @param   year    the year minus 1900.
    * @param   month   the month between 0-11.
    * @param   date    the day of the month between 1-31.
    * @param   hrs     the hours between 0-23.
    * @param   min     the minutes between 0-59.
    * @see     java.util.Calendar
    * @deprecated As of JDK version 1.1,
    * replaced by <code>Calendar.set(year + 1900, month, date,
    * hrs, min)</code> or <code>GregorianCalendar(year + 1900,
    * month, date, hrs, min)</code>.
    */
   public DustinDate(int year, int month, int date, int hrs, int min)
   {
      super(year, month, date, hrs, min);
   }

   /**
    * Allocates a <code>Date</code> object and initializes it so that
    * it represents the instant at the start of the second specified
    * by the <code>year</code>, <code>month</code>, <code>date</code>,
    * <code>hrs</code>, <code>min</code>, and <code>sec</code> arguments,
    * in the local time zone.
    *
    * @param   year    the year minus 1900.
    * @param   month   the month between 0-11.
    * @param   date    the day of the month between 1-31.
    * @param   hrs     the hours between 0-23.
    * @param   min     the minutes between 0-59.
    * @param   sec     the seconds between 0-59.
    * @see     java.util.Calendar
    * @deprecated As of JDK version 1.1,
    * replaced by <code>Calendar.set(year + 1900, month, date,
    * hrs, min, sec)</code> or <code>GregorianCalendar(year + 1900,
    * month, date, hrs, min, sec)</code>.
    */
   public DustinDate(int year, int month, int date, int hrs, int min, int sec)
   {
      super(year, month, date, hrs, min, sec);
   }

   /**
    * Allocates a <code>Date</code> object and initializes it so that
    * it represents the date and time indicated by the string
    * <code>s</code>, which is interpreted as if by the
    * {@link Date#parse} method.
    *
    * @param   s   a string representation of the date.
    * @see     java.text.DateFormat
    * @see     java.util.Date#parse(java.lang.String)
    * @deprecated As of JDK version 1.1,
    * replaced by <code>DateFormat.parse(String s)</code>.
    */
   public DustinDate(String s)
   {
      super(s);
   }
   
}

Because the "subtype" approach was employed, only constructors had to be generated by NetBeans to use the class being extended. The public or protected "get", "set", and any other methods of Date are automatically available to the extending DustinDate class. There are sometimes limitations and disadvantages of using implementation inheritance (it has even been called evil). One such disadvantage is the inability to extend final classes. To illustrate, I'm move to introducing a local extension of java.lang.String instead of Date.

Main.java (String Instance Variable Added)
package dustin.examples;

/**
 *
 * @author Dustin
 */
public class Main
{
   private DustinDate date;
   private String string;

   /**
    * @param arguments the command line arguments
    */
   public static void main(final String[] arguments)
   {
   }
}

Highlighting the String datatype and selecting the "Introduce Local Extension" refactoring leads to a wizard screen like that which follows.

I was pleasantly surprised to see that NetBeans 7.2 does not allow for the "Subtype" option in this case (String is final and cannot be extended). I must use "Wrapper," but can select one of the three "Equality" options for "Wrapper." I'm not going any further with String in this example, but the wizard will generate local extensions as wrappers using any of the three "Equality" options. In all cases, certain methods in the generated class need to be removed or altered for the new code to compile. A screen snapshot of using this with String using "Wrapper" and "Delegate" is shown next.

To more easily demonstrate NetBeans 7.2 refactoring local extension of wrapper type with the different options set, I had NetBeans generate most of the source code for a simple, all-new class called Person that is shown in the next code listing.

package dustin.examples;

import java.util.Objects;

/**
 *
 * @author Dustin
 */
public final class Person
{
   private String lastName;
   private String firstName;

   public Person(final String newLastName, final String newFirstName)
   {
      this.lastName = newLastName;
      this.firstName = newFirstName;
   }

   public String getLastName()
   {
      return this.lastName;
   }

   public void setLastName(String newLastName)
   {
      this.lastName = newLastName;
   }

   public String getFirstName()
   {
      return this.firstName;
   }

   public void setFirstName(String newFirstName)
   {
      this.firstName = newFirstName;
   }

   @Override
   public int hashCode()
   {
      int hash = 3;
      hash = 83 * hash + Objects.hashCode(this.lastName);
      hash = 83 * hash + Objects.hashCode(this.firstName);
      return hash;
   }

   @Override
   public boolean equals(Object obj)
   {
      if (obj == null)
      {
         return false;
      }
      if (getClass() != obj.getClass())
      {
         return false;
      }
      final Person other = (Person) obj;
      if (!Objects.equals(this.lastName, other.lastName))
      {
         return false;
      }
      if (!Objects.equals(this.firstName, other.firstName))
      {
         return false;
      }
      return true;
   }

   @Override
   public String toString()
   {
      return "Person{" + "lastName=" + lastName + ", firstName=" + firstName + '}';
   }

}

When using "Wrapper" type of local extension, there are three possible "Equality" selections. The next three screen snapshots show use of each with a class named appropriately for each. Note that I unchecked the option to change my use of Person to this new class because I wanted to use that original Person class to demonstrate refactoring for "Generate" and "Separate" equality settings in addition to "Delegate."

The three "Wrapper" generated classes (PersonDelegate, PersonGenerate, and PersonSeparate are identical except how they override Object.equals(Object) and Object.hashCode(). Given this, I first show the code listing for PersonDelegate and then show only the different equals implementations for the three approaches.

PersonDelegate.java (NetBeans-generated)
package dustin.examples;

/**
 *
 * @author Dustin
 */
public final class PersonDelegate
{
   private Person delegate;

   public PersonDelegate(Person delegate)
   {
      this.delegate = delegate;
   }

   public PersonDelegate(final String newLastName, final String newFirstName)
   {
      this.delegate = new Person(newLastName, newFirstName);
   }

   public String getLastName()
   {
      return delegate.getLastName();
   }

   public void setLastName(String newLastName)
   {
      delegate.setLastName(newLastName);
   }

   public String getFirstName() {
      return delegate.getFirstName();
   }

   public void setFirstName(String newFirstName)
   {
      delegate.setFirstName(newFirstName);
   }

   public String toString()
   {
      return delegate.toString();
   }

   public boolean equals(Object o)
   {
      Object target = o;
      if (o instanceof PersonDelegate)
      {
         target = ((PersonDelegate) o).delegate;
      }
      return this.delegate.equals(target);
   }

   public int hashCode()
   {
      return this.delegate.hashCode();
   }
}

As stated before the last code listing, only the implementation of "equals" and "hashCode" change depending on the equality setting chosen. To make the differences more obvious, only the equals and hashCode implementations of the three generated classes are shown next.

PersonDelegate.java equals Method - Delegate Equality
   public boolean equals(Object o)
   {
      Object target = o;
      if (o instanceof PersonDelegate)
      {
         target = ((PersonDelegate) o).delegate;
      }
      return this.delegate.equals(target);
   }

   public int hashCode()
   {
      return this.delegate.hashCode();
   }
PersonGenerate.java equals Method - Generate Equality
   @Override
   public boolean equals(Object obj)
   {
      if (obj == null)
      {
         return false;
      }
      if (getClass() != obj.getClass())
      {
         return false;
      }
      final PersonGenerate other = (PersonGenerate) obj;
      if (!Objects.equals(this.delegate, other.delegate))
      {
         return false;
      }
      return true;
   }

   @Override
   public int hashCode()
   {
      int hash = 5;
      hash = 43 * hash + Objects.hashCode(this.delegate);
      return hash;
   }
PersonSeparate.java equals Method - Separate Equality
   public boolean equalsPersonSeparate(PersonSeparate o)
   {
      return this.delegate.equals(o.delegate);
   }

   public boolean equals(Object o)
   {
      Object target = o;
      if (o instanceof PersonSeparate) {
         target = ((PersonSeparate) o).delegate;
      }
      return this.delegate.equals(target);
   }

   public int hashCode()
   {
      return this.delegate.hashCode();
   }

Looking at the different implementations of equals andhashCode helps us to see how they are different. The "Generate" equality approach generates the equals method for this new class using NetBeans's standard generation mechanism. Because I have the source set to JDK 1.7 in my NetBeans project, it takes advantage of the new (to Java 7) Objects class. The "Generate" approach also generates its hash code as if done for an all-new class rather than relying explicitly on the delegate's hash code. The other two "Equality" approaches ("Delegate" and "Separate") for generating a "Wrapper" both simply return the delegate's hash code.

The "Equality" setting for "wrapper" local extensions of Equality "Delegate" or "Separate" lead to the same implementations of equals and hashCode. The difference between the two is that "Separate" adds a new method (not part of the Objects contract) called equalsXXXXXXXX where the XXXXXXXX represents the generated class's name [so it is called equalsPersonSeparate(PersonSeparate) in this case]. Note that this new method does not accept an Object like equals, but expects its own type.

NetBeans 7.2's online help covers all of this in more detail under "Introduce Local Extension Dialog Box." The following is an excerpt from that section.

  • Equality. Select one of the following options to set how the equals and hashCode methods should be handled:
    • Delegate. Select to delegate to the equals and hashCode methods of the original class.
    • Generate. Select to generate new equals and hashCode methods using the IDE code generator.
    • Separate. Select to separate the equals method into two. A new method is added to check if the original class equals the extension class.

Before ending this post, I want to point out how easy it is to use NetBeans to identify differences between the generated files. The next screen snapshot shows what it looks like when one right-clicks on the tab in the source code editor for the PersonDelegate.java class/file. This brings up the drop-down menu that includes "Diff To ..." as an option.

I'm then presented with the option of the file to diff PersonDelegate to in either the same package (or browser allows arbitrary location to be specified) or opened in the editor window. In this case, I have selected PersonGenerate in the right side choices of files already open in the editor.

NetBeans displays the differences between PersonDelegate and PersonGenerate as shown in the next screen snapshot.

Most of the changes indicated by the colored bars on the far right are changes in class names. However, as the image above shows, the substantial changes are in the equality methods equals and hashCode.

The NetBeans diff shows that the primary difference between "Delegate" and "Separate" Equality in the corresponding generated Wrapper classes is the new method in the "Separate" class.

Finally, NetBeans shows that the differences between the "Generate" and "Separate" wrapper implementations.

Using NetBeans 7.2's "Wrapper" approach to the "Introduce Local Extension" refactoring provides an easy mechanism for employing the delegation pattern (as commonly understood these days rather than the more historically based use of it described in The Gang of Four is Wrong and You Don't Understand Delegation).

Conclusion

This post has focused on use of NetBeans 7.2's ability to automatically generate code based on the "Introduce Local Extension" refactoring using implementation inheritance ("Subtype") and composition ("Wrapper"). Along the way, the post also examined NetBeans's handy file differencing ("diff") capability.

Monday, August 20, 2012

JavaOne 2012: Difficult Decisions

It was recently announced that the JavaOne 2012 Schedule Builder is now available. I have signed up for my first cut at sessions that I will attend, but found myself experiencing the typical feelings of excitement and disappointment as I did so.

If I was forced to make a Top Ten list of the sessions I have been most interested in attending at JavaOne 2012, I would estimate that 3 to 4 of those are being offered at exactly the same time and there are a couple others in conflict with one another. On one hand, I find myself excited at the idea of attending certain presentations, but this is tempered at the disappointment realized when I see other presentations at the same time that I'll have to miss. There is undoubtedly an opportunity cost associated with seeing my chosen presentations.

One of the session slots that is most difficult for me to make a final decision regarding is the Monday (October 1) 10 am session. In that session, I must choose between "The Road to Lambda" (CON4862), "Concurrency without Pain in Pure Java" (CON3454), "Finding and Solving Java Deadlocks" (HOL6500), "Efficient Memory and Thread Management in Highly Parallel Applications" (CON4611), "Uncovering Hidden Power Tools in the JDK" (CON7059), "JSR 311: Constraint Programming API" (CON3255), "Lessons Learned: Use of Modern JVM Languages Besides Java" (CON2424), "Effective HATEOAS with JAX-RS" (CON3383), "How RESTful is Your REST?" (CON7573), "Make Your Clients Richer: JavaFX and the NetBeans Platform" (TUT4801), "Building Amazing Applications with JavaFX" (CON4606), and several other interesting sounding presentations. I'm currently leaning toward "The Road to Lambda" because I believe lambda expressions will "change everything" in how we think about and write Java and because Brian Goetz is its presenter.

Another example of being forced to make a very difficult decision is the 8:30 am slot on Tuesday (October 2). Among other great sessions, I am forced to choose between "Lambda: A Peek Under the Hood" (CON6080), "Introduction to the Play Framework" (CON3845), "Modern Software Development Antipatterns" (CON6152), "Kotlin: Practical Aspects of JVM Language Implementation" (CON5759), "The Evolution of Java Persistence" (CON6622), "New Image Operations in JavaFX" (CON4440), and "3-D Made Easy with JavaFX" (CON4513).

A final example that I'll cover here of the difficult decisions to be made comes from the 10 am hour on Wednesday (October 3). Among many great sessions available in that hour, I am having an especially difficult time making my mind up between "Unlocking the Java EE 6 Platform" (CON2987), "Innovating Testing Techniques with Bytecode Instrumentation" (CON3961), "Software Modularity: Paradoxes, Principles, and Architectures" (CON3992), "Design Patterns in Modern JVM Languages" (CON3455), "Developing Polyglot Persistence Applications" (CON4775), "JSR 353: Java API for JSON Processing" (CON3566), "Audio and Video Processing in JavaFX" (CON7146), "Do It Yourself: Custom JavaFX Controls" (CON2425), and "Building HTML5 Mobile Apps with Cloud Services" (CON11114). Fortunately, I don't have this same hour's Are Your Garbage Collection Logs Speaking to You on this difficult choices list because I attended it last year.

I listed a session code after each session name in the lists above. The session naming uses the following convention:

  • BOF - Birds-Of-a-Feather
  • CON - Conference Session
  • HOL - Hands-On Lab
  • KEY - Keynote Speech
  • TSF - Test Fest
  • TUT - Tutorial
  • UGF - User Group Forum

I focused on three hours of JavaOne 2012 that provide a set of presentations of such great interest that it is difficult to choose only one from the group. Although I used three for examples here, the truth is that just about every hour had at least two of my "must see" presentations and many had more than two in the same hour.

Even though I've made initial selections for which presentations I plan to attend, these will change between now and the conference and even during the conference. In fact, they already have changed some since the Content Catalog was released. In particular, my previously high level of interest in Mark Reinhold's "The Modular Java Platform and Project Jigsaw" (CON10844) is lessened significantly since learning that it is likely that we won't see Project Jigsaw until at least 2015 (Java 9). It is difficult to justify using a precious time slot on something that we likely won't see for at least 3 more years.

As I was browsing through the JavaOne 2012 presentations and the Oracle OpenWorld 2012 presentations, I noted that no JavaOne session had yet filled up, but several Oracle OpenWorld sessions are already full. I like that Schedule Builder tells you that it's full and tells you how many people are already on the waiting list. In one case, an Oracle OpenWorld session already had a waiting list of 43 people!

One of the things I don't like about Schedule Builder is that some of the pre-selected sessions that appeared on "My Schedule" keep reappearing every time I log into Schedule Builder even though I explicitly remove them every time I'm in the tool. I've stopped removing them for now, but would like to have them permanently removed so that it is more clear what I have scheduled each day.

I am trying to attend presentations representing a wide variety of topics at JavaOne 2012. I could attend a presentation on JavaFX in just about every session, but I hope to cover a much broader set of topics than just JavaFX. I'm trying to mix in some JavaFX, basic Java SE tooling, alternative JVM languages, and more. The biggest challenge is eliminating so many great sessions and trying to live with attending just one each hour.

Friday, August 17, 2012

NetBeans 7.2: Refactoring Constructor As Static Factory

In the post NetBeans 7.2: Refactoring Parameterized Constructor As Builder, I looked at how NetBeans 7.2 supports refactoring a constructor to a builder as described in Item 2 of the Second Edition of Effective Java. In this post, I look at how NetBeans 7.2 similarly supports refactoring constructors to factories as described in Item #1 of Effective Java.

I start with an Employee class that is largely the same as the one I used in my previous post on refactoring a constructor to a builder. There are some minor differences, the most significant being that the attributes of the version used here cannot be final as the factory initializer approach does not allow final class attributes because they are not set in the constructor with this approach.

Employee.java with Traditional Constructor
package dustin.examples;

/**
 * Simple employee class intended to illustrate NetBeans 7.2 and refactoring
 * constructor to use Factory initializer as discussed in Item #1 of Joshua
 * Bloch's <em>Effective Java</em>.
 * 
 * @author Dustin
 */
public class Employee 
{
   private String lastName;

   private String middleName;

   private String firstName;

   private long id;

   private int birthYear;

   private int birthMonth;

   private int birthDate;

   private int hireYear;

   private int hireMonth;

   private int hireDate;

   public Employee(
      final String newLastName,
      final String newMiddleName,
      final String newFirstName,
      final long newId,
      final int newBirthYear,
      final int newBirthMonth,
      final int newBirthDate,
      final int newHireYear,
      final int newHireMonth,
      final int newHireDate)
   {
      this.lastName = newLastName;
      this.middleName = newMiddleName;
      this.firstName = newFirstName;
      this.id = newId;
      this.birthYear = newBirthYear;
      this.birthMonth = newBirthMonth;
      this.birthDate = newBirthDate;
      this.hireYear = newHireYear;
      this.hireMonth = newHireMonth;
      this.hireDate = newHireDate;
   }

   @Override
   public String toString()
   {
      return  this.firstName + " " + this.middleName + " " + this.lastName
            + " with ID " + this.id;
   }
}

Right-clicking on the constructor of this class leads to the choices for refactoring including the highlighted choice to "Replace Constructor with Factory..."

When the "Refactor: Replace Constructor with Factory..." choice is selected, a window like that shown in the next screen snapshot appears. It has the name "create" for the factory method by default.

One of the advantages of these static initialization factories over constructors is the ability to name them as we like rather than always needing to use the class name. This can lead to them being more expressive and means potentially less reliance on overloading. The next screen snapshot shows my change of the name of the method to be generated.

When the above options are chosen, the class's source code is automatically changed to the code shown in the next code listing. Note that the constructor is changed from public to private and a new newInstance method is generated.

Refactored Employee.java (with White Space Adjustments Made Manually)
package dustin.examples;

/**
 * Simple employee class intended to illustrate NetBeans 7.2 and refactoring
 * constructor to use Factory initializer as discussed in Item #1 of Joshua
 * Bloch's <em>Effective Java</em>.
 * 
 * @author Dustin
 */
public class Employee 
{
   public static Employee newInstance(
      final String newLastName, final String newMiddleName,
      final String newFirstName, final long newId,
      final int newBirthYear, final int newBirthMonth,
      final int newBirthDate, final int newHireYear,
      final int newHireMonth, final int newHireDate)
   {
      return new Employee(newLastName, newMiddleName, newFirstName,
                          newId, newBirthYear, newBirthMonth, newBirthDate,
                          newHireYear, newHireMonth, newHireDate);
   }
   private final String lastName;

   private final String middleName;

   private final String firstName;

   private final long id;

   private final int birthYear;

   private final int birthMonth;

   private final int birthDate;

   private final int hireYear;

   private final int hireMonth;

   private final int hireDate;

   private Employee(
      final String newLastName,
      final String newMiddleName,
      final String newFirstName,
      final long newId,
      final int newBirthYear,
      final int newBirthMonth,
      final int newBirthDate,
      final int newHireYear,
      final int newHireMonth,
      final int newHireDate)
   {
      this.lastName = newLastName;
      this.middleName = newMiddleName;
      this.firstName = newFirstName;
      this.id = newId;
      this.birthYear = newBirthYear;
      this.birthMonth = newBirthMonth;
      this.birthDate = newBirthDate;
      this.hireYear = newHireYear;
      this.hireMonth = newHireMonth;
      this.hireDate = newHireDate;
   }

   @Override
   public String toString()
   {
      return  this.firstName + " " + this.middleName + " " + this.lastName
            + " with ID " + this.id;
   }
}

There are multiple advantages to using static initialization factory methods rather than constructors. These include the ability to provide different and more meaningful names that do not necessarily require overloading because they can be different. I like to name these methods in such a way that some of their parameters are implied, resulting in the need to provide fewer arguments to that method than would be necessary for a constructor.

Other advantages of the static factory approach of acquiring an instance and two disadvantages of this approach are discussed in Item #1 of Effective Java. That item concludes, "Often static factories are preferable, so avoid the reflex to provide public constructors without first considering static factories." NetBeans 7.2 makes it easy to see how a constructor can be refactored into a static factory and will even do the basic work for the developer.

Thursday, August 16, 2012

Recent Java News - Mid-August 2012

Oracle has released significant announcements regarding Java in recent weeks. I summarize some of these in this post.

Java SE 6 End of Life Extended to 2013

Henrik Stahl announced in the post Java 6 End of Public Updates extended to February 2013 that "the Oracle JDK 6 End of Public Updates will be extended through February, 2013." As Stahl states in that post, this is additional time beyond the previously announced extension from July 2012 to November 2012. The Oracle Java SE Support Roadmap has been updated to reflect this new extension.

Java SE 7 Update 6 Released

The 14 August 2012 Oracle Press Release titled Oracle Releases New Java Updates - Java SE 7 Update 6, JavaFX 2.2 and JavaFX Scene Builder 1.0 announces the release of Java SE 7 Update 6 bundled with JavaFX 2.2.

The Java 6 Update 7 Release Notes list the significant new features of this release: JDK and JRE Support for Mac OS X, JDK for Linux on ARM, JavaFX SDK and JavaFX Runtime included in JDK 7u6 and JRE 7u6, Java Access Bridge included in JRE 7u6, Alternative Hash Function, and Changes to Security Warning Dialog Box for Trusted Signed and Self Signed Applications.

JavaOne 2012 Schedule Builder Goes Live

Tori Wieldt's post JavaOne Schedule Builder Live announces that Schedule Builder is now live and available for registered JavaOne 2012 attendees.

Oracle and Fortress

Although not technically Java-related, I found it interesting to read that Oracle is throwing in the towel on development of the Fortran-inspired programming language Fortress.

Friday, August 10, 2012

NetBeans 7.2: Refactoring Parameterized Constructor As Builder

Shortly after the Second Edition of Josh Bloch's Effective Java was released, I borrowed a colleague's copy to browse it and consider purchasing a copy of my own despite already owning a copy of the first edition. It did not take me long to realize that the Second Edition was worth purchasing. In particular, the usefulness of the first new item in the Second Edition (Item #2 "Consider a builder when faced with many constructor parameters") struck me. This item addressed many issues I had run into during my Java development in a nice fashion. In this post, I look at the approach described in that chapter and look at how NetBeans 7.2 provides refactoring support for this approach.

As outlined in Item #2 of the Second Edition of Effective Java, there are several disadvantages to using constructors with large parameter lists. To help illustrate, I include a code listing below.

Employee.java
package dustin.examples;

/**
 * Simple employee class intended to illustrate NetBeans 7.2 and refactoring
 * constructor to use Builder pattern as discussed in Item #2 of the Second
 * Edition of Joshua Bloch's <em>Effective Java</em>.
 * 
 * @author Dustin
 */
public class Employee 
{
   private final String lastName;

   private final String middleName;

   private final String firstName;

   private final long id;

   private final int birthYear;

   private final int birthMonth;

   private final int birthDate;

   private final int hireYear;

   private final int hireMonth;

   private final int hireDate;

   public Employee(
      final String newLastName,
      final String newMiddleName,
      final String newFirstName,
      final long newId,
      final int newBirthYear,
      final int newBirthMonth,
      final int newBirthDate,
      final int newHireYear,
      final int newHireMonth,
      final int newHireDate)
   {
      this.lastName = newLastName;
      this.middleName = newMiddleName;
      this.firstName = newFirstName;
      this.id = newId;
      this.birthYear = newBirthYear;
      this.birthMonth = newBirthMonth;
      this.birthDate = newBirthDate;
      this.hireYear = newHireYear;
      this.hireMonth = newHireMonth;
      this.hireDate = newHireDate;
   }
}

Employee's parameterized constructor includes numerous parameters and this presents a challenge to clients of this class that need to create a new instance of it. This particular constructor is particularly tricky for clients because it has three consecutive String parameters and numerous consecutive int parameters. It is all too easy for a client to mix up the order of these same-typed parameters in the invocation.

Suppose that business logic is such that an employee should be instantiable with only a last name, first name, and ID provided. In other words, suppose that all attributes of the class are optional except for the three just mentioned. In such a case, with only a constructor like that one above, the client would need to pass null for the middle name String and zeroes or some other number without meaning. The numeric types could be reference types rather than primitives, but the clients would still need to pass null for each optional argument.

One might argue that a three-argument constructor could accepting the three required attributes' values could be supplied and then appropriate set methods could be invoked to set each optional attribute. However, this approach has drawbacks. For one, it makes it easier for the client to accidentally instantiate an instance with a bad or partial state. In some cases, it is not desirable to change the state of the object after instantiation, but the presence of the set methods make it more mutable than desired. Indiscriminate supplying of set methods has several drawbacks in the world of concurrency and object-oriented interfaces.

An elegant approach that allows a client to only supply optional parameters that are meaningful without supplying otherwise unnecessary set methods is the Builder pattern. NetBeans 7.2 makes it easy to refactor the constructor with the long parameter list in the above example to take advantage of an instance of Builder. The next screen snapshot shows how I can use NetBeans 7.2 to accomplish this by hovering over the parameterized constructor, right-clicking on it, and selecting the option "Replace constructor with Builder...".

When this option is selected a popup similar to that shown in the next screen snapshot appears.

The refactoring tool only allows parameters passed to the constructor being refactored to be set in the builder. I can check the boxes of the optional attributes. When I make an attribute optional without supplying a default value, a warning appears as shown in the next screen snapshot.

If I supply default values (null for the String and zero for the integers that should never be zero for valid values), the warnings go away.

It is worth pointing out here that the refactor tool allows the refactor to continue when only warnings (no errors) are present. An error might be caused, for example, by declaring a package and class name of the builder to be generated with a name used by an existing class.

The "Preview" button can be clicked to see what the class would look like without actually creating the class file. When the "Refactor" button is clicked, a new Java class with the package and class name indicated in the "Builder Class Name" text field is created. The result in this case is shown in the next screen snapshot with the generated code listed in a listing following the snapshot.

NetBeans 7.2-Generated EmployeeBuilder.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dustin.examples;


public class EmployeeBuilder
{
   private String newLastName;
   private String newMiddleName = null;
   private String newFirstName;
   private long newId;
   private int newBirthYear = 0;
   private int newBirthMonth = 0;
   private int newBirthDate = 0;
   private int newHireYear = 0;
   private int newHireMonth = 0;
   private int newHireDate = 0;

   public EmployeeBuilder()
   {
   }

   public EmployeeBuilder setNewLastName(String newLastName)
   {
      this.newLastName = newLastName;
      return this;
   }

   public EmployeeBuilder setNewMiddleName(String newMiddleName)
   {
      this.newMiddleName = newMiddleName;
      return this;
   }

   public EmployeeBuilder setNewFirstName(String newFirstName)
   {
      this.newFirstName = newFirstName;
      return this;
   }

   public EmployeeBuilder setNewId(long newId)
   {
      this.newId = newId;
      return this;
   }

   public EmployeeBuilder setNewBirthYear(int newBirthYear)
   {
      this.newBirthYear = newBirthYear;
      return this;
   }

   public EmployeeBuilder setNewBirthMonth(int newBirthMonth)
   {
      this.newBirthMonth = newBirthMonth;
      return this;
   }

   public EmployeeBuilder setNewBirthDate(int newBirthDate)
   {
      this.newBirthDate = newBirthDate;
      return this;
   }

   public EmployeeBuilder setNewHireYear(int newHireYear)
   {
      this.newHireYear = newHireYear;
      return this;
   }

   public EmployeeBuilder setNewHireMonth(int newHireMonth)
   {
      this.newHireMonth = newHireMonth;
      return this;
   }

   public EmployeeBuilder setNewHireDate(int newHireDate)
   {
      this.newHireDate = newHireDate;
      return this;
   }

   public Employee createEmployee()
   {
      return new Employee(newLastName, newMiddleName, newFirstName, newId, newBirthYear, newBirthMonth, newBirthDate, newHireYear, newHireMonth, newHireDate);
   }
   
}

As the screen snapshot and code listing above indicate, NetBeans 7.2 generated a builder based on the constructor. This was easily done, but there are a few things I don't like about it as much as the builders I have generated by hand. For the builders I have built by hand, I have chosen to have required attributes be part of the builder's constructor so that they must be supplied (I had expected this to happen for the parameters that I did not check the box for optional on). This is shown in the next code listing, which is an adaptation of the generated code shown above. The only thing changed from above is the builder's constructor. It now takes parameters for the Employee class's required attributes.

Adapted EmployeeBuilder.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dustin.examples;


public class EmployeeBuilder
{
   private String newLastName;
   private String newMiddleName = null;
   private String newFirstName;
   private long newId;
   private int newBirthYear = 0;
   private int newBirthMonth = 0;
   private int newBirthDate = 0;
   private int newHireYear = 0;
   private int newHireMonth = 0;
   private int newHireDate = 0;

   public EmployeeBuilder(
      final String newBldrLastName, final String newBldrFirstName, final String newBldrMiddleName)
   {
      this.newLastName = newBldrLastName;
      this.newFirstName = newBldrFirstName;
      this.newMiddleName = newBldrMiddleName;
   }

   public EmployeeBuilder setNewLastName(String newLastName)
   {
      this.newLastName = newLastName;
      return this;
   }

   public EmployeeBuilder setNewMiddleName(String newMiddleName)
   {
      this.newMiddleName = newMiddleName;
      return this;
   }

   public EmployeeBuilder setNewFirstName(String newFirstName)
   {
      this.newFirstName = newFirstName;
      return this;
   }

   public EmployeeBuilder setNewId(long newId)
   {
      this.newId = newId;
      return this;
   }

   public EmployeeBuilder setNewBirthYear(int newBirthYear)
   {
      this.newBirthYear = newBirthYear;
      return this;
   }

   public EmployeeBuilder setNewBirthMonth(int newBirthMonth)
   {
      this.newBirthMonth = newBirthMonth;
      return this;
   }

   public EmployeeBuilder setNewBirthDate(int newBirthDate)
   {
      this.newBirthDate = newBirthDate;
      return this;
   }

   public EmployeeBuilder setNewHireYear(int newHireYear)
   {
      this.newHireYear = newHireYear;
      return this;
   }

   public EmployeeBuilder setNewHireMonth(int newHireMonth)
   {
      this.newHireMonth = newHireMonth;
      return this;
   }

   public EmployeeBuilder setNewHireDate(int newHireDate)
   {
      this.newHireDate = newHireDate;
      return this;
   }

   public Employee createEmployee()
   {
      return new Employee(newLastName, newMiddleName, newFirstName, newId, newBirthYear, newBirthMonth, newBirthDate, newHireYear, newHireMonth, newHireDate);
   }
   
}

The code used to call the adapted builder shown in the last code listing is exemplified in the following code listing. This code listing demonstrates how readable ("fluent" in the more trendy vernacular) the client code is with the builder and demonstrates that the object is never in a partial or inconsistent state.

package dustin.examples;

import java.util.Calendar;

/**
 * Example calling adapted employee builder to get an instance of employee.
 *
 * @author Dustin
 */
public class Main
{
   public static void main(final String[] arguments)
   {
      final Employee employee =
         new EmployeeBuilder("Coyote", "Wile", "E.")
              .setNewBirthMonth(Calendar.SEPTEMBER)
              .setNewBirthDate(17)
              .setNewBirthYear(1949)
              .createEmployee();
   }
}

The most significant drawbacks to the builder implementation are potential performance impacts of extra object instantiation (probably not an issue for most Java applications) and the extra code verbosity.

Although I don't show it here, the other thing I like to do with my builder implementations is to include them as nested classes in the class they build. This is how the code example in the second item of the Second Edition of Effective Java implements it, but I don't see anyway in NetBeans 7.2 to generate the builder as a nested class rather than as a standalone class.

Although the NetBeans 7.2-generated builder class is not quite what I have written by hand, it is pretty close and really easy to use. It makes it easy to use an existing parameterized constructor to quickly generate a largely equivalent builder class. Although I have to edit the generated class slightly to get my preferred implementation, it still saves me significant time. Furthermore, this is another example of where an IDE's code generation capabilities help a developer to see how a particular paradigm or pattern is implemented.

Thursday, August 9, 2012

Book Review: Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications

As I described in an earlier post, Packt Publishing invited me to review the book Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications. In this post, I provide a review of the strengths and weaknesses of this book along with an idea of the type of person who would gain the most from reading this book. Before doing that, I summarize the recipes covered in each chapter.

Chapter 1

The first chapter of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications covers portions of the Java EE specification that are changing names or being removed from the Java EE specification altogether before moving onto brief introductions of new things being added to the Java EE specification. The chapter covers the "pruning" of "old APIs" such as JAX-RPC (renamed JAX-WS), JAXR, entity EJB (replaced by JPA), JSR 77, and JSR 88.

New Java EE 6 features introduced briefly in this first chapter include JSR 175 and JSR 250 annotations, JSR 299 and JSR 330 Context Dependency Injection (CDI), EJB 3.1, Java Persistence API 2.0, JAX-RS 1.1, Servlet 3.0, JavaServer Faces 2.0, Bean Validation 1.0, and Profiles.

Chapter 2

The second chapter of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications provides more detailed coverage of JPA 2.0 introduced in the initial chapter. The chapter begins with more coverage of @CollectionTable and includes a couple recipes with quite a bit of code to demonstrate new JPA 2.0 functionality.

This second chapter also discusses profiling with JPA 2.0 and provides recipes using YourKit and IntelliJ IDE. This was probably my least favorite chapter in the book.

Chapter 3

Chapter 3 of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications is on "Security" and begins with an introduction of basic security-related terminology. The chapter also introduces GlassFish and Tomcat before covering authentication with Java EE. The chapter then moves onto authorization and specifying security settings via annotations. Significant attention is aid in this chapter to signing Java JARs before inclusion of a recipe on configuring Linux firewalls used with Tomcat.

The third chapter concludes with recipes on obfuscating and minimizing Java compiled code. I really like the example Groovy/Gradle script and equivalent Ant XML that show how to create an obfuscated JAR using yGuard. Another recipe demonstrates use of Yahoo's YUI Compressor to minimize JavaScript and CSS code size.

Chapter 4

Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications's fourth chapter is on "Enterprise Testing Strategies," a topic that can be a little tricky at times. The first recipe in this chapter demonstrates "how to attach a remote debugger process to a Maven build running outside of the IDE." This is another recipe that features Gradle in part of its example.

Another recipe in Chapter 4 examines use of DBUnit and JUnit with Enterprise Java applications. Each tool is introduced and I like the simple graphic that cleanly articulates the JUnit lifecycle.

The fourth chapter's examples build on examples introduced in the second chapter. The author starts by covering static imports of JUnit and Hamcrest classes.

Another recipe of Chapter 4 focuses on mocking and highlights use of Mockito and PowerMock. For the recipe on "testing HTTP endpoints," Selenium is the tool of choice. soapUI is used for the recipe on testing web services (JAX-WS and JAX-RS). The final recipe of the chapter builds on this and provides another great example of using Groovy in the development process.

Chapter 5

The fifth chapter of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications is on "Extending Enterprise Applications" and talks about use of Groovy, Jython, Scala, AspectJ, and "two standard Java EE 6 extensions" (CDI Decorators and Interceptors) with enterprise Java.

The recipe in this chapter on Groovy explains the scope of coverage: "we will not cover all the inner-workings of the Groovy language and all the benefits from this JVM language, but we will cover how to integrate Groovy into a new or existing Enterprise Application and how to use Groovy for unit testing." The Groovy recipe introduces GMaven and shows use of Groovy with Maven, Ant, and unit testing Java applications.

A recipe in Chapter 6 centered on Jython demonstrates "using Jython to create a Java Servlet and access Java classes from within the Jython script dynamically." The recipe focused on Scala, like the recipes in the same chapter on Groovy and Jython, starts with use of Maven. The recipe on Scala demonstrates using Scala for Java unit testing.

The recipe "Weaving AspectJ advice into Enterprise Applications" begins with descriptions of key aspect-oriented programming terms such as aspects, cross-cutting concerns, advice, pointcut, weaving, and joinpoint. This recipe briefly shows how to use AspectJ at compilation time. The next recipe, "Weaving AspectJ advice into existing libraries," demonstrates using AspectJ with pre-existing libraries and further discusses the AspectJ compiler (ajc).

The recipe "Adding advice with CDI Decorators" starts with discussion of interceptors in general before focusing on CDI decorators specifically. The recipe contrasts the common differentiating attributes of decorators versus interceptors: decorators implement business logic and intercept specific business methods while interceptors are more general and address cross-cutting concerns rather than implement specific business logic. CDI interceptors are the focus of the final recipe of the fifth chapter. Both CDI-related recipes of the fifth chapter include examples using JBoss's JSR 299 implementation (Weld).

Chapter 6

Chapter 6 of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications covers "recipes that touch on the issues, considerations, and options related to extending enterprise development efforts into mobile application development," but also starts with an important caveat: "With the mobile device and tool landscape changing daily, it will be difficult to cover certain specific implementations, but we can cover many of the options available and considerations that can be assessed when integrating mobile applications into an enterprise project."

As advertised, the sixth chapter provides an overview of considerations to be made in the mobile space and lists examples of and pros and cons of using "mobile-web framework projects", "native code generators", and "native web runtimes." The chapter then moves onto discussion of considerations to be made related to native mobile application development with focus on development, deployment, and distribution with Apple and Android.

Two recipes of the sixth chapter list some tools for mobile device application design and testing and there is an extensive recipe on "setting up a local Apache environment" with Tomcat using XAMPP. Chapter 6 concludes with a recipe on "native SDK development considerations" with focus on available IDEs and build management tools.

As the author pointed out early in the chapter, this sixth chapter is, in general, a higher level of explanation than is commonly associated with recipes. Software development recipe books and cookbooks tend to be example-focused and tend to be heavy on code with explanations of that code snippet. Many of the recipes in this same book follow that pattern, but Chapter 6 is definitely more text than code.

Chapter 7

The seventh chapter of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications returns to core Java EE coverage and focuses on deployment and configuration. This chapter is one of my favorites, which is not too surprising given that it includes Groovy and JMX in practical examples. The chapter starts with a JMX introduction and the statement, "The JMX recipes in this chapter are based on JDK 1.6 and VisualVM 1.3.3."

The first recipe of this chapter covers "how to implement application configuration with property files using the Contexts and Dependency Injection (CDI) APIs." The recipe looks at issues associated with using property files for application configuration and looks at how CDI can be used with properties to deal with some of these issues. Another recipe in the seventh chapter highlights advantages of using Groovy for configuration rather than properties files and provides an example using Groovy's ConfigSlurper in Java.

Chapter 7 contains four recipes focused on using JMX in conjunction with Tomcat and GlassFish with and without SSL. These recipes introduce JConsole and VisualVM (including debugging VisualVM connection issues) and demonstrate in detail how to use Tomcat and GlassFish with JMX on different operating systems. One recipe even introduces the Windows tool cacls.

One of Chapter 7's recipes focuses on JRebel and uses this in conjunction with IntelliJ IDEA IDE.

Chapter 8

The final chapter of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications is on "performance and debugging" and is one of my other favorite chapters in the book. VisualVM is heavily covered again in recipes in this chapter, this time for profiling memory consumption in conjunction with the VisualGC VisualVM plugin and for remote profiling with jstatd.

The relatively well-known netstat tool gets covered in a Chapter 8 recipe. This recipe introduces the basics of processes and threads and contrasts the two and briefly summarizes socket states as preparation for the remainder of the recipe. The recipe concludes with coverage of other "netstat tools" NetStat Agent and TCPView.

Chapter 8 includes additional recipes that demonstrate "how to leverage TCPMon to debug TCP connections", demonstrate "how to install and configure Munin to monitor computer resources and a Tomcat application server," and demonstrate how to "leverage HTTP Debugger to trace client and server-based requests and responses."

Overall Impressions

As with all books, Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications has its pros and cons. As is also the case with most books, certain attributes of this book are pros to one reader and cons to a different reader. Given this, I'll cite things I liked and did not like about the book, but I understand that some of the things I like will not be to others' liking and some of the things I did not like might be welcome to other readers.

  • Not Your Typical Java EE Book - Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications is not the typical Java EE book. Although it does provide coverage of core new features of Java EE 6 in its early chapters, its focus is generally on use of tools and scripts to do exactly what the title describes: secure, tune, and extend Java EE-based enterprise applications. This is not the book one learns about the basics of EJBs, servlets, JavaServer Faces, JMS, or other Java EE technologies. In my opinion, this is a good thing and is what perhaps separates this book most from other Java EE 6 books.
  • Name Dropping - One of my favorite aspects of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications is its broad coverage of interesting and useful tools used in Enterprise Java development and production. This book does more than just drop the names. It provides summaries of what each tool offers and shows realistic and meaningful uses of that tool for improving the enterprise development experience. I tried to reference several of this book's referenced tools in this post to provide a flavor of its breadth of coverage of tools. The recipes each end with a list of references for additional information on the tools discussed in that recipe.
  • Use of Groovy - Although Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications features numerous tools and techniques, I think its coverage of Groovy is particularly well done and provides solid examples of how Groovy can improve the Java developer's ability to write scripts.
  • Different Operating Systems - I liked that this book generally focuses on solutions and tools that apply to many major operating systems and often provides specific details on use of a recipe on each of these different operating systems.
  • Lots of Pictures - In keeping with something I've come to expect in Packt Publishing books, this book continues the trend of featuring numerous screen snapshots to illustrate points.
  • Repetition - Several closely related recipes include similar or even identical text to one another. For the typical reader of a cookbook or recipe-oriented book, this is welcome because it can be distracting and even irritating to be referred to a separate recipe if one is only interested in how to accomplish a single recipe. I read the book from cover to cover rather than focusing on particular individual recipes as they interested me and so was more cognizant of the occasional repeated text.
  • Different Backgrounds - One of the challenges facing the author of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications must have been addressing his audience at the appropriate level. I think most chapters and recipes deliver well on this, providing enough information to introduce the reader to useful tools and approaches for working with Java EE applications and only relying only minimal knowledge of Java EE. The one exception to this is Chapter 2, which I feel assumes quite a bit of JPA-specific knowledge to be appreciated. The good news is that, in the tradition of recipe-oriented books, understanding of Chapter 2 is generally (with a few exceptions) not required for appreciating the other chapters. Chapters 7 and 8, on the other hand, might be as useful to Java EE developers as they are to Java EE developers.
  • Typos, Editing, and Formatting - I reviewed an electronic (PDF) version of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications and do not know if the printed version has the same typo and editing issues that I occasionally saw in the PDF version. At times, the PDF version of the book feels like it missed a final edit. In general, these are only slightly distracting and rarely provide any significant distraction.
The Target Audience

The "Who this book is for" section of the Preface of Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications states, "This book is aimed at Java developers and programmers who want to secure, tune, and extend their Java EE applications." This articulates well the primary audience for this book, though I think that Java SE developers could benefit from several of the recipes and chapters in this book as well.

The "What you need for this book" section of the Preface also says of the book's audience, "The recipes in this book are of an intermediate to advance nature, so a good understanding of Java is required." The book definitely assumes basic familiarity with Java (SE and EE), but some recipes require this experience more than others.

Idea Generation

For me, the best thing about Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications is its introduction to a wide variety of topics, tools, and ideas. Even recipes that I might have no direct use for at this time provide value because they demonstrate use of tools for accomplishing various administrative tasks. I found myself thinking of related but different uses for some of the tools and approaches discussed in this book.

Related Links (External Sites)

The following are some other sources of information about the book Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications.

Wednesday, August 8, 2012

A Slicker Typesafe Stack: Q&A with Martin Odersky

Typesafe announced this morning that the Scala Language Integrated Connection Kit (Slick) has been added to its Typesafe Stack. Slick has been mentioned in Michael Azoff's Typesafe roadmap indicates the maturing of Scala and the ScalaDays 2012 presentation SLICK: Scala Language Integrated Connection Kit provides significant details about Slick as well as code examples of how to use it.

The "About" portion of the Slick web page states the following:

Slick is a modern database query and access library for Scala. It allows you to work with stored data almost as if you were using Scala collections while at the same time giving you full control over when a database access happens and which data is transferred. You can write your database queries in Scala instead of SQL, thus profiting from the static checking, compile-time safety and compositionality of Scala. Slick features an extensible query compiler which can generate code for different backends.

I had the opportunity to pose some questions to Scala creator and Typesafe co-founder Martin Odersky about Slick. It is exciting to think about what Slick offers based on Martin's answers (posted next) and based on the material available on the Slick website (tweeted by Martin yesterday).

Slick Q&A with Martin Odersky

Q: Is Slick open source?

A: Yes, Slick is an open source project.

Q: What is the licensing for Slick?

A: Slick is distributed under a BSD-style license. The license was chosen to be the same as Scala's to keep the hurdle for adoption low.

Q: Can Slick be used with databases other than those explicitly supported as listed in the press release (such as Oracle)? and Q: What steps must be taken to use a database other than those listed?

A: Yes. The session handling and "plain SQL" layer is database-independent. Compiling Scala code to SQL requires a Slick driver for the target DB. There is a BasicDriver implementation based on standard SQL which should support the majority of standard features of many database systems. Since all databases in practice deviate more or less from the SQL standard, custom driver implementations will be needed to make use of all features.

Q: Is Slick extensible to make use of an unsupported database transparent to the developer if certain extensions are implemented (in other words, can the community add support for other databases)?

A: User code can be written in a database-independent way, depending only on an abstract profile which is implemented by different database drivers. New drivers can easily be implemented by 3rd parties as separate projects.

Q: Are there plans in the future to support other databases out-of-the-box?

A: At the moment Slick is limited to JDBC-based SQL databases. We are planning to support different kinds of NoSQL databases with non-JDBC drivers in the future as part of the Slick core release. Drivers for high-end commercial database systems will be available as a commercial add-on from Typesafe.

Q: Is a JDBC driver required to use Slick or does the Slick driver for a particular database handle it completely?

A: All database connections are made through JDBC using the standard JDBC drivers for the respective database systems. This makes it easy to integrate Slick into existing platforms, e.g. for using container-managed data sources or sessions in JEE environments.

Q: Does Slick make Java and Scala ORM solutions unnecessary?

A: Slick is not a drop-in replacement for an ORM but we believe it can provide superior results in many cases. Traditional ORM solutions focus on making the database disappear from your application, giving you the illusion of working with a network of mutable objects in memory. This comes with the usual problems of mutable state in general, plus additional challenges caused by the large impedance mismatch between the relational and object-oriented worlds. Slick makes heavy use of immutable data structures and concepts from functional programming which are much closer to SQL, thus staying clear of most impedance mismatch problems while providing much of the power of an ORM.

Conclusion

There seem to be many great ideas incorporated into Slick and I think it may be the feature that finally motivates me to make time to try out Scala. Thanks to Martin for responding to my questions and to Laura Masterson for arranging for the opportunity to have my questions about Slick answered.