Skip navigation
1 4 5 6 7 8 Previous Next

cayhorstmann

153 posts

I am updating the “External Services” chapter in Core JSF. There is lots of new and interesting stuff: How to use JPA, stateless session beans, and WebBeans. I ditched the LDAP sections (for which I had received very few queries, even though the examples are notoriously hard to set up). I reimplemented the authentication example with a JDBC realm, which was no fun. Now I am at the web services section.

In the previous edition, I used the Amazon e-commerce service that lets you browse the Amazon catalog. It is pretty simple, really. Inject the service into a managed bean:

@WebServiceRef(wsdlLocation=
   "http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl")
private AWSECommerceService service;

Then call the service API.

Generate the client-side artifacts:

wsimport -p com.corejsf.amazon http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl
jar cvf aws.jar com/corejsf/amazon/*

Put the JAR file into WEB-INF/lib. Deploy, and it just works.

Except that Amazon has repositioned the API as a “product advertising API”, and you now need to be an “Amazon associate” to use it, which makes it less suitable for a book example.

Now what? I found a couple of web services directories here and here. SOAP services seemed pretty pathetic. Mostly vendor and academic demos. A magic square finder? Please...

There were two useful services that seemed to have a chance of being long-lived. The NOAA weather serviceand Microsoft Bing. Ok, let's make those client-side artifacts:

wsimport -p com.corejsf.noaa http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl
parsing WSDL...

[ERROR] rpc/encoded wsdls are not supported in JAXWS 2.0. 
  line 405 of http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl

wsimport -p com.corejsf.bing http://api.search.live.net/search.wsdl
parsing WSDL...

[ERROR] A class/interface with the same name "com.corejsf.bing.SearchRequest" is already in use. Use a class customization to resolve this conflict.
  line 1 of http://api.search.live.net/search.wsdl

[ERROR] (Relevant to above error) another "SearchRequest" is generated from here.
  line 1 of http://api.search.live.net/search.wsdl
(followed by seven more errors)

WT-*? Aren't these supposed to be interoperable?

dead-dog.jpeg

Am I beating a dead dog here? This article describes research on finding web services. In 2008, they found a few thousand services, most of which didn't seem to work. Are WS-* services the new CORBA? I know there are lots of interesting RESTful services out there. The only drawback for me is (1) the data comes back as some ad-hoc XML, RSS, or JSON, and I have to deserialize it by hand and (2) there is no connection to JSF.

If you can point me to an interesting WS-* service that is free to use, likely to stay around for a few years, and has a WSDL thatwsimport can process, I would very much appreciate if you leave a comment. Or, talk me into dropping the web service section altogether.

As I am updating my share of chapters in the Core JavaServer Faces book (with the hard parts fortunately being tackled by my coauthor, David Geary), I started playing with WebBeans, erm, JavaContexts andDependency Injection. I'll keep calling it WebBeans—the alternative JavaCandi is more than I can take. There are two features that are crucial for JSF users: Conversation scope and access to stateful session beans from JSF pages. (Seam users know all about this and can skip this blog.)

http://weblogs.java.net/blog/cayhorstmann/archive/tower-of-babel.png

I have been using Glassfish for most of my test programs, mostly because I am used to it. But today, as I did some experiments with JBoss, I found another reason to like Glassfish—it bootsa lot faster. (I remember a rather dismal Java One session with Jerome Dochez a couple of years ago where he demoed the embryonic Glassfish v3 and how it was wonderfully modular, and I thought “Oh boy, Second System Syndrome”. Well, I was wrong, and Glassfish v3 is wonderfully fast.)

The current Glassfish v3 Preview has some support for WebBeans. As of today, it contains a 2-month old version of WebBeans and a more recent WebBeans integration module (look for Glassfish JCDI in the update tool).

I got my first trivial app to work after paying attention to these points:

  • Import javax.annotation.Named andjavax.context.SessionScoped—that's where the classes were way back when
  • Be sure to add an empty WEB-INF/beans.xml
  • Make your bean serializable

Then simply replace @ManagedBean @SessionScopedwith @Named @SessionScoped, and you are good to go.

Of course, that's just another way of achieving what you can already do with JSF 2.0. For something strictly better, turn to conversation scope. In JSF, you have the uncomfortable choice between request scope (which is too short) and session scope (which is too long). JSF 2.0 gives us view scope and a flash object, neither of which is all that helpful in general. Conversation scope is what you want. You turn it on when you want to start a sequence of interactions with the user, then turn it off when that interaction has finished. The user can open two browser tabs with different conversations.

conversation.png

It's easy with WebBeans, and it works with the current Glassfish v3. Change @SessionScoped to@ConversationScoped. Add a field

private @Current Conversation conversation;

and calls

conversation.begin();

and

conversation.end();

into suitable action methods. The life of the bean is extended from request to conversation scope when you callbegin, and it ends when you call end.

Perhaps this should have been a feature of JSF 2.0, but I take it any way I can get it.

The other key feature is the ability to skip managed beans altogether and to invoke stateful session beans from your JSF pages. This does not seem to work in the current Glassfish, which is too bad. I get a warning

INFO: Web Beans 1.0.0.PREVIEW1
INFO: Transactional services not available. Transactional observers will be invoked synchronously.
INFO: EJB services not available. Session beans will be simple beans, injection into non-contextual EJBs, injection of @EJB in simple beans, injection of Java EE resources and JMS resources will not be available.
INFO: JPA services not available. Injection of @PersistenceContext will not occur. Entity beans will be discovered as simple beans.
INFO: @Resource injection not available.

That's when I installed JBoss 5.1.0GA. Here are a few things I learned:

  • JBoss 5.1.0 includes a more modern version of WebBeans than Glassfish
  • WebBeans support seems pretty complete, much more than in Glassfish
  • JBoss startup is s l o w compared to Glassfish
  • Hot deployment is lukewarm in JBoss. I had to restart the server more often than with Glassfish
  • The logs are at server/default/log/server.log, and they don't show up as nicely in Eclipse as the Glassfish logs
  • You can use JSF 2.0 with JBoss 5.x simply by replacing the jsf-api.jar and jsf-impl.jar in theserver/default/deploy/jbossweb.sar/jsf-libs directory with the Mojarra 2.0 beta
  • The Eclipse adapter for JBoss 5.0 almost works with 5.1, but it doesn't import the JSR299 API. I had to manually add the JAR file to the project. This fellow has a remedy.

A few days after Eclipse Galileo, Netbeans released its latest offering, Netbeans 6.7. Here is a first look, as always from my entirely biased perspective.

out-of-box.jpg

“Out of the box” readiness has always been a forte of Netbeans (pun intended for old-timers). The integration with theKenai open source software hosting site takes nothing more than entering your password. You can do issue tracking from inside the IDE. Think of it as “Mylyn for Kenai”.

Glassfish integration is also smoother than in Eclipse. And you don't have to fuss with a Subversion adapter, like in Eclipse. Subversion and Mercurial are built in.

I just noticed that Netbeans has an equivalent to Eclipse's workspaces, called “project groups”. (Thanks to Michael Bien for pointing out that this feature has been there since 6.0.) The Netbeans feature isn't quite as powerful as the Eclipse equivalent. —you can't have two project groups with different code formatting conventions.

I am told that Netbeans has great support for PHP, but that's not my cup of tea. I tried activating Scala support, following the “nightly build” instructions from this page, but I got an error “Could not connect to compilation daemon.”.Update: That error goes away if you globally setSCALA_HOME and add the Scala bin directory to theglobal path (e.g. in /etc/environment). Unfortunately, the plugin seems just as basic as the Scala plugin in Eclipse. In particular, no useful autocompletion or refactoring.

One big disappointment for me is the lack of support for a JSF component set. Netbeans used to include the Woodstock components, which Sun unfortunately abandoned. The promise at the time was that Netbeans would switch to IceFaces, and you can find a conversion guide here. It uses a plugin which does not seem to be available with NetBeans 6.7. (Soapbox: I have always felt that there ought to be a high quality, visually attractive component set as a part of JSF. Can you imagine if Swing had just specified JComponentand left it to third parties to develop component sets? Well, that's how it is with JSF, and Sun is now at the mercy of those third parties.)

If you want to experiment with JSF 2.0, be sure to install Glassfish v3 preview (from here; this is not the same as the prelude version that ships with NetBeans). Then install Vince Kraemer's nifty Glassfish V3 enabler plugin from the Netbeans plugins dialog, and point it to your installation. Unfortunately, JSF editing is disappointing. The facelets plugin doesn't know anything about JSF 2.0. So, it's really no better than Eclipse.

That, in a nutshell, is the problem with this Netbeans release. For a while, Netbeans was faster and better in supporting new Java EE features. For that reason, I regularly used it for my web projects. But with both Eclipse and Netbeans having equally basic support for JSF 2.0, I found myself back in Eclipse. What would it take for me to change again? Autocompletion in JSF 2.0 pages. A JSF component set with a visual editor. A superior Scala plugin. Hopefully in Netbeans 6.8.

http://weblogs.java.net/blog/cayhorstmann/archive/galileo.jpeg

I just installed Eclipse 3.5 (Galileo)—it seemed a more attractive thing to do than actually getting my work done. Fortunately, I only need three Eclipse plugins right now. Here is how they fared with Galileo.

  1. The Scala plugin seems to work just fine, even though the plugin page ominously states “3.5 Milestone releases are not fully supported”
  2. The Glassfish plugin works, but not in the same way as it did in Eclipse 3.4. In that version, you right-clicked on the Servers tab, selected New and then clicked the “Download additional server adapters” link. Following this tip, I instead addedhttp://ajax.dev.java.net/eclipse to the update sites, which is a much more sensible way anyway. I never understood why there was a separate mechanism just for server adapters.
  3. The Subclipse pluginalso works as always. Actually, I tried the Subversive plugin first (which is a part of Eclipse), but it didn't pick up my existing SVN projects. I think this is because one has to download “connectors” from another site, as explained here. What's the point of having half of it a part of Eclipse? I guess I'll stick with Subclipse for a littler longer.

What did I have to show for my troubles? Not much, actually. Here are the three improvements that I noticed so far.

http://weblogs.java.net/blog/cayhorstmann/archive/eclipse-icon.png

  1. The icon now has a Java EE IDE banner, probably because people were always confused which version they had actually installed. Why they don't show it in the title bar is a mystery. Maybe in 3.6.
  2. The code formatter now has an option Never join lines that makes Eclipse not move code or comments to different lines. That is useful if you don't want Eclipse to make a hash of your carefully aligned array initializations etc. Of course, it also means that you then have to manually reflow your javadoc comments, which doesn't sound like a win. Maybe in 3.6, they'll give us separate options for code and comments.
  3. There is now an option to generate toStringautomatically. This is something I've wanted for a long time. Unfortunately, it is not very good. Core Java gives these simple rules for toString
    • Use getClass().getName() to print the class name. Then your toString can be inherited.
    • When you redefine toString in a subclass, first call super.toString(), then add the subclass data.

    The Eclipse formatter follows neither of these eminently sensible rules. Maybe in 3.6.

Did I miss anything exciting? Thisand this and this review didn't have anything that looked it would change my life. Not a problem, of course. Eclipse is a great IDE and pretty mature at this point. If I could wish for something, it would be better support for JSF and Scala. Maybe in 3.6.

jsf2-refcard.png

DZone just published the JSF 2.0 version of my JSF refcard. It provides updated summaries of the tags and attributes needed for JSF programming, along with a summary of the JSF expression language and a list of code snippets for common operations.

If you haven't done so, give JSF 2.0 a try. It is a lot more fun than JSF 1.0. Here is a quick recipe.

Now look at the source. Note these points:

  • A blessedly empty faces-config.xml
  • @ManagedBean @Stateless annotations in the bean class
  • Facelets syntax in the web pages

If you are stuck with JSF 1.x, the old refcard is still available.

I teach computer science at San Jose State University. My department just ended up on Slashdot. One of my colleagues, Dr. Beeson—who, to his great credit, makes beginning students write lots of little homework programs until they get them right—got into a tussle with Kyle Brady, an eager student who insisted on publishing his answers on the internet. I don't want to get into the personalities here. Beeson can be irascible and a bit overbearing, and the student's claim that he is doing this to increase his chances for employment rings a bit hollow. When is the last time you hired someone because of their TicTacToe program? Even if I did, I'd be wary about candidates who write if (foundEmpty == false) instead of if (!foundEmpty)...

http://weblogs.java.net/blog/cayhorstmann/archive/tictactoe.jpegSure, instructors should vary their problems from one semester to the next, but there are only so many ways in which you can vary the basics. Consider TicTacToe. There are maybe ten ways of changing it. Of course, there is no intrinsic merit to TicTacToe. It's just a vehicle to test nested loops over a 2D array. We like it because doesn't require a long backstory—students are familiar with it. But let's ditch TicTacToe if all variations are on Google. What else is there? Magic squares. Row and column totals. Counting zeroes. Making shapes with ASCII art: squares, diamonds, spirals. Floodfill. Escaping from a maze. The game of life. But all of these are on the internet too.

So, what does it mean for teaching and learning programming when the solution to every beginner problem is available on the internet?

I am all for more code reading by students. Too many students just write code, and if googling an answer makes them read more code, that's great.

When I learn new stuff, I set myself little tasks to solve. I don't just google for the answer since that would defeat the purpose of learning. Are our students like that? Kyle Brady probably is. But I have met a few who just want to get a good grade, get their degree, and start making money. Others are willing to do the right thing but lack the self-discipline. Quite a few work a job or two to put themselves through college, and limited time and financial necessity makes them go to Google when they shouldn't.

That brings me to the issue of “certification”. When you hire someone, you want to see that college transcript because you expect some correlation with ability. So, we as instructors need to give grades, and to give grades, we give homeworks and exams. All of whose solutions are available on Google. So, how can we certify that students know what they are supposed to?

http://weblogs.java.net/blog/cayhorstmann/archive/cone-of-silence.jpegStrategy #1. Shut off the internet. Herd everyone in a room with lead walls and make them do their work there. Or (gasp) go back to paper and pencil. Personally, I hate doing that. I give bring-your-laptop, open-book, open-notes exams because I want my students to build up skills that they can use later.

Strategy #2. Starve them for time. That's what TopCoder and betterprogrammer do. Sure, you could google for hints, but then you would not be able to finish in time. My students will argue that I use that approach as well, and they do not like it.

Strategy #3. Interview each student personally and ask questions about the code. Unfortunately, this is incredibly time-consuming and impractical on a large scale. (After all, if this was easy, we wouldn't have the SCPJ.)

Strategy #4. Forget about coding and evaluate students on their ability to be creative, express themselves, resolve conflicts in a non-confrontational way, etc. etc. These are all wonderful traits, of course. But I am reminded of a faculty summit at, of all places, Google, where eager professors from reputable institutions shared the latest thinking in computer science education. At the closing session, one of the Google managers said that this was all good and well, as long as the graduates can code.

http://weblogs.java.net/blog/cayhorstmann/archive/arnold-bodybuilding.jpegSo, as you read those Slashdot comments, have some pity for the poor CS instructors. Not for having to come up with a neverending stream of practice problems—that's part of the job. But for having to teach students to be ever more disciplined. In the past, we could rely on a reward system for homework assignments. Do a good job, get an A. Thanks to Google, it has become too expensive to give a fair reward for the kind of routine practice homeworks that one really needs to build up skills. Now we must train students to do their homework without resorting to Google, show them nicely what happens when they don't, and then tighten the screws by the end of the semester, all without demotivating those students whom we want to attract to the major. This is not an easy task.

What you don't hear in Slashdot is that Dr. Beeson is actually doing a good job. He built a system where students can submit their problems until they get the right answer, and for a lot of students that is pretty motivational in itself. Obviously motivational enough to get Kyle Brady to come up with answers that he is proud to share with the world.

The Toy Show

One of my favorite parts of Java One is the Friday morning “toy show” where James Gosling presents a random mixture of cool and inspirational projects. Of course, all these involve Java in some way.

The BlueJ team received a ]]>water-troll.png

A fellow from RuneScape dev demoed their tools, and I learned how one animates a water troll, something that will surely come in handy one day.

There was a wacky demo involving a Wii infrared sensor and infrared LEDs that guide a projector. One of them lets kids draw on a virtual wall. I want it for the Horstmann twins.

Tor Norbye, the demo stud, showed a very impressive JavaFX authoring tool whose release is planned in December. I admit that I was dubious about Java FX when it was first released, but it is looking much better now. At least when Tor demoes it...

There was a demo by the high school kids who won the FIRST robotics contest. Sun and the FIRST folks just ported the programming environment from C/C++ to Java. They hope it will lead to more interesting robots in the future—right now, the students struggle enormously with core dumps. They need volunteers—check out their web site. What's in it for you? “There is nothing more fun than see your program drive on the floor.”

gosling-14.png

The Grameen foundation showed off an open source system for helping with microfinance in third world countries. They also need volunteers.

 

SIM cards have now become so powerful that they can easily run Java and a web server. The latest ones can interact with sensors and WiFi radios. A fellow showed how you can mock that up with Sun Spots for easier debugging.

gosling-14.png

Someone demoed a satellite ground station management app built on Netbeans RCP (i.e., the same platform on which the Netbeans IDE was built), using over 1000 modules. As it happened, James Gosling's first programming job was in a satellite ground station (he was 14), using a PDP 8. It had less compute power than a modern smart card.

Two Hungarian university students showed off the project that won them first price in the Ricoh printer contest. Those printer/copiers are Java-powered, and the students used them to grade multiple choice exams.

A musician showed off a Java-powered juke box that allows independent artists to upload their creations to a web site and have it played in bars. As James put it: “Here's Manuel. He is a musician. He has a problem.”And with the help of a touch screen, a cash reader, and Java FX, he put together a solution.

“Project Bixby” controls an Audi TT on a dirt rallye course going really fast (160 km/h) without a driver. And finally, the“LincVolt” project controls a 1959 Lincoln Continental with an electric motor, this time with a human driver—another musician named Neil Young. There is a Swing-based control panel. Boy, is it ugly—maybe JavaFX can help. What's next? The “Thinkin' Lincoln” that no longer requires Mr. Young?

Technical Sessions

I attended the “JPA Magical Mystery Tour” session. JPA has been a real game-changer, maybe more than people realize. I can now routinely run student projects that involve a database, with a lecture on JPA and a couple ofcode samples. These are greenfield projects, so there is no need for any SQL. Of course, as the speaker pointed out, in a real project, you don't need to write the SQL, but you still need to understand what goes on. For example, JPA 2.0 has a nifty @OrderColumn for persisting list orderings, but you really need to think about the implementation to understand the costs. The talk started out with the basic mappings and it got a bit mysterious at the end, with attribute overrides and compound primary keys, but it never quite rose to being magical. I had hoped for more details about the magic of the entity manager. Moral: Don't overpromise in your title.

Bill Pugh gave a repeat of his “Defective Java” talk—the antidote to “Effective Java”. If you haven't used his FindBugs tool, check it out now! He had a sabbatical at Google where he explored how FindBugs does on production code. Interestingly, it found a lot of bugs—over 3/4 of the flagged issues were deemed by Google engineers to be mistakes that should be fixed—but it didn't find many mistakes that really matter. Those had been found earlier, and perhaps painfully, through testing and failures in production. The moral is to use FindBugs early. Bill is now working on a cloud service for community review, where programmers can post previously found bugs. When you evaluate a FindBugs issue, you can then evaluate whether it is likely to be serious.

Our cat, Mr. Darcy, would like to thank Bill for the bug that he tossed my way when I raised my hands as soon as I saw the slide involvingDouble and ==.

http://weblogs.java.net/blog/cayhorstmann/archive/mrdarcy.jpg

Ludovic Champenois (AKA Ludo) gave a presentation about EE6 tooling in NetBeans and Eclipse—sadly not well-attended at a time slot that is usually reserved for such crowd pleasers as “Enhancing the Role of aLarge U.S. Federal Agency as an Intermediary in the Federal Supply Chain via a Service Registry and a JBI-Based ESB”. Ludo is responsible for the Glassfish plugin for Eclipse, which I can heartily recommend. If you just get started with it, download theEclipse/Glassfishbundle. You get one-stop shopping, just like with NetBeans, with JavaDB configured, all XML schemas, javadocs, etc.

Finally, after having been thoroughly worried about JSR 299 vs. JSR 330, I decided I'd better learn more about Guice, and I attended the talk by Jesse Wilson. Ok, it's a nice enough DI framework. You configure injection with a “fluent” API, not XML. That's nice. But it isn't as nice as WebBeans, erm, Contexts and Dependency Injection. Instead of writing a lot of XML boilerplate for configuring a test of a large system, Guice makes you write a lot of Java boilerplate.

Here is the one thing I don't get about JSR 330. It has this annotation @Inject that tells you that you want to inject something,but it doesn't tell you why. Injection annotations such as @Resource, @EJB, @PersistenceContext, @ManagedProperty, are common in Java EE. I can see the benefit of having a meta-annotation that says “this annotation injects”, but I don't see why you would want a single injection annotation. I asked Jesse about that, and he seemed to say that injection was this big, scary, strange thing that should definitely stare in your face in your source code. Well, in my Java EE experience, injection is your friend, not something that you fret about. So it seems that in its current form JSR 330 isn't very compatible with, say, JP Ain a Java SE application, surely a reasonable use case. My suggestion would be for JSR 330 to lighten up, realize that there isn't going to be a single source of injection, and focus on meta-annotations and commonalities among injection providers. Caveat: I am not an expert on this stuff, just someone who looks at it from the outside with some experience in both EE and SE.

Summary

Java One is now over, and here are my random conclusions and opinions.

  • Concurrency is on many developers' minds, and there is no silver bullet.
  • The evolution of the Java language is essentially over. There may be a few minor tweaks on the way, but if you are pining for closures, properties, or metaclasses, look elsewhere. Scala is a great choice today, and Groovy could be good if they'd just start writing a language spec.
  • I am still a bit sore that Java FX is yet another language and not a DSL in Scala or Groovy, but the libraries and tooling have come a long way. I'll give it another try. And, hey, Larry Ellison (or perhaps his personal coder) likes it.
  • Java EE 6 is a winner. With sane WAR packaging, JSF 2.0, JPA 2.0, and (hopefully) web beans, erm, contexts and dependency injection, it can truly stand on its own without third party components (ok, except for a library of decent-looking JSF components).
  • A trend started a few years ago where more presenters and conference attendees used Mac OS X, Linux, or even the occasional OpenSolaris. These screens easily make the majority now. There is a sea of Macs, and even the orange glow of Ubuntu easily outnumbers Vista.
  • Where will Java go after the Oracle acquisition? Will there be another Java One? Will the JCP stay on? My guess is that Oracle will not make any major changes in the near future, and that we will all meet again for Java One 2010 next year.

For Packrats

packrat.jpeg

Like every year, I offer a quick script for packrats who want to download the slides for all the talks. Of course, you can just wait for them to become available online after the conference, but then you'd not be a true packrat. Here goes:

curl -d ilc=230-1 -d ilg=English -d is=y http://www28.cplan.com/cc230/sessions_catalog.jsp > index.html
mkdir cb_export
for f in `grep -o "/[^/]*.pdf" index.html` ; do curl -u contentbuilder:doc789 -o cb_export/$f http://www35.cplan.com/cb_export/$f ; done

This script improves upon last years—point your browser to index.html, and you get a page with all the talk names and links to the local PDFs. For extra credit, figure out how to add the paperclip.

Miscellaneous Fun

Hooray--no keynotes today. (They were there, but I wasn't.) My day started out with a "Second Life" session with David Geary. It was weird but kind of fun. Here are the slides, and here are David (in the middle of the podium) and myself (to the right).

cay-sl.png

I went to a lab in which I built a "JavaFX client-server application with Jersey and REST based web services" in 100 minutes, which is pretty good given that I have never used either Java FX or JAX-RS.

fxpie.png

JAX-RS is definitely very nice--thanks eduardo for pushing me to check it out. Java FX was better than I thought. Of course, they gave us a pre-made component with the nifty effects (a pie chart with animated slices). I noted that Java FX now has a bunch of standard effects, like "glow" and "distant light". That kept the code clean and manageable.

The lab stuck to the easy part--reading data from the server. I would have liked to have an enhancement where cli king on a slice modifies the data on the server, but the course author said that was pushing the 100 minute limit.

I like to run hands-on labs in my own classes to make sure that my students get a good amount of practice and have someone there when they need help. It's always a big hassle, with students' hardware and software configurations failing in exciting ways. Well, the lab attendees--who looked like professionals--didn't have a better track record than my students, keeping four Sun people scurrying from one machine to the next.

Technical Sessions

Kito Mann gave a nice talk on writing composite components with JSF 2.0. This feature is definitely a crowd pleaser. Also check outJim Driscoll's slides.

Cliff Click and Brian Goetz's talk "Not Your Father's Von Neumann Machine" gave a crash course on modern hardware. I thought I know nothing about hardware--whenever the hardware courses come up during faculty meetings, I lose my customary loquacity for fear of embarrassment. Cliff and Brian talked about instruction pipelining, parallelism, speculative execution, and branch prediction. Hey, I knew that. Multicore memory caches. I knew that. And that was pretty much it. Ok, I learned something new about chip-level multithreading, but the idea is pretty simple. I guess I'll speak up at the next faculty meeting and ask why my students seem to be stuck with the von Neumann architecture. Check out the slides when they become available--they are very clear.

Finally, I went to Phillip Haller's and Frank Sommers' talk on Scala actors, which didn't have a huge audience but a very long Q&A period. Here is what I learned.

  • Twitter is using Scala actors for their messaging system.
  • It is a good idea to spawn new actors whenever some operation might block. The more, the merrier.
  • You can have > 100,000 actors per VM.
  • "Event based" actors do not consume a thread when they are waiting.
  • The !? operator is nicknamed the FTW operator. (Chuckles from the caffeinated part of the audience.)

Overall, it was a pretty satisfying day at the conference, but it doesn't make for a thrilling blog. Did I miss something exciting? If so, please comment!

The keynote

I do this to myself every year. I go to the opening keynote on Tuesday. I suffer through the love-in-with-Sun-partners part, just so I can get to the good part with the important announcements. Then I go to the Wednesday keynote, which offers no such benefit, and vow never to go to any other keynote except for James Gosling's toy show.

Today's mobility keynote was easily the most painful in my memory. Some fellow from Sony Ericsson broke into rambling monologes that left his stage partners speechless, and he had an inexhaustible supply of platitudes (such as "Every user is unique" and "You can be a part of the total experience") that work better in the executive suite than a gathering of engineers.

He seemed a bit taken aback that the audience didn't "get" the idea of "monetizing" the 200 million Sony Ericsson phones out there. But help is on the way, in the form of another app store. Oh goody...

The store has been around for some time, selling ring tones, games, music, and movies. Unlike the Java app store, they figured out how to take money. After July 1, you can submit your apps (without having to pay a fee, which is apparently customary in the game biz), and they'll review it within 30 days. For their trouble, there will be a 70/30 "rev share".

I think I'll skip the other keynotes.

JUG Meeting With James Gosling/Buzz from the Floor/Radio Interview

Van Riper kindly invited me to the Silicon Valley JUG meeting with James Gosling. JUG members and students asked lots of very interesting questions. A few random answers that I remember, hopefully accurately:

  • In hindsight, there aren't many things that should have been changed in Java 14 years ago. The C++ like syntax was necessary for wide adoption, and it was important to get it out then rather than waiting any longer.
  • Functional programming is great, but a lot of people have a hard time thinking that way.
  • Those alternatives to locking sound seductive at first, but not many problems map into it in a way that is natural to most programmers.
  • Google Android pays little attention to keeping a common standard, and there will be nasty surprises when every vendor does their own extensions.

People asked about "buzz from the floor", such as "Why isn't there a banner advertising next year's Java One, like there used to be in the past?" James didn't know. But he did know what was behind the rumor that he coached Larry Ellison in Java FX programming. It was not so. Larry just downloaded the SDK and hacked together some stuff on his own. Later, I told that story to some engineers, and they inquired whether it was really Larry who did it, and not his personal hacker.

radio.jpeg

Unfortunately, I had to run off early to give a Java One Radio interview. The recording should be available here.

Technical Sessions

I attended Jonas Bonér's session entitled "State--You are doing it wrong". Jonas reviewed three alternatives to standard locking: Software transactional memory (with Clojure), actors (with Scala), and data flow, which he called "the forgotten paradigm". He wrote a custom library for data on top of Scala actors. It wasn't very deep, but I learned

  • In data flow, deadlocks are deterministic. Run your program again, and it deadlocks in the same way.
  • STM isn't a free lunch--one can spend a lot of time retrying transactions

Alex Miller gave a talk on concurrency gotcha's, with good old fashioned locks. The talk was very well attended--clearly, interest in concurrency has reached the mainstream. Most of the gotchas were pretty familiar, such as the shared DateFormat. (I really hope the date and time API makes it into Java 7. Haven't we suffered enough?) I liked the slide:

synchronized(what goes here?)

I had students who would just try filling in one thing after another into that slot...

jaws.jpeg 

I tell students that they should just stay away from synchronized blocks unless they really know what they are doing. Reentrant locks seem easier to understand. Of course, there is a way of snatching defeat from the jaws of victory, also covered in Alex' presentation:

public static final Lock LOCK = new ReentrantLock();
synchronized(LOCK) { ... }

JSR 299

My final presentation was Gavin King's talk on WebBeans, erm, Contexts and Dependency Injection or JSR 299. Gavin is an opinionated speaker--good thing his opinions were pretty close to mine. He was very enthusiastic about EE6 (provided, of course, it includes JSR 299). As he puts it, finally the EE stack will be fully usable without 3rd party addons.

The web profile removes a lot of old cruft. I agree--cruft removal is excellent. He says JavaMail should have been added. Agreed too--all my web apps seem to need JavaMail, usually for password recovery.

He spoke kindly of JSF 2.0. It fixes "all the problems". Ed Burns, whom I met later at the Java EE party, basked in that statement :-)

There are a lot of things to like in WebBeans, erm, Contexts and Dependency Injection. Gavin will tell you about the benefits of loose coupling with strong typing. But I'll be more pragmatic.

  • JSR 299 gives us @ConversationScoped (think multiple NumberGuess games in different browser tabs). Maybe that should have been part of JSF 2.0, but I take it any way I can get it.
  • Your JSF apps can reach stateful session beans directly from JSF pages, without having to fuss with managed beans. If you are willing to deploy on a real app server (and not Tomcat), that greatly simplifies your architecture. I am not saying that every web app should do that, but it is a very useful option to have, as evidenced by the success of Seam.
  • JSR 299 has a very clean approach to switching between testing and deployment scenarios.

Gavin promises a proposed final draft of the spec by Monday. During the Q&A, he sad that, in hindsight, JSR 299 should maybe have been an SE JSR. I asked about potential conflicts with 330? Gavin said that JSR 299 has no (portable) solution to a standalone bootstrap outside a Java EE container, which JSR 330 provides. He'll be glad to adopt whatever they come up with. But the fact remains that there are gratuitous naming differences between the JSRs.

At the Java EE party, Ed Burns introduced me to Bill Shannon who oversees Java EE. Bill seemed genuinely perturbed by the conflict between the two JSRs. I hope this gets resolved in a positive way. As an app developer, I really want the benefits of WebBeans in Java EE 6. Sure, I could always use Seam, but that removes the "one stop shopping" advantage from Java EE.

winchester.jpeg 

At dinner with my co-author, David Geary, and my editor, Greg Doench, we talked about the Winchester Mystery House, the building constructed by the widow of the gun manufacturer who was obsessed about the spirits of those killed by the guns. The house has over a hundred rooms, most with no purpose, windows that don't open, and stairs that lead to nowhere. As one of the dinner companions remarked, just like the JSF spec. Ouch!

Tomorrow, too early in the morning, David and I will be in a Second Life chat. Please join in if you are into that kind of thing.

The Morning Keynote

I am no fan of keynotes, but I figured I should earn my press pass (thanks Jacki!) and show up.

http://weblogs.java.net/blog/cayhorstmann/archive/harmony3.jpg

The keynote started auspiciously, promising a release of Java SE 7, but that turned out to be irrational exuberance—it was just another JDK 7 build. This may seem a trivial distinction, but it is not. There is no official JSR for Java SE 7, and at tonight's JCP party unnamed but knowledgeable people agreed that Sun was not moving forward with the JSR because they are nervous about Apache Harmony. Perhaps the plan is to forge ahead with JDK 7 and then rubber stamp a fait accompli through the JSR process, which would not be good.

Apparently, every keynote must go through the usual dreary ritual of allowing paid sponsors to say their part. This time, we had

  • A fellow from eBay, offering zero detail why Java was wonderful for the eBay data center
  • A fellow from Blackberry bragging about the fact that they are the #1 smart phone (which, as remained unmentioned, has its own API, not JavaME or Java FX), and showing off the xobni app that uses that API. Apparently, xobni scrapes your information from Facebook, LinkedIn, Twitter, etc., making it available in other people's BlackBerry contact list. Such a comforting thought...
  • A fellow from Sony showing a pointless movie about Sony and Blu-Ray. Imagine my excitement when I learned that I too can particulate in interactive trivia games (their term, not mine) and earn points for some unspecified purpose.
  • The CEO from Verizon, who has the demeanor of a used car salesman, just like you think he would after looking at your Verizon bill. He admitted that perhaps they had been a bit overprotective in the past about controlling what Java apps could run on “their” phones (i.e., as far as I can tell, none). He promised to release an API on July 27 that would let developers take advantage of information known to Verizon, such as the phone user's location, friends and family, and so on. Such a comforting thought...
  • And, to top it off, an indescribably pointless love-in between Jonathan and an executive from Intel.

Once we got that out of the way, things got more interesting. There was a demo of a Korean made TV set running Java FX. This was the first really compelling use case that I saw about Java FX. Flash or Silverlight aren't plausible candidates for running in a TV set. But Sun has experience in getting Java into embedded devices, and you want flashy UIs there, not Swing. And there is a nice per-device royalty coming Sun's way.

Nandini Ramani showed off a nifty looking authoring tool for Java FX that is slated to be available by the end of the year.

Then there was a demo of the Java store, presented by James Gosling. The idea is that a developer can put an app on the store, turning the labor of love into day job. When I first heard about it, I was dubious, but I can see two advantages. (1) The “drag to install” feature is nicer than anything you can do on Windows today (2) The app store can automatically install new versions.

http://weblogs.java.net/blog/cayhorstmann/archive/larry-ellison.jpg

Most importantly, at the end of the keynote, Scott McNealy and Larry Ellison showed up. They said the usual things about not being able to say anything until the acquisition was completed, but then Larry said soothing words about being supportive of OpenOffice, Java FX, and Android-powered netbooks.

In the post-keynote press conference, someone asked why Java FX wasn't developed under the JCP. Good question, I thought. Jeet Kaul, a Sun executive said that the speed of innovation in this technology wasn't compatible with the JCP. Ouch.

I asked about the sorry state of Java ME/FX on cell phones. I was reminded that it takes a long time for phones to incorporate new technologies. Fair enough, but the showcase phone for Java FX (which you can buy on the show floor) is the HTC Diamond, running Wince. I think I'll pass.

In summary, this year's Java FX demos looked a lot better than last year's. I did come away with the impression that the renewed focus on the desktop was for real, and that Oracle might keep it going.

The Afternoon Keynote

In the afternoon, Bob Brewin hosted annoucements on the status of Java SE, EE, and FX. Mark Reinhold gave a nifty demo on managing modules in Java SE. He got a resounding applause when he said “the classpath is dead”. Roberto Chinnici demoed Glassfish v3 and got a round of well-deserved applause when he demoed “deploy on save”. If you have not experienced hot deploy of an EE app, you should really give Glassfish v3 a try. It is a game changer in terms of developer productivity.

I'll spare you the details about SOA and the app store.

Sessions

Joe Darcy talked about “project Coin” or small language changes in JDK 7. Properties, reification of generics, and closures are definitely out. They would impact too many parts of the JDK. He walked us through the many issues raised by the introduction of enum. Personally, I wasn't convinced that any of these issues were very complex. I keep complaining about issues with JSF 2.0, but those are an order of magnitude more complex than those mentioned in Joe's talk. Let's just say that the core team is very cautious. Among the features that we might see in JDK 7 are

  • multi-catch: try { ... } catch (Extype1 | Extype2 ex) { logger.log(ex); }
  • automatic resource management: try (Reader in = new FileReader("foo.txt")) { ... }
  • [] for array lists and maps
  • Collection literals
  • The “diamond” operator: Map<String, List<String>> anagrams = new HashMap<>();

Well, it's better than nothing, but I have come to realize that the Java language may well have reached the end of its evolution. For more fun/productivity, it may be best to look for other languages on the JVM. I attended the Clojure presentation. The software transactional memory feature is intriguing, but otherwise, I think I'll still consider Scala first.

I was on the “Tools and languages” selection committee again this year, where we reviewed about 500 proposals for technical sessions and BOFs. Many of them were excellent, and we could only accommodate a small fraction. Rather than filling the entire allotment with JRuby talks (←minor sarcasm here), I successfully lobbied for some of the more advanced topics, such as Michael Ernst's presentation on type checking annotations (JSR 308) and Phil Haller's work on Scala actors. I was very happy to see Michael's talk fill up with an attentive audience that asked lots of great questions.

Overall, for me, the highlight of the day was seeing Larry Ellison on the stage, appearing generally supportive of the entire breadth of the Java ecosystem.

Today is day 0 of Java One, AKA “Community One,” with a focus on open source and community projects. With the economy being what it is, and Java One stretching the definition of “early bird” specials past the breaking point—the discount was good until today—I was fearing for the worst, but there definitely were crowds today.

Here are some of my impressions from today.

http://weblogs.java.net/blog/cayhorstmann/archive/groovy.jpeg

Guillaume Laforge gave a nice presentation on what is new in Groovy 1.6. An expanded version of the talk is here. I was most impressed by the ability to manipulate abstract syntax trees. For example,

class Event {
    @Delegate Calendar when
    String title, url
}

All of Calendar's methods are added toEvent and delegate to the when object. In Java, this would be an absolute no-no. Annotations are not supposed to change the classes that are being annotated. But Groovy isn't Java, and in a more dynamic world, these transformations make perfect sense.

I really want to like Groovy, but what is holding me back is (a) the rather ad-hoc process in which Groovy rediscovers what has been known in other (mostly functional) languages for a long time and (b) the stubborn resistance to producing a language spec.

As for (a), consider the sections on ”multiple assignment” and “optional return for if/else and try/catch/finally blocks” in the InfoQ article. In Groovy, you can now write

def (a, b) = [1, 2]

What's with that mishmash of parentheses and brackets? In Scala, you'd write

val (a, b) = (1, 2)

That's because Scala—like so many of its predecessors—has tuples. And Scala—like so many of its predecessors—has conditional expressions that return values, without having to wait for version 1.6.

Perhaps I quibble. But the lack of a spec really bothers me. Suppose I add two @Delegate fields to a class. What happens if one method signature is shared by both delegates? I asked about the spec, and Guillaume's response was that a spec was not really needed. The Groovy API documentation is excellent, and there is an extensive set of test cases. (Note to self—check that out.) Well, the API documentation for @Delegateis here, and it doesn't seem to answer my question.

JSF 2.0 can work very nicely with Groovy, and I understand that the lack of a spec is making it difficult for the JSF spec to acknowledge that fact. Hopefully, one of these days, the Groovy folks will get around to a formal spec.

http://weblogs.java.net/blog/cayhorstmann/archive/seam.jpeg

Dan Allen gave a great presentation on running Seam on Glassfish, and what pitfalls one encounters. Mostly, the issues are JNDI naming, exploded WARs, and other distasteful topics. It all adds a dose of reality to app server portability.

Sharat Chander and someone who admitted to being in marketing talked about Project Kenai. David Geary and myself are hosting a project there for our Core JSF book. The site works just fine, but I never understood why it describes itself as “more than a forge”. The speakers were hinting at great things to come, in terms of continuous integration, testing, and deployment, so that will definitely be worth watching.

http://weblogs.java.net/blog/cayhorstmann/archive/alice.jpeg

I met up withDennis Cosgrove of alice.org at the show floor. If you haven't checked out Alice, do it now! It is a super-cool environment to teach programming to middle and high school kids. The new version—now in beta—has two enhancements. It has characters from the Sims that are a lot smoother than the old wireframes. And you can program in Netbeans, in addition to the Alice IDE. Next semester, I will try this out on freshman students, replacing the old “print all prime numbers <n” with problems that use the Alice cast of characters.

eeepc.jpeg

My favorite talk of the day was a “lightning talk” by Masafumi Ohtaon running OpenSolaris on an Eee PC. Now here is a true hacker. Apparently he even got Second Life running!

Finally, I stumbled into a “bring your own laptop” lab on the Eclipse Glassfish plugin, brought to you by Ludovic Champenois (AKA Ludo). I had used that plugin with good success, as did my software engineering students last semester. We used Java EE 6 + JSF 2.0 on Glassfish v3 with Eclipse, and it all worked out. Except, that there was some flakiness with the adapter. My students figured out how to solve this by downloading the Eclipse + adapter + JavaDB bundle that Ludo provides, but I stubbornly refused to do that and ran into grief when Glassfish v3 updated. It turns out that you need to manually check the update site for the plugin:

http://weblogs.java.net/blog/cayhorstmann/archive/plugin-not-checked.png

(It doesn't help that the update site is called https://ajax.dev.java.net/eclipse.)

When the Glassfish plugin broke for me, I had a miserable time testing my JSF 2.0 examples with Tomcat for the last several weeks. I look forward to going back to Glassfish! If you are still using Tomcat, you should really have another look at Glassfish or another app server.

This year, Sun has been very generous in admitting students to Java One for free. In fact, one of the lab participants who ran into trouble in that lab turned out to be one of my students—good choice on her part; she is starting a master's project using this stuff. I ended up being pressed into service with troubleshooting because she ran Linux. The issue was a space in a file name :-)

http://weblogs.java.net/blog/cayhorstmann/archive/cloud1.jpeg

This being day 0, I have no profound observations yet. There seems to be cautious optimism about EE 6, JSF 2.0 and even OpenSolaris and Java FX on the conference floor. Interestingly, I ran into a group of my students and asked where they were going. The cloud talks, duh.

http://weblogs.java.net/blog/cayhorstmann/archive/melon-collie1.jpgWhen I come across an article such as this one, I am overcome with melancholy. I really want to love JSF. Its heart is in the right place. It wants to let me drag and drop components onto a form, wire them up with JavaBeans, and give me AJAX with essentially no work on my part. And it comes so close.

Now, admittedly, I am biased. I am a co-author of the best-selling JSF book, with David Geary, published by Sun Press. I am making lots of pennies on the Safari page views and a few dollars from the hardy souls who, bless their hearts, still buy the paper version. But frankly, there are easier ways of making a buck than writing a JSF book. I wouldn't do it if I didn't think JSF was (or, at least could be) the cat's pajamas.

We all know that JSF is far from perfect. Too much stuff in the HTTP session. Component authoring is way too hard. A leaky abstraction. The stack trace from hell.

http://weblogs.java.net/blog/cayhorstmann/archive/dashboard.jpg

But what really bugs me is the overall lack of “fit and finish.” Sometimes, JSF feels like one of those lower end American cars that make up much of the rental car fleet. Cheap, mismatched buttons. Gaudy metallic plastic that comes off when you stare at it too hard.

Here is a random example, one of many:

JSF 2.0 has a new feature for locating resources. It's pretty nice. You dump images, CSS files, scripts, and so on, into subdirectories of a resources directory. Then you can write

<h:graphicImage library="images" name="myimage.png"/>

Or, as my coauthor inexplicably prefers,

<h:graphicImage value="#{resource['images:myimage.png']}"/>

As it happens, I have a command button with an image. Wanting to be thoroughly modern, I move the image to theresources directory. Oops,h:commandButton hasn't been fixed to havelibrary and name attributes. No problem:

<h:commandButton image="#{resource['images:myimage.png']}" .../>

Of course, it doesn't work. The value ofresource['images:myimage.png'] is/context-root/faces/javax.faces.resource/myimage.png?ln=images, which starts with a slash! (Can you hear the evil laughter in the background?)

The JSF 1.0 expert group had to worry about big and important things such as the pluggability of the state manager, and nobody paid much attention when h:graphicImage added the context root to an image URI and h:commandButtondidn't. The 1.2 expert group, focusing on lofty issues such as the ability to have multiple render kits in a single application, apparently had a few minutes to spare on a “solution”. Now h:commandButton prepends the context root if the image URI starts with a slash. So, I get/context-root/context-root/faces/javax.faces.resource/myimage.png?ln=images.

I know, it's no big thing, and I can work around it. It's just like that rattling piece of plastic in the rental car.

And I don't want to make fun of the JSF expert groups. They are very knowledgeable and have solved hard problems in constrained time frames.

My beef is with the process.

http://weblogs.java.net/blog/cayhorstmann/archive/evolution.jpeg

  • A JSR is formed
  • The expert group goes to work
  • An early draft and a reference implementation are posted to the public
  • The spec is incomprehensible to those who haven't participated in the discussions
  • With much effort, the early reference implementation can be coaxed into running some nifty examples
  • A few blogs appear
  • It becomes apparent that large parts of the promised deliverables are not yet specced or implemented
  • In a few short months, a very large amount of new technology is added to the public review draft
  • The spec is still largely incomprehensible
  • The reference implementation is getting almost usable
  • There are still important pieces missing that look pretty dicey to spec and implement
  • The expert group, in a burst of heroic action, provides most of the missing pieces and issues a proposed final draft.
  • The spec is still filled with gobbledygook, but it has become familiar gobbledygook
  • The reference implementation has become pretty stable
  • Bloggers, authors, tire kickers, and early adopters can finally make sense of the thing
  • The final draft is rubber-stamped
  • Lots of little “fit and finish” issues become apparent
  • None of them can get addressed because the spec is final
  • All behavior must now be preserved in the interest of backwards compatibility

With this process, cruft is bound to accumulate. JSF is not the only culprit. Apparently, all is not well in the land of servlets. And that's a much simpler spec.

I think the process needs a couple of tweaks

  • “Public review” should not be mere lip service. Give at least 6 months between issuing the proposed final draft and approval. Have a formal process for collecting input and responding to it.
  • There should be a process for cruft detection and removal in every update. Deprecate in version x + 1, remove in version x + 2.

Again, I don't want to bash JSF. There are lots of nifty things in JSF 2.0, and I see no really compelling alternative to it. (If there was, everyone would just flock to it instead of kvetching about JSF.) I just want more fit and finish in JSF 2.1 and 3.0.

http://weblogs.java.net/blog/cayhorstmann/archive/delphi-oracle.jpgAs everyone knows from yesterday morning's news, Oracle has made an offer to buy Sun Microsystems, Sun has accepted, and the acquisition is expected to go through by the summer.

The Java blogosphere seemed pretty happy when IBM was rumored to acquire Sun. IBM has made many contributions to the Java infrastructure, embraced open source well before Sun, and, with the release of Eclipse to a independent foundation, showed more confidence in open governance than Sun. Everyone expected them to be a good steward of Java. With Oracle, the mood seems less optimistic. Of course, Oracle has made contributions such as the EclipseLink JPA implementation and the Trinidad JSF library, but they pale in comparison with IBM. And some developers are clearly weirded out by Larry Ellison... http://weblogs.java.net/blog/cayhorstmann/archive/larry-ellison.jpg

There have been many questions and guesses what will happen to various pieces of Java and other open source technologies that Sun has. Here are my guesses. It will be interesting to come back in a year and see how many of these I called right, and where I was way off.

MySQL. There has been a lot of talk how this is surely the end of MySQL—Oracle will just let it wither on the vine or kill it outright. Well, I don't think so. Suppose someone can't use MySQL any longer. Would they say “aw shucks, then I'll just have to fork over the money for an Oracle database”? No, they'd first have a look at a MySQL fork or PostgreSQL. I think Oracle will be smart, keep MySQL as an entry level product, and use it to get consulting revenues and an upsell opportunity. MySQL actually seems a better match for Oracle than Sun because Sun never had that upsell opportunity.

Java 7. There have been grumblings that Sun is busy working on a JDK 7 without moving forward on a JSR for Java 7 because they don't want to get into a fight with IBM and Apache about TCK licensing. Will Oracle see the light, let Apache use the TCK, and then go back to using the JSR process, which despite its flaws is a lot more transparent than what is currently happening with JDK 7? I would like to see that happen, but I don't think so. Oracle just paid good money for the right to do whatever they want to do with Java, and I fear it will take some time until they understand that the best thing they can do is to let go.

Netbeans. Manypeople seem to think that Netbeans is a goner too. After all, Oracle has its own IDE, JDeveloper. Come on, people. Have you ever used JDeveloper??? I am sure Oracle realizes that developers have stayed away in droves, and that you can't force the unwilling to use it. If Netbeans were to die, Eclipse would be the winner, not JDeveloper. Instead, this is a golden chance for Oracle to get rid of the JDeveloper albatross and switch to Netbeans.

Glassfish. The conventional wisdom is that Oracle just paid a bundle for BEA, so they don't want Glassfish to succeed. I am not so sure. Oracle wants Java EE to succeed, and Glassfish is the reference implementation, so they can't very well ditch it. In the past, Glassfish acquired high-end features such as clustering, and I would expect that trend to stop. Still, it is in Oracle's interest that people use Glassfish and not JBoss for their entry-level Java EE projects, and I expect that it will remain a viable option.

JavaFX. I predict it won't survive. The beancounters will want to cut something, and this is the obvious candidate. It's not making money, it isn't making visible inroads against Flash or Silverlight, and in general Oracle doesn't have much interest in client-side software. I am not the only one with this brilliant insight, so if Oracle does intend to keep it going, they really need to make some reassuring announcement very, very soon. What worries me is the state of client-side Java in general. Sun has done a rather poor job with the thankless and expensive task of building a reliable Windows installer/updater. Is Oracle committed to putting more resourcees behind that effort? If not, the future for client-side Java is bleak.

OpenSolaris. Oracle has said that they want to integrate Solaris and the database products and deliver an integrated solution with hardware, OS, app server, and a database. Solaris makes a lot more sense for Oracle than for IBM. Do they want to keep it open? I am afraid it's not a high priority.

VirtualBox. Your guess is as good as mine. I really like VirtualBox, but I don't understand why Sun bought it in the first place.

OpenOffice. As an OpenOffice user, I am grateful to Sun for having it brought along this far. I hope it gets more love and attention in the future, but I see no reason why it should, except that Larry might want to spite Microsoft.

http://weblogs.java.net/blog/cayhorstmann/archive/bigj3.jpgI am currently revising my “Big Java” book, a college text for beginning computer science students. In the chapter on loops, I cover the whileloop and the for loop extensively, and then there is an “advanced topic” that briefly introduces thedo-while loop.

Why am I not keen on bigger coverage of thedo-while loop? First, do-while loops are quite rare in practice. Using a few grep statements, I get these statistics for the code that is distributed with JDK 6 in src.zip:

                      
for729771%
while276827%
do-while2372%

Here are the grep statements in case someone wants to improve on this:

grep -r -h "[^A-Za-z0-9]for (" . | grep -v "^[ ]*[*]"  | wc
grep -r -h "[^A-Za-z0-9]while (" . | grep -v "^[ ]*[*]"  | wc
grep -r -h "[^A-Za-z0-9]do {" . | grep -v "^[ ]*[*]"  | wc

As you can see, 98% of the loops are not do-whileloops.

Moreover, a do-while loop is obviously never required—a student can always write it as awhile loop with a boolean flag. For example,

boolean positive = false;
while (!positive)
{  
   System.out.print("Please enter a positive number: ");
   value = in.nextDouble();
   if (value > 0) positive = true;
}

instead of

do
{  
   System.out.print("Please enter a positive number: ");
   value = in.nextDouble(); 
}
while (value <= 0);

Is the first alternative that much worse?

http://weblogs.java.net/blog/cayhorstmann/archive/big-fish-fry.jpgI thought that downplaying the importance of the do-while loop helps instructors who have bigger fish to fry (such as how to turn a problem statement into a working loop, which is really hard for beginners). However, reviewers were not amused. One of the kinder comments: “This chapter would be vastly improved by moving the do-while into the main body of the text.”

That's indeed what other textbooks do. They give equal billing to each Java loop type. Here is a quote from one briskly selling text:

In general, a for loop may be used if the number of repetitions is known, as for example, when you need to print a message a hundred times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before the continuation condition is tested.

To paraphrase Truman Capote, that's not computer science—it's taxonomy.

(And it's bad taxonomy. Wouldn't “the case of reading the numbers until the input is 0” be one of the few cases where ado-while loop is a better choice?)

But, you may say, an employer wants to make sure that any student whom they hire can read a do-while loop when it does occur, and also write one when it is most appropriate.

I guess this gets to the heart of the difference between certification and education. In my loop chapter, I want to educate students to

  1. Implement loops from a given problem statement
  2. Learn minor technical minutiae on their own as needed

http://weblogs.java.net/blog/cayhorstmann/archive/certificate.jpgCertification, on the other hand, seems to be mostly concerned with those minor minutiae. Check out these sample questions. I don't see how this it is meaningful for hiring purposes. When I hire coders, erm, software engineers, I want to know whether they can solve problems, not whether they can memorize Java trivia.

Am I getting all worked up over nothing? I could just give in and turn the “advanced topic” into a regular section. Or should I stick to my guns? Please help me make up my mind by posting your thoughts!

When teaching unit testing in the context of a simple EJB3.1 application, I was looking for an easy way of testing managed beans and session beans inside Glassfish. Of course, one can test out-of-container or use an embedded container (but I didn't quite figure out how to do that with Glassfish v3—I'd appreciate hints), or a mock container (but that seemed to require a bit of setup).

I hit upon a scheme that I had not seen elsewhere: put the unit tests in the container and trigger them with a servlet that reports the outcomes. Advantages:

  1. There is very little setup to learn
  2. It is easy to run the tests from a browser
  3. The tests run in the exact same environment as your app
  4. No need to wait for container startup with every test. (This could also be a disadvantage because the database isn't in a pristine state at the beginning of each test.)

Here is how to do it.

Add the JUnit 4 JAR to WEB-INF/lib.

Add the following servlet to your WAR file:

package myapp.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.internal.JUnitSystem;
import org.junit.runner.JUnitCore;

public class TestServlet extends HttpServlet {   
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
       String className = request.getParameter("class");
       response.setContentType("text/plain");
       OutputStream out = response.getOutputStream();
       final PrintStream pout = new PrintStream(out);
       new JUnitCore().runMain(new JUnitSystem() {
         public PrintStream out() { return pout; }
         public void exit(int arg0) {}
       }, className);
       out.close();
   }
       
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
       doGet(request, response);
   }
}

Add the following entries to web.xml:

    <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>myapp.servlets.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>

Write your JUnit test case in the usual way. For example, here is a test for a session bean:

package myapp.session;

import static org.junit.Assert.assertEquals;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.junit.Before;
import org.junit.Test;

import myapp.entity.Person;

public class UserSBTest {
   private UserSB userSB;

   @Before public void init() throws NamingException {
      InitialContext context = new InitialContext();
      userSB = (UserSB) context.lookup("java:global/MyApp/UserSB");
   }
   
   @Test public void testAddUser() {
      Person p = new Person();
      p.setFirstName("Fred");
      p.setUsername("fred");
      userSB.save(p);
      Person q = userSB.find("fred");
      assertEquals(p.getFirstName(), q.getFirstName());
      userSB.removePerson("fred");
   }   
}

Unfortunately, you can't just have the container inject the session bean.

   @EJB private UserSB userSB; // Doesn't work when JUnit loads the class

When JUnit loads the class, it doesn't deal with EJB annotations.

Then point your browser tohttp://localhost:8080/MyApp/test?class=myapp.session.UserSBTest

unit-test-in-browser.png

Proverbial exercise to the reader: Add a green bar when the test cases pass.