Where Is Java Going to Go From Here?

Ever since I attended the NFJS Gateway Symposium almost 2 years ago, I’ve been hearing the same theme over and over:

Java is the new COBOL.

Everywhere you go, you can’t seem to avoid hearing this. An ex-coworker commented when I ran into him at Agile 2007: “I’m surprised you guys aren’t using JRuby.” Two sessions I attended there also had speakers throwing in a little rant that Java is a dinosaur that is going way. With all the new languages that can run on top of the JVM now, there has been a lot of fuss on what is going to become the next language of choice for Java developers.

DZone’s Steven Devijver is placing his bets on Groovy. This was brought up quite a bit at NFJS last year as well. It’s hard to argue against it… with JRuby, java developers have to learn a completely new language with different characteristics than what their used to, whereas Groovy combines the best of both worlds with all of the nice characteristics Ruby has (and more) as well as a familiar syntax… java code is completely valid in Groovy.

Scala has also captured my interest as of late and I really think that 2008 will be the year that it breaks into the mainstream (much like a year or two ago was for Groovy). Only time would tell I suppose… I like both languages so it is difficult to place any bets on which is going to become the new replacement for Java.

What do you think?

Extending Selenium Via Javascript

Looks like I’ve already accomplished one of my new year’s resolutions by doing some polygot programming at work today embedding javascript within java. And it happened completely by accident.

Lately we’ve had a handful of Selenium Remote Control based fitnesse fixtures crop up at work… there’s a nice generic one, and several custom ones designed to tackle specific front end domain problems. On our latest project we have your run of the mill tabbed layout, you know… click on tabs and and you see different content, nothing special. What made things interesting, however, is that marketing wanted to track some specific usage information when each tab is clicked. Fine enough, just whip up some ajax and register some event handlers for the click event, and we’re ready to go. Well, hold on… what about testing?

Everything on the server side was unit tested and functionally tested to a T… in fact I am rather proud of the partner I worked with and myself on how well the tests are written and how many scenarios are covered. However, I still wanted to test the front end… I want to be sure that each time someone promotes, they didn’t do something to, as our team’s QA member would say, “jack it up.”

So I quickly wrote some selenium tests in fitnesse (note: this violates everything I believe FIT should be for, but fitneese is a convenient poor man’s application server) to get to the vehicle history report and test it. Speed bump number one. The interface that lets users run reports uses a target attribute on the form to open the report in a new window, and apparently selenium can’t focus on a window unless you explicitly use window.open to open the window. Drats… foiled. Or was I?

After a bit of searching, I found out that selenium remote control has a method called getEval that will simply evaluate any javascript you pass into it, which is handy for checking variable values for example. From there, you can access the runner via this.browserbot, which provides a whole slew of awesome commands you can use for manipulating the runner, including accessing the current window. And that’s where it sinks in… I can do anything in the world (almost) with javascript, and if I can access the window, I can make things happen. Bypassing the earlier speed bump was a simple matter of opening a new window with the same name as the target, and then focusing on it once the form is submitted. Piece of cake.

Since we have a lot of forms like this, I wrote a simple script to open new windows for any forms with a target on it using the name of the target, and wrapped in a java method. So that was step one… I now had a java method in a fitnesse fixture with javascript code inside a string indented all nicely… and evaluated on demand.

Now. at the new tabbed page is where things got immensely interesting… I wanted to intercept xmlHttpRequest calls, capture them, and be able to access them later. Redefining jQuery’s XHR methods were a piece of cake, the code was something like this (and whipped up in about 5 seconds):

var _d = this.browserbot._caughtValues = []
this.browserbot.getCurrentWindow().jQuery.post = function(a,b,c){
	_d[_d.length] = b;
}

the second parameter here was the data packet being passed in, which is what I was interested in the most. Different meta data is fired off on different tab clicks.

Then topping this off was a simple matter. I created a method that would return a ListFixture (because I wanted to loop over the meta-data packets in the order they were fired, and also because it is vastly supperior to RowFixture) and got to work scraping the values out, which became a mix of BOTH java and js, together.

Building a list of java objects from the captured values was a matter of:

  1. Getting the length of the _caughtValues array and converting it to a java int (getEval only returns strings)
  2. iterate a number of times equal to the length to visit each value on the array
  3. do an eval against _caughtValues with an index specified to get the json packet:
    String packet = getSelenium().getEval("this.browserbot._caughtValues["+index+"]");
                   
  4. parse it into a java.util.Map by making a call to a nice JSON parsing library
  5. populate a java object representing the packet with the map, add it to a list, and return a new ListFixture containing that list.

I wrestled a little to get it work, but I’ll have to admit it felt oddly great when I saw the table of expected packets light up green… and then red for the last 4 rows (good to know it was able to catch the invalid packets). There’s also a sense of joy in seeing it run consistently… for a session it worked, but would randomly fail.

It’s pretty interesting, but I think my coworkers might hate me for the embedded javascript code inside of java. So far they either think it’s really cool, or really insane. ;)

Making extJS More Accessible to Java Developers

With my recent interest in extjs, I was playing with the idea of making a Struts2/WebWork component library or a tag library to handle a lot of the boilerplate extjs code (i.e. creating layouts and such) but, luckily, discovered someone beat me to the punch!

I randomly came across ExtTLD this morning while sifting through my rss feeds, and I must say I am rather impressed. Although I consider myself a pretty good javascript developer, there seems to be a lot of java developers who aren’t that hot at javascript… which is why whenever I attend any java related conference there is always several sessions touting “javascript free ajax!” frameworks like GWT, Ajax4JSF, or IceFaces. Although I’ve always been skeptical of such frameworks, I do see their benefits… especially for the java developer who excels at serverside JEE development but generally sucks when it comes to adding javascript behavior to the presentation layer.

So far it looks good, but I haven’t had a chance to play with it yet. Basically, I’ll have to see if it passes my “good javascript generator framework” test. I’m a pretty staunch advocate of unobtrusive javascript, and generally hate any presentation layer framework that seeks to dump several hundred (or thousand) lines of javascript inline in the html document. This is the reason I totally hate Struts 1′s client side validation plugin.

Using AOP for Measuring Elapsed Time

Recently I’ve been knee deep in some legacy code doing a fair bit of refactoring, and one of the patterns I keep coming across is processes that need their elapsed time measured. You know what I’m talking about… a procedural mess shock full of primitive obsession all over, something like the following (except imagine that the for loop is some time intensive process):

public class TimeWaster {

	public SomeResponse makeLongRequest(){
		long start = System.currentTimeMillis();
		for(long i = 0L; i < 200000000L;i++);
		SomeResponse resp = new SomeResponse("FOO");
		long end = System.currentTimeMillis();
		resp.setElapsedTime(end - start);
		return resp;
	}
}

Of course, the knee jerk response will be to hide the primitive long values manipulated all over behind some kind of abstraction, such as:

	private static final StopWatch TIMER = new StopWatch();
	
	public SomeResponse makeLongRequest(){
		TIMER.start();
		for(long i = 0L; i < 200000000L;i++);
		SomeResponse resp = new SomeResponse("FOO");
		TIMER.stop();
		resp.setElapsedTime(TIMER.getTime());
		return resp;
	}

A little better... but there's still something fishy here... why does my class (despite the fact I selected the random name of timewaster) need to know about a timer? It has two roles now... generating the SomeResponse (again, remember the for loop is an assumed time intensive process of generating SomeResponse) and timing the time it takes to generate that response.

To solve this problem, we can move the timing process to an aspect, measuring the execution of the makeLongRequest using an around advice, which allows us to invoke the target method as well as modify any input and output values before returning (this is also ideal for contraint checking). So to begin, and especially since aspects can be a little tricky, we construct a very simple aspect... containing only a pointcut and a sysout in an after advice (which is called after the method finishes):

public aspect TimeWasterTimer {
	pointcut makeCall(): call(SomeResponse TimeWaster.makeLongRequest());
	
	after(): makeCall(){
		System.out.println("Pointcut worked..");
	}
}

I run the tests and see that yep.... that worked. So, to start small, we'll make an around advice that simply returns the return value and run the tests to make sure they pass.

public aspect TimeWasterTimer {
	pointcut makeCall(): call(SomeResponse TimeWaster.makeLongRequest());
	
	SomeResponse around():makeCall(){
		SomeResponse resp = proceed();
		return resp;
	}
}

Tests pass, so let's remove the timing code completely and run tests.

public class TimeWaster {
	public SomeResponse makeLongRequest(){
		for(long i = 0L; i < 200000000L;i++);
		return new SomeResponse("FOO");
	}
}

Now all of our tests related to elapsed time fail... perfect. Now to finish things off, we simply move the timing code to the aspect and set the elapsed time on the response before it's returned.

public aspect TimeWasterTimer {
	private static final StopWatch TIMER = new StopWatch();

	pointcut makeCall(): call(SomeResponse TimeWaster.makeLongRequest());
	
	SomeResponse around():makeCall(){
		TIMER.start();
		SomeResponse resp = proceed();
		TIMER.stop();
		resp.setElapsedTime(TIMER.getTime());
		return resp;
	}
}

Rerun tests, and everything is green. Sweet! ;)

In this case, we were able to split out the responsibility of measuring execution time to a separate module by using an Aspect, allowing for a better separation of concerns. We could take this a step further an make it generic enough to be used in all cases that elapsed time is measured, perhaps by having an interface for classes that record elapsed time and a pointcut with some complex joinpoint matching magic. I'd also be interested in any alternative solutions others have come up with to solve this problem (I know Spring AOP is another way of tackling it).

Stay turned for more posts on Aspect Oriented Programming. :-P

Iterative SAX Parsing

Today I’ve spent my personal development time writing a sax parser that allows iterative parsing, stoppping on a specified “stop tag” for each iteration, and uses an Iterator interface. The power is the custom handler that uses closures to implement callbacks on each node encounter, and in future work on it I hope to get it to the point that one can simply call next() on the iterator and get the custom object they just built. This is just a starting point, but there’s a lot of room for improvement (XPATH FILTERING!!!):

Disclaimer: the data (and format) is made up. It’s not from work. ;)

The XML:

<?xml version="1.0"?>
<records>
	<record type="stolen">
		<vin>SDC3ER4320RMT5321</vin>
		<name>James Carr</name>
	</record>
	<record type="maint">
		<vin>RGGHWERTGBWERGBQE23R</vin>
		<name>Som Won</name>
	</record>
	<record type="sold">
		<vin>24werf34g34gqe4rgq</vin>
		<name>Das Boot</name>
	</record>
</records>

Setting a simple string:

 public void testElementEncounterCallbackSetName() throws SAXException, IOException{
      parser = (PullSaxParser) XMLReaderFactory.createXMLReader("org.jamescarr.parsers.PullSaxParser");
      handler = new ClosureContentHandler();
      parser.setContentHandler(handler);
      parser.iterateOn("record");
      handler.onElement("name", new Closure<SimpleNode>(){
         public void execute(SimpleNode arg) {
            name = arg.getValue();
         }
      });
      parser.parse(getInputSourceFromString(XML_STRING_OF_THREE_RECORDS));


      Iterator iter = parser.iterator();
      assertEquals("", name);
      iter.next();
      assertEquals("James Carr", name);
      iter.next();
      assertEquals("Som Won", name);
      iter.next();
      assertEquals("Das Boot", name);
   }

Constructing an object:

 int i = 1000;
   public void testConstructRecordObjectFromEachElement() throws IOException, SAXException{
      parser = (PullSaxParser) XMLReaderFactory.createXMLReader("org.jamescarr.parsers.PullSaxParser");
      handler = new ClosureContentHandler();
      parser.setContentHandler(handler);
      parser.iterateOn("record");
      
      
      handler.onElementStart("record", new Closure<SimpleNode>(){
         public void execute(SimpleNode arg) {
            record = new CustomerRecord(++i);
            record.setType(arg.getAttribute("type"));
         }
      }).onElement("name", new Closure<SimpleNode>(){
         public void execute(SimpleNode arg) {
            record.setName(arg.getValue());
         }
      }).onElement("vin", new Closure<SimpleNode>(){
         public void execute(SimpleNode arg) {
            record.setVin(arg.getValue());
         }
      });
      
      
      
      /// start
      assertNull(record);
      parser.parse(getInputSourceFromString(XML_STRING_OF_THREE_RECORDS));
      Iterator iter = parser.iterator();

      iter.next();
      assertEquals(1001, record.getId());
      assertEquals("James Carr", record.getName());
      assertEquals("stolen", record.getType());
      assertEquals("SDC3ER4320RMT5321", record.getVin());

      iter.next();
      assertEquals(1002, record.getId());
      assertEquals("Som Won", record.getName());
      assertEquals("maint", record.getType());
      assertEquals("RGGHWERTGBWERGBQE23R", record.getVin());

   }

Using Value Objects in Fitnesse With Nested Tables

Today I discovered something rather cool while playing with FitLibrary. Not only can you just pass primitive types to fixtures, you can also pass in value objects as well (at least in DoFixture) by using nested tables.

Nested tables work pretty interesting, and I couldn’t really find much documentation on it outside of a scant bit on the fitnesse mailing list and what I was able to figure out by fiddling around. To start things off, I thought I’d show off an example I have while putting together an Email Fixture for checking emails in a mail box. In this particular case, this is a portion that sends an email for the fit test for the fixture. Below is what the table with the nested table looks like:

To do this, you have to assign the nested table to a variable, then simply reference the variable within the table.


!define inner_table (|subject|This is a test|
|type|text/plain|
|body|some content|
)

|Email Accessor|
|connect to|*****|using password|test123|on server|example.com|
|check for|0|messages with subject|This is a test|
|send email|${inner_table}|
|disconnect|

The code for the EmailAccessor is simple... simply extend a DoFixture and have a method called sendEmail which takes an argument (in our case, of type EmailMessage):


public class EmailAccessor extends DoFixture{
   ...
   public void sendEmail(EmailMessage message){
      this.box.send(message);
   }

Now, how does the inner table map to the domain object it represents? The values in the first column map to setters, with the values in the second or further columns as parameters. Below is the relevant method signatures for EmailMessage:


public class EmailMessage{
	...
	public void setType(String type){
	...
	}
	public void setSubject(String subject){
	...
	}
	public void setBody(String body){
	...
	}
}

You can even use nested tables within nested tables to map to domain objets for arguments to other domain objects, although it may look a bit complicated at that point. It worked well on a personal project I did some time ago however as the documentation for a standard I was implementing contained a set of nested tables that outlined the message format. ;)

SSH Over Java

Recently I’ve had the need from java to run a job on a remote server that can take a variable amount of time (anywhere from a few seconds to a few hours) and needed to detect when it is complete and get a file it generated when completed. This was a little challanging at first, as I had never used ssh from java, but I knew a little searching would yield results.

After a little searching, I found Java Secure Channel (JSch), a handy library with a BSD license and used in Ant and eclipse. The only sad thing is that there is zero documentation outside of a few examples, and my knowledge of streams (specifically PipedInputStream) was sorely behind as I hadn’t used them directly, since, well, college.

A little confusion abounded for awhile … how the heck am I supposed to detect the end of data coming over a pipe!? I mean, you can detect when it closes, but in my case I want to stay connected and issue more commands and close when I please, which means I cannot simply detect when the pipe is closed.

I struggled for a bit, then decided … I’ll just append ” && echo ” and read until I see that token, escape, remove the token, and return the data. So I wrote a small and dirty SshClient class that would allow me to send and recieve responses. The send method simply added the appropriate marker and saves the command so that it knows to strip it from the response:

public void send(String command) throws IOException {
		command += " && echo \"" + TERMINATOR + "\"\n";
		toServer.write(command.getBytes());
		lastCommand = new String(command);
	}

Getting the server response was a bit tricky. Since the command shows up when reading from the server, I need to detect the 2nd time it shows up and break out of the loop on that. After a little time I hacked up the following:

public String getServerResponse() throws IOException, InterruptedException {
		StringBuilder builder = new StringBuilder();
		int count = 0;
		String line = "";
		for (int i = 0; true; i++) {
			
			line = fromServer.readLine();
			builder.append(line).append("\n");
			if (line.contains(TERMINATOR) && (++count > 1)) {
				
				break;
			}

		}
		String result = builder.toString();
		
		
		int beginIndex = result.indexOf(TERMINATOR+"\"") + ((TERMINATOR+"\"").length());
		result = result.substring(beginIndex);
		return result.replaceAll(escape(TERMINATOR), "").trim();
	}

This makes so many assumptions, but I guess that as I keep working on it I can find a better way. Anyway, below is the final result of the SshClient class I came up with:
Continue reading

Comparable and Comparator

Wow. Every now and then when you think you know everything something just pops up and suprises you. I’ve recently been studying to take the Sun Certified Programmer certification exam and, even though I thought I knew enough to just go in and take the exam, I decided to go ahead and spend 25 bucks and buy a study guide off of amazon.

Although at first it was a light read, and I find myself skimming sections, I keep coming across interesting and useful features of the language I was unaware of, and sometimes even find myself kicking myself when I realize I came up with half assed solutions that the Java API already solves.

The most interesting features I came across so far were the Comparable and Comparator interfaces. Sure they’re simple, and braindead obvious to use, but I never knew of them before, but I’m glad I do now.

Continue reading