Sunday, August 28, 2011

Article: Java 7: Worth A Hard Look

I just finished reading a half-page article called "Java 7: Worth A Hard Look" by Andrew Binstock in InformationWeek. If you want to read the article you can download the pdf from InformationWeek. Their site has a broken link to the article.

In the article he briefly mentions a couple of the new items in Java 7 such as NIO.2, fork-join framework, and invokedynamic.

There is no significant meat to the article, but he misses a few of the really cool language improvements: diamond operator, try with resources, and multi-catch. These are changes from project coin which most developers can take advantage of immediately.

The diamond <> operator simplifies the use of generics by reducing code duplication.

Map<String,Map<String,String>> map = new HashMap<>();


Try with resources allows us to use critical system resources like I/O and not have to worry about closing them. The system will handle it for us. All of the Java I/O libraries have been retrofitted with the AutoClosable interface.

The multi-catch allows us to catch multiple exceptions and handle them in a common way.

try {
...
} catch (NullPointerException | ArithmeticException e) {
log(e);
}

This is a lot simpler, and makes the code cleaner and easier to read.

The other items like fork-join, and invokedynamic are much more specific (niche). If you are not using other JVM languages, invokedynamic is not of interest to you. Fork-Join is (in my opinion) more of an academic problem. I have not seen a real good use case example.

NIO.2 is really cool, but it will require a lot more work on the part of the developer to take advantage of. The FileSystem API is awesome for anyone who needs to take advantage of manipulating files on a system. However, it will take some re-work to bring into existing code.


Thursday, August 25, 2011

Type Safe Collection Conversion

I was reading a great article by a friend of mine Checking an Unchecked Cast in Java 5 or Later where he refers to some of the rules from Josh Bloch about making type safe conversions. It was interesting. Glen also provides a good code example of how he does a type safe conversion. I thought I would provide a couple of examples using a List converter. I have heard that a number of folks do not like returning <T> from a method which has a collection associated with it. However like any tool, it is up to the person using it not to hurt themselves (i.e. a screwdriver is not a hammer). In this example I have a couple of methods which do type safe conversion of a List of something. We need to know in advance what we expect that something to be. This is just one example of how you can do a conversion on a collection. I would like to note that there are methods on the Collections class which returns a checked collection. This ensures that any object added to a collection is of particular type. As the API notes, this is for the addition of classes after the collection has been turned into a checked collection. It does not check the Collection for previously added objects. The code below checks all of the object types before doing the conversion, and fails if it encounters the wrong type.

Wednesday, August 24, 2011

JSF Trick of the Day: @ManagedProperty set using GET request

JSF 2.0 GET request
This tip is designed to show how you can use plain HTML form, or parametrized strings to pass data to a JSF page, or backing bean.

This provides some additional flexibility when working with mixed environments. JSF 2.0 supports GET requests, but this is a simple alternative for mixed environments.

Jacob Hookam published an article called JSF 1.2 RI - Bean Instantiation and Annotations which mentions the use of <managed-property> to do this with JSF 1.2 in 2007.

This is a complete example using JSF 2.0 and annotations.

We use the @ManagedProperty annotation which replaces the faces-config.xml equivalent. We set the value of the managed property using the param implicit request object. This allows very simple substitutions for values.

In this example, we use a Facelets file which consists mostly of HTML with some JSF markup. The file contains a plain HTML form which is posting back to the same page with parameters which the user can enter. Alternatively, there is a hyperlink which accomplishes the same thing. Once the values are entered, or the hyperlink is clicked, the values will appear on the page.

The source code for the NetBeans 7.0.1 project can be found here: JSFGet.zip

Here is an alternate version which was confirmed on GlassFish 2.1.1: JSF2GETGF2.zip  

JSF 1.2 Example: This example was done using JSF 1.2 for those who may need it. It uses a faces-config.xml to configure the <managed-property/>: JSF12GET.zip

index.xhtml



Index.java


Tuesday, August 23, 2011

@PostConstruct Example Using Stateless Session Beans and CDI

There was a question posed about using @PostConstruct to initialize JSF fields from a database on the NetBeans Java EE Forum. I thought I would write a quick example of how to use @PostConstruct to initialize a list of customers, and select one to display.

This example also includes using a stateless session bean directly with the @Named annotation from Context and Dependency Injection (CDI).

All of this was accomplished using NetBeans 7.0.1.

Index.java



A copy of the project can be downloaded here: postconstruct.zip

Sunday, August 14, 2011

Book Review: NetBeans IDE 7 Cookbook

I have had the opportunity to review NetBeans IDE 7 Cookbook by Rhawi Dantas from Packt Publishing. Let me start by saying that the title is misleading. Normally I expect a cookbook to provide solutions to common problems, or situations which are not normally covered elsewhere, e.g. documentation, or tutorials. This book should have been called NetBeans IDE 7 Tutorial.

Now that I have gotten past the title, I should be frank and say that the book is targeted for new NetBeans users. If you have been using NetBeans for more than a year, this book is not for you. Advanced NetBeans users will likely find very little information in the book for which they are not currently aware.

If you are a new NetBeans user, the book provides a good tutorial on the features in NetBeans. The "recipes" are very topical though. The NetBeans project has a number of great tutorials developed from members of the NetBeans team, and community contributors. A majority of these tutorials cover more details than are in the book. This is not to say that the book is bad, or poor, but does not cover the topics in as great details as some of the more targeted tutorials available.

I would give the book 3/5 stars for new NetBeans users, and 2/5 stars for advanced users. I gave the book a dual rating since I believe that there is valuable information for new NetBeans users, but it is less valuable for advanced users.

Chapter Details

The book is divided into twelve chapters. It covers basic IDE usage to source control, and is logically divided into chapters based on functionality from basic IDE functions to technologies.

Chapter 1 - NetBeans Head First

This chapter has the obligatory "Hello World" application example, and demonstrates some basic features of the IDE. The examples show how to create projects, import projects from Eclipse, and use Apache Maven projects.

The chapter mentions that the Apache Ant scripts allow the project to be run outside of NetBeans. It also notes that Apache Maven applications are first class projects that the IDE can use without modification.

Chapter 2 - Basic IDE Usage

This chapter covers basic IDE functionality. The discussion is a good place to start for any new NetBeans developer. It is well done, and gives a good overview of the basic functionality.

Conditional breakpoints (page 31) are mentioned, but does not cover how to configure, or use them. I was disappointed This is a really nice feature which developers should take advantage of.

Chapter 3 - Designing Desktop GUI Applications

This chapter starts off with as the author notes:
One of the greatest strengths of NetBeans is the powerful Swing GUI Builder.
I couldn't agree more. The Swing GUI building functionality has always been strong, and with each release it gets better.

The SwingX project mentioned on page 38 is actually at Swing Component Extensions. The book has a link to the old project location on Java.net.

On page 56, there is mention of properties one of which is Code. This was an opportunity for the author to provide a real cookbook answer. Alas, it was not meant to be. The author glances over the pre- and post- configuration parameters without an explanation.

The author also comments on the following page that JavaDB is not production quality. I would respectfully differ. Before becoming Apache Derby (JavaDB), it was a database product called Cloudscape from a company by the same name. It provides a great enterprise quality database which has a number of capabilities found in databases 10x its size. I think that the comment is completely without fact, or merit.

Page 62, has a set of typographical errors on item #2. It should read as follows:

Image image = resourceMap.getImageIcon("window.icon").getImage();

The version on the page has guillemets instead of quotes.

Page 67 Step #4 should use EclipseLink instead of TopLink which is its replacement.

EclipseLink JPA 2.0

Chapter 4 - JDBC and NetBeans

This chapter spends a majority of its space dedicated to setting up databases like MySQL, PostgreSQL, Apache Derby, and Oracle. The remainder of the chapter has an explanation of the SQL Editor. It is a nice introduction for beginners, and could serve as a primer.

Page 81, uses the ojdbc14.jar. This is incorrect. It should use ojdbc6.jar.
 

Chapter 5 - Building Web Applications

This is my personal bread and butter. Swing applications are no where near the usage levels as Web based development using Java Enterprise Edition (EE).

One of my favorite things about this chapter is an example of writing a JUnit test for EJBs located on Page 105. This example is very well done, and demonstrates the power of using the embedded container.

The biggest disappointment is the coverage of JSF which is lackluster. There is more coverage of Apache Struts than JSF which is part of the EE specification.

Page 96 under WEB-INF mentions that the web.xml file is located here. This file is optional in Java EE 6, and may not be present. Also the picture shows a beans.xml file which is only present if Context and Dependency Injection (CDI) is being used. It is also optional.

Page 111 has a JSF coding error on &amp;lt;h:panelGrid/&amp;gt; which incorrectly uses rowClasses. It should be as follows:

&amp;lt;h:panelGrid columns="2"&amp;gt;
Page 114, the image shows an incorrect layout which has the Session Bean Package and JSF Classes Package listed as ejbs. These should be kept separate.

Page 115, faces-config.xml is not required in JSF 2.0. The author spends a lot of time configuring the faces-config.xml file which is not required, or desired. All of this is handled by annotations. JSF developers take heed!

Page 117, under how it works mentions facelets templates which are not covered in this section, but subsequent section. This is entirely misplaced. Further, the explanation is the author's viewpoint, and is not required by the specification. The reasoning is relatively sound, but should be conveyed as opinion.

Page 127, the author missed the title of the book on NetBeans 7 and mentions Google Web Toolkit and its plugin which are available on NetBeans 6.8. Therefore it is irrelevant.

Chapter 6 - Using JavaFX

This chapter is irrelevant since the functionality discussed is part of NetBeans 6.9.1. That said, it does provide a good learning path for what is available in NetBeans for JavaFX.

I am not sure when the author began writing the book, but currently there is a JavaFX 2.0 Beta SDK Plugin for NetBeans available.  

All developers interested in JavaFX should be using the new plugin.

Chapter 7 - EJB Application

This was a sample chapter that the publisher sent to me originally. The demonstration is well done, and serves as a nice accompaniment to my demonstration on Youtube of how to do some of the same things with JPA.


The recipe for doing a Stateful Session bean demonstrates its usage correctly, but fails to cover when and where you would want to use them.

RESTful web services (JAX-RS) are very popular right now. It seems like every time I look around, I find more applications taking advantage of it. The coverage here is simplistic. The reader is better off looking on the Jersey site, looking at this overview, or demo.

The explanation of Metro (JAX-WS) as a web client is well done, and the example using Google Maps is easy "eye candy".

Chapter 8 - Mobile Development

I examined the section, but reserve some comments since I use Mac OS X and refuse to install Windows to use the kits mentioned. That being noted, the latest version of the Java ME SDK does work on Mac OS X.

CLDC Application Emulator and NetBeans 7.0.1

I was able to create the CLDC application without issues, and run it as can be seen in the image.

I could not verify the Nokia S40 Toolkit since it works only on Windows.

The CDC environment is not available on Mac OS X. I could not verify the information as noted above. I don't use Windows.

Chapter 9 - Java Refactoring

The author does a good job of explaining the refactoring tools in NetBeans in general. This is more complete than a number of publicly available tutorials. This would be a reason to buy the book. I really enjoyed this part of the book, and wished that the author would have provided even more examples. I liked it. The extracting a super class and interface examples are very nicely done.

The author should have skipped a comment at the beginning of the chapter about the techniques breaking some code. As with any refactoring tool, you could cause some code to break, but this puts a new developer on the defensive, and could cause them not to use the tools. This would be a real shame since the NetBeans tools are some of the best around.

Page 202, How it works has commentary about the folder name and project name should be the same. I totally disagree. You could call the folder ejbmailapplication, and then use the refactoring tools to rename the project EJB 3.x Mail Application which is much easier to read than a generic folder name.

Chapter 10 - Extending the IDE

This chapter is dedicated to providing an example of how to extend the IDE to meet a specific need. The examples are contrived, but do demonstrate the ease with which you can extend NetBeans. The examples are simple and to the point.

This is a well done set of examples, but I feel most people would not use this information.

Chapter 11 - Profiling and Testing

I found this chapter to be another missed opportunity by the author. The chapter starts out by showing the user how to perform a profiler calibration of JDK, It is followed by profiling an example application. The author does not provide any real depth to the profiling beyond the basics. There is not explanation, or what the information means. There are some obvious "hot" spots which are shown for example initComponents() and startup() could have some discussion points.

The section on creating JUnit tests explains how to use the IDE to create the tests, but does not cover any of the options that are available, and why you would choose to use them, or not.

The section on SQE is so short I feel it could have been skipped. SQE is a really good tool, but this cursory preview is not much to get you excited about it. I use it and PMD on a daily basis. If I didn't know more about it, I would believe that the author finds it mildly important. SQE can make you a better developer if you understand what it is telling you about the code.

The section on monitoring HTTP connections covers a lot more details than I have seen elsewhere and may be a gem in the rough. I had not played with "replay" and it was interesting.

JMeter should have been skipped. It is frivolous in coverage.

Chapter 12 - Version Control

This chapter covers two important source control systems. The first is Subversion which is probably the largest installed base worldwide. Every very large enterprise I have worked at has used it. I use it at home for code that I post on my blog.

The coverage of Subversion is very well done. Every developer using NetBeans with SVN should read this chapter.

The second source control system is Mercurial. When Sun chose this for OpenJDK I was surprised. Until that point, I had never heard of it. The coverage here of this important SCM is very well done too. If you are using a distributed SCM like Mercurial, this section is a good read.

Please note that NetBeans supports Git and numerous other SCMs.

Additional Information

Additional information on the book, errata, and ordering information directly from Packt can be found here: http://www.packtpub.com/netbeans-ide-7-cookbook/book
Enhanced by Zemanta

Tuesday, August 09, 2011

JSF Trick of the Day: CSS and EL

A perfect desktop image for CSS developersImage via Wikipedia
If you need to dynamically change CSS based on page location, you probably have seen something like this:
background-image: url('../../../../resources/images/background.gif');
You can remove all of the ../../../../ from the CSS by using Expression Language (EL) selectively in your CSS for example the above example can be modified to use the FacesContext to determine the location of an image resource from any page. See the example below.
background-image: url('#{facesContext.externalContext.requestContextPath}/resources/images/background.gif');
This will always have the correct path to the resources no matter how nested the pages are in your application. This same technique can be used to manipulate other CSS entries dynamically. This technique works on JSF 1.2 and JSF 2.0.

UPDATE:
As a friend pointed out in the comments it can be shortened further. I want to make a point that this technique gives you access to the FacesContext object which gives you a lot more flexibility.
Enhanced by Zemanta

Friday, August 05, 2011

Book Review: Java: The Good Parts

I had an opportunity to read Java: The Good Parts by Jim Waldo which was included in my Java 7 Launch Party Kit. I was not sure what to expect from the book. I was pleasantly surprised to discover it is a really good book.

There are a number of great quotes in the book which I will keep handy when I need to find a good code quote. Especially great were quotes to use with junior engineers.

The book covers a lot of history about decisions made in the Java language in the beginning, and how those decisions have evolved over time. The historical design decisions are still relevant today, and in some cases make the evolution of the platform more difficult. The idea that we must be able to run 1.0 Java code is rooted deeply in the language. The decision has caused a lot of legacy designs and constructs to remain in the code. Arguably, good, or bad depending on implementer, or implementation.

I was very happy to have been given the opportunity to read the book, and would give it 4/5 stars. It is a guide for senior developers to help mentor junior developers, and provides junior developers with answers to questions about why something was done a certain way in Java.

Details

The book is divided into eleven chapters: Introduction, Type System, Exceptions, Packages, Garbage Collection, JVM, Javadoc, Collections, RMI and Object Serialization, Concurrency, and Developer Ecology. These are in the author's opinion some of "good" parts of Java.

The introduction is more of a list of credentials for the author, and why we should consider him a subject matter expert. Jim certainly has the credentials to cover the topic being part of the early team on Java at Sun.

Chapter Two - Type System

The Type System is our first introduction to why the author feels this is a good part. The explanation has some historical perspective and is backed up with code. The real gem for me occurs under the topic A Real Problem where Jim has an interesting and insightful set of remarks. Jim explains a change in the class loading mechanism that was a response to a potential security issue which was discovered early on in Applet security. The issue was sharing of static variables across applets in a shared VM space. The fix was to ensure each applet was loaded by its own class loader. Also the run time type of an object would now be determined by a combination of its compile time type, and the class loader.

This now means that there is a difference between the compile time type of an Object and its run time type. It usually does not matter if you are not loading objects over the network, or not using multiple class loaders. If you do so, there can be consequences which should be considered. This is a sage piece of advice.

As noted, you will not notice most of the time if the Object is loaded by a common class loader. If they are loaded by different class loaders you will get a message telling you that the declared type is not the same as the run time type and are incompatible even though the source indicates they are the same.

Chapter Three - Exceptions

This chapter covers exceptions and starts with a great quote:
Those who object to the exception mechanism either don't understand it, don't realize what it can do, or are simply lazy twits who don't care about writing reliable code.
This is a great quote. Sometimes you feel like it was a bad idea, but it forces you think about what your code could do. We think of code with rose tinted glasses, and this allows us to get some clarity.

There is another quote on page 34 about some code which is not abstracted, and checks for exceptions after every operation.

This is the mistake of a puppy programmer. When you encounter such code, you should correct the writer, perhaps by rolling up a newspaper and swatting the offender.
That is one to keep in your hip pocket for use later.

On page 36, Jim points out a common form of exception handling which I have seen far too often and should result in the aforementioned swatting with a paper.

} catch (Exception ignored) {
// Catch and swallow.
}

I have seen too much of this, but this pattern is common in a try, catch, finally where you are closing a resource. This changes with Java 7 and try with resources.

The closing part of the chapter refers to the Dark Side. The discussion is focused on the evil of RuntimeException and why developers should avoid it. If you have been doing any development over time you will come across code you have written and is now deployed which has an exception condition you did not anticipate. Usually it occurs where we may have been a little lax on unit testing, and had to meet a deadline. When it occurs, we will be tempted to make the exception a RuntimeException so that we don't have to change our method signature. That is the temptation of the Dark Side. This is summed up in the following quote:
... If you actually design your code to throw only subclasses of RuntimeException, then you have gone beyond simple evil. You have now become a corrupter of others, and should feel the appropriate shame and be subject to the appropriate ridicule. 
Enough said.

Chapter Four - Packages

I started laughing and remembering my early days as a Java programmer.  Page 41 has a quote on using the unnamed package (default).

The unnamed package is a form of namespace limbo where code written by confused, obstinate, or lazy programmers is placed until they evolve to a higher life form.
Following that witty comment is one of the best explanations on why you should not use wildcard imports. I will quote the author once again since the explanation is succinct.

The more general form of the import statement is quite popular, but should be avoided if you can. By importing more than you need, you are polluting the namespace of your own code, and make it more likely that you will clash with some name that is defined in the other package.

Later there is an important discussion on examining the quantity of imports in a class. The more classes that are imported from another namespace may indicate an interconnection between the class, and the other namespace. This may indicate a design flaw, increased complexity, or lack of abstraction.

Chapter Five - Garbage Collection

There is a great explanation on the use of references in Java as opposed to pointers in C/C++. The primary reason we use references is because of garbage collection. The explanation is really well done, and gives you insight really why this is such a good part of Java. I actually found this chapter very interesting, and the historical perspective on what decisions were made and how it works today make the chapter a must read.

Later there is a discussion on finalizers and why you should avoid them as a programmer. The basic point is that the finalize() method may never be called. If you rely on the finalizer to cleanup your code, you may leave your data in an inconsistent state.

Chapter Six - Java Virtual Machine

The JVM is probably the most important part of Java. Its design and flexibility have allowed us to use it for more than just Java. Today the JVM allows us to run languages like Ruby (JRuby), and Scala on the same VM as Java. It allows us to combine these languages in a new "ployglot" programming style. The chapter is a discussion of the great flexibility of the JVM.

Chapter Seven - Javadoc

At first I was not sure why the author felt this was one of the good parts of Java. After reading his discussion on the subject I have become convinced he is correct.

I think that the {@inheritDoc} tag requires special mention. This is particularly important if you have a class which is implementing an interface, or extending a class. If the documentation is complete on the interface, or parent class, this allows you to inherit the documentation and allows the developer to be more productive without having to copy the previous comments to their implementation. It also allows you to add additional comments to the existing comments.

The author makes a very good recommendation: write the documentation for your interfaces first. The implementation classes simply need to inherit them.

Finally, the author concludes that Javadoc comment review is just as important as code review. I agree generally with the author, but I have found that the code changes over time, and often the Javadocs do not. So I take a position to not believe the Javadocs per se, and choose to use the force and read the source.

Chapter Eight - Collections

If there is any reason to buy this book, this is it. The explanation of the Collections API is very complete, and the historical reasons for how it was constructed, and the evolution over time is a walk down memory lane. The discussion about parametrized types, and the evolution of generics in Collections is very interesting, and informative. I have a new found appreciation of the difficulty, and the decisions made on how to incorporate them.

Additional information can be found in Java Generics and Collections by Maurice Naftalin and Philip Wadler (O'Reilly & Associates).

Chapter Nine - Remote Method Invocation and Object Serialization

Here is where I depart with the author. Jim was involved with the development of RMI. His love for the technology is apparent. Without a doubt, it is a valuable technology, but it is often dealt with on a higher level of abstraction today. Most Java developers could not write an RMI application without taking a trip to Google.

If you are looking at RMI, the author recommends using a security manager. Here is his quote on why:

Because RMI makes use of the ability of the JVM to dynamically load code, and because you don't want to load code without the protection of a security manager, programs using RMI should always be run with a security manager.

Object serialization is an important part of Java development today. This is particularly true of applications which are running on an application container. I was surprised to discover something about serialization I had not considered before. When serializing an object, it makes an object graph of all the classes that are contained in the object so that when it is de-serialized, it matches state of the application as completely as possible. There are two key items to remember.

  1. If two Objects serialized have a reference to a third common Object, when the objects are de-serialized. There will be two Objects created which represent the common third object. This could result in strange errors.
  2. All static variables are reset to the default values on the de-serialized object. Static variables are considered transient by serialization.
The second issue is particularly interesting to web developers. Session objects must be Serializable. This means you must keep the fact that static variables can not be assumed to be consistent since they are transient.

Chapter Ten - Concurrency

This is a boon to Java and an Achilles Heel. The author talks about a simple implementation, but refers you to other resources for more details on the subject.

The best book which should be on all developer's bookshelves is: Java Concurrency in Practice by Brian Goetz (Addison-Wesley). It is a must have for anyone doing concurrent programming. Also consider Java Threads by Scott Oaks and Henry Wong. A good book too on the subject.

One interesting note is mentioning the Timer object to schedule Thread processing. I would go further and recommend that the reader look at the Java Concurrency API instead. If you need anything more sophisticated than basic scheduling, it is the only logical choice.

Atomic data types are mentioned along with an example. This is something that most programmers, I believe, forget about. These are thread-safe data types which should always be considered in concurrent programming. Thanks for the reminder, simple explanation, and example.

Chapter Eleven - Developer Ecology

This concluding chapter talks about the evolution of the ecosystem in which Java development occurs. The advancement in tooling available should be used to increase productivity, and cleanliness of the code. The author covers items like IDEs, and unit testing. This is a nice conclusion to the book.
Enhanced by Zemanta

Thursday, August 04, 2011

NetBeans 7.0.1 SerialVersionUID Generator Plugin Published

T.N.C.A, Serie H

This seems to be a common item that I publish, but the latest version is published for NetBeans 7.0.1 and can be downloaded here: serialVersionUID Generator. Another great job for to keep pace with the release.

Popular Posts