Junit’s Theory’s as interprested by Schauderhaft and Groovy

JUnit theories sound promising.  Many a time a developer writes a whole lot of @Tests along the lines of testParameterXzero(), testParameterXone(), testParameterXmaxInt(). The test code may be almost identical apart from the parameters being used in the class/method under test which is redundant and prone to error.

Theories offer a sound alternate, specifying a single test method, with a different set of annotations to the regular @Test defining a field or annotation based ParameterSupplier to inject a series of values into each test.

Schauderhaft’s blog provides a great summary of what theories are and how to write a parameter supplier to supply a series of datapoints in Java. The annotation based ParameterSupplier does look a little verbose but as Schauderhaft points out, they can be reused – annotation based data fixtures – excellent. I liked these two posts because they do a better job at explaining than the release notes. The blog also links to a blog about another Junit4 feature – parameterised tests – that seem to be a precursor to Theories, and a little simpler to setup. Another great source of how to use Theories is actually in the Groovy documentation about Junit integration. Closures make Datapoints a little more concise (or maybe the example is just simpler? hehe) along with the fact that test data (lists,maps) have a groovy conciseness to them to begin with.

JavaFX Charts

JavaFX has some pretty charts in the latest 1.2 SDK.  This post has a general overview, including the javafx.scene.chart class hierarchy and a great demo of all the charts with an excellent click transition.

image image  image

1d vs 2d (Pies vs Everything Else)

Well lets go 1d, a pie chart.  The series of data that fits a pie chart is just a pie label and its value

   1: def pieChart = PieChart {

   2:     title: "Sample Pie"

   3:     data: [

   4:         PieChart.Data { label: "Apples" value: 34  }

   5:         PieChart.Data { label: "Oranges" value: 27 }

   6:         PieChart.Data { label: "Bananas" value: 16 }

   7:         PieChart.Data { label: "Grapes" value: 50 }

   8:         PieChart.Data { label: "Cherries" value: 6 }

   9:         PieChart.Data { label: "Raspberry" value: 7 }

  10:     ]

  11: }

Code snippet taken from How do I create charts and graphs? – not much of a tutorial, but a link to some better references later.

The most important thing is that most charts, with the exception of the pie chart, inherit from XYChart. 

This means that while you may think a simple Bar Chart is just a series of Y values, its actually a bunch (series) of X categories with a complimentary data series (or two or three or more) plotted against those category values.  In the below example are 5 x-categories, with three data series (each a different colour)

image

I would think there should be a SimpleBarChart which only takes one data series and has an interface more like a pie chart, I think it would be a fun exercise as a JavaFX student to roll your own, extend chart, perhaps use Mixins of various pie-chart features (if possible)

The concept of two axis lends itself better to line charts where you are plotting anywhere in the XY space that is allowed.

BarChart Gotchas

Its not as automatic as you’d like.  The BarChart wouldn’t display until I defined my XCategories and set my Y limits (valueAxis). 

   1: BarChart {

   2:     categoryAxis: CategoryAxis {

   3:         categories: ["Child", "Teen", "Peaking", "Middle-Aged", "Grand-parenting", "Refined"]

   4:     }

   5:     valueAxis: NumberAxis {

   6:         lowerBound: 0

   7:         upperBound: 80

   8:         tickUnit: 10

   9:         label: "Age"

  10:     }

It would be nice in future to have an auto-resize=true flag which does as much magic as the proportional: true flag in the LinearGradient class.

Setting Data in Bar Charts

Order is important in the series, as you add a datapoint to the series, it gets assigned in a Bar Chart to the first item in the categories above.

Although a category field exists in the Data item, it doesn’t correlate to the category in the X-axis above.

   1: data: [BarChart.Series {

   2:         name: "The series",

   3:         data: [

   4:             BarChart.Data {category: "Child", value: 10},

   5:             BarChart.Data {category: "Refined", value: 80},

   6:             BarChart.Data {category: "Peaking", value: 25},

   7:             BarChart.Data {category: "Middle-Aged", value: 40}

   8:             BarChart.Data {category: "Grand-parenting", value:60}

   9:             BarChart.Data {category: "Teen", value:16}

  10:         ]}

  11:      ]

image

The data follows the order of the series, the category in the BarChart.Data literal is ignored – likely used for a different purpose :)  Note to self, RTM (or perhaps file a bug, what I read in the API sounds like I’m doing it right?)

BarChartSimple.fx

Binding the data to a variable

The bar charts data and categories can be bound to another variable, and the variable updated by something else.  In the below code I was able to add an onMouseClicked event to the bar chart so that when the series title or one of the existing bars were clicked, an additional category and random value data point where added to the chart.

BarChartBind.fx

Other Intro’s to JavaFX Charts

Creating XYCharts in JavaFX – The continuation of Dean Iverson’s blog about how to do each of the XY Charts, nice use of the for loop function to prepare the chart data.

Animated Bar Charts – Sexy way to dress up the bars with Fills (gradients or different coloured paints for the bars) and KeyFrames to animate them

What’s New In JavaFX 1.2 Technology: JavaFX Charts – The most detailed blog entry I found about charts from Sun/Oracle so far.  It actually went in depth to all chart types quite well and covered feeding in data from an RSS feed for a stock graph application

Paul Bakker

JavaFX Folder Visualiser – Using BackgroundTasks to update a folder pie chart view

JavaFX Charts – A great rundown of all the chart types with their usage

Interactivity with Web Services

So what about interactivity?  Live feeds from RESTful services are done with the HTTPRequest, then invoking a PullParser on it.  The ShoppingMashup is the first simple example of this, but its real simple and doesnt get too much into the how.

The first thing I had to do though was learn how to use Web Services in WS.  Not wanting to go too off topic, there is a HTTPRequest and a PullParser.  The PullParser does the work of reading an input stream from the HTTPRequest and processing a JSON or XML request.  My issue with it just seems to be the way that you access the XPath or JSON data.  I would have liked a more concise interface, too many if START_ARRAY_ELEMENT, if END_VALUE to make it feel testable.  And you can’t use the same uniform interface to read a JSON resource as you do an XML one.  No where near as simple as what you can get through Grails. I’ll elaborate in a future post.

The best examples to help me get started on a JSON feed though was Coffee Shop, in particular JSONPullParser.fx.  Other tutorials for talking to RESTful service that may help: JavaFX RESTful Web Services Invocation (using XML to talk to a home grown feed), pet catalog javafx example application and JavaFX Twitter Client – all referenced from Connect to a web service or RSS feed on the JavaFX Learn page

See TwitterTrend.fx and TwitterTrendClient.fx

My next TODO is to poll a few days worth of twitter trends and graph them.  And since this post has gone on long enough, I’ll defer that to my next one 🙂

Sharing an IntelliJ project via VCS

I found this post Sharing IntelliJ IDEA Project Files in Version Control via the twitter-sphere. 

They talk of all the usual stuff like ignore the iws file, but they introduced a neat trick for project variables which I didn’t know about.

If you edit your ipr or iml files, you can replace values with the text $whatever_project_var_you_please$ and then when someone else checks out the project and doesn’t have the vars set, a Configure Path Variables dialog pops up and asks you to set them.

I’ll be keen to give this a try at work as we recently switched from .ipr to the .idea dir format to avoid some conflicts we’ve been having, but I suspect that doing so is not the silver bullet alone, the above tip may help – by replacing what varies and let the devs set variables locally.

The next questions to ask is how this gets handled by Teamcity (I presume there are some system properties that you set in the team city project) and how in Idea, you can change these project variables.  But otherwise its a very neat tip.

Edit: To change these vars, I believe you can simply go into the File->Settings->Path Variables … Simple

Netbeans JavaFX plugin experience – and what about IntelliJ Idea?

Warning: Many of the following criticisms are superficial, but I wanted to document my experience of learning a new IDE.  I’ll come back to this post in a year to see what’s changed.

I should also state, I’ve got nothing against the Netbeans editor itself, and respect how it is able to support all the new Java platforms and standards in line with their release to the public.  Because of this, it’s as easy to adopt a new sun-backed Java platform enhancement as it is in the .net world, and the support provided makes it easy to learn new Java technologies in both regular desktop and enterprise space.

So now for the whinge:

Trying out Netbeans 6.8 and its best of class JavaFx support left me a little disappointed.  Following the JFX tutorials was ok, but copying the code from the tutorial into the IDE was a little frustrating since the formatting would be all screwed up.  Organise Imports (CTRL+SHIFT+I) plus Format Source (ALT+SHIFT+F) become my new best friends.  Maybe its because I’m trying in a new IDE, but I dont remember having to do these things with Idea, imports would resolve (or prompt for resolve) on paste, and formatting would normally match the target source.  (I’m a spoilt IDE brat, lol)

The JavaFX palette left me wanting as well.  Sure I could drag and drop a template from the palette into my code, but like the copy and paste, it didn’t respect the formatting of my code.  Sure once the template was there, I could tab b/ween the fields within the object literal, but my first instinct is to make the code pretty and doing a Format Source.  Doing so meant that I could no longer tab between the elements.

It would be nice to have a visual guide as to where in the code you could drop a said palette template into (perhaps highlight code blocks yellow if it was within a content or def assignment, but orange if it was somewhere else in the scenegraph it didnt make sense).  This is because if you put the item in the wrong place, you have to spend a minute figuring out the order of ] and } in order to get a compiler fx class again.  The scenegraph should make it easy to identify which element belongs to what, but its easy to miss a line.

I’d also like to see elements which took a sequence (like content) but only had one element assigned to them (eg content: Rectangle { … }), become a group or a sequence automatically when items were dragged into them.  (eg: content: [ Rectange { … }, Circle { // i just added this } ]

I also found that CTRL+Space within an object literal to find the other properties didnt always seem to work.  As I got more experience with the IDE, I found this happening less.  I think the problem could have been to dragging and dropping in the wrong place, as soon as you have a syntax error in your code, the intellisense isn’t going to work, regardless if your CTRL+Space is just within the braces of the object literal.

Also in Netbeans, a lot of refactoring functions were neutered. Options like Move or Copy class or even create a variable (ALT+SHIFT+V) would prompt they didn’t work in the context of the file type.  Doing a block comment using the default comment keyboard shortcut (CTRL+SHIFT+C) didnt work, and its menu option under Format was greyed out, but you could press CTRL+I, type comment and select Toggle Comment for it to work there.  Strange.

End whinge

To Netbeans credit, the JavaFX preview is a great feature to help pick up the language, and of course the different profiles (Desktop, Common, Mobile) along with the integration with the the emulator is excellent.  The above things are pretty superficial and since Netbeans has the jump on the other IDE’s, will probably get around to addressing those other concerns later as the platform is adopted by more devs in future.

Many of the above criticisms are borne out of wanting more refactoring options and polyglot support like I’m used to in IntelliJ.  At present IntelliJ offers a mere syntax highlighting when opening Fx files, but thats about it.  What I’m really waiting for is the super refactoring options when working with a project that has Scala, Groovy and other facets.  As well as just being able to use the refactoring options that I’m used to (eg rename a var/class in java, and refs in the Groovy and scala get changed too).  However, those things aren’t automatic in IntelliJ, I appreciate those refactoring features would have to be developed specifically for JFX, just as they have been for Groovy and Scala.  The list of refactorings isn’t as wide as the java ones.

IntelliJ Idea

So what else can you do to get some java fx love in IntelliJ?  At present not much, you can compile & run JavaFX using Intellij using the External Tools function or by using the ant script as specified in the link.

There was a JavaFX plugin that was being developed by Brian Goetz back in 2008 but word on this has gone quiet.  In 2009 a blog was started by someone about writing a JFX plugin for idea but this too has gone quiet.

So its a case of watch this space.

Pair Programming and Programmer Psychology

This is a great article in the IEEE Software journal looking at why pair programming does and doesn’t work and why it should or shouldn’t work.

In fact the article doesn’t have all that much to do with pair programming but looks at how developers work with each other. The article sites 4 mechanisms where pairing can have influence.

For example, the great scenario whereby describing a problem to an ‘expert’ colleague helps you find the answer, even if the colleague has little idea about the problem or the domain to begin with.  This reminds me of the Code Consultant plugin for IntelliJ Idea. 

Or when someone misses an error right in front of them (inattentional blindness), a pair can pick up the error.  The old psych lab of Did you notice the woman dressed as a 400 pound gorilla in the picture the second time around?

The article talks about how pairs can help keep each other using proper development patterns over change, compile, run, fail, change something else, compile, hope for change loop that beginners use when they first start developing. 

Finally, the article talks about how having a pair helps get a view of your own self since developers working solely don’t usually have their techniques reviewed critically and often, working with a pair also enforces them to do some introspection.  A yard-stick?  People who don’t pair are less likely to do this, and the article sites the scenario where job applicants who claim to know something, get stuck when it comes to explaining these things in practise.

Overall, I think it was a good article, not because it was talking about pairing, but more because it highlighted the tribulations of everyday developers, and how pairing could help or detract as an afterthought.

Multiple Inheritance in Java

This is something that’s usually taught to first year Java students.  Though I had a small mental blank about how it was implemented. I knew that to get around the ‘limitation’*, you could specify a class with multiple interfaces, but that was only half the solution. What about the implementation?

Surprisingly it was hard to get a clear answer from the fractal patterns that Google found, a lot of developers saying, “oh yeah, you need interfaces” but it didn’t sound like they knew themselves.

So, this was my way, probably duplicated a zillion times, but here you go, here’s a way:

We are going to have three classes, A, B & C (sorry for the lack of imaginative names here).  Class C will extend both A & B.  We’ll extra interfaces for A & B dubbed Ai & Bi respectively.

First an interface for the classes we are going to ‘extend’ from.

   1: public interface Ai {

   2:     public void aMethod();

   3: }

   1: public interface Bi {

   2:     public void bMethod();

   3: }

and now some implementation:

   1: public class A implements Ai {

   2:  

   3:     public void aMethod() {

   4:         System.out.println("aMethod");

   5:     }

   6:     

   7: }

   1: public class B implements Bi {

   2:     public void bMethod() {

   3:         System.out.println("bMethod");

   4:     }   

   5: }

And now for our binding class, C.  The class implements both interfaces, and takes in implementations of each of the super-classes as constructor arguments. The implementations of each method defined in the A and B interface is a delegate to the relevant A or B class that was injected in the constructor.

   1: public class C implements Ai, Bi {

   2:     private final Ai a;

   3:     private final Bi b;

   4:     

   5:     public C(Ai a, Bi b) {

   6:         this.a = a;

   7:         this.b = b;

   8:     }

   9:  

  10:     public void aMethod() {

  11:         a.aMethod();

  12:     }

  13:  

  14:     public void bMethod() {

  15:         b.bMethod();

  16:     }

  17: }

The call to the implementing a.aMethod() is effectively a super() call.  You can then append your own extra implementation, or remove the delegating call and define your own.

So what about the diamond problem, when both A & B define a method that is named that same thing.  In Java if you try to say a class implements interfaces that have duplicate signatures you’ll get a compile time error.  If Ai and Bi both had a method called cMethod() then the C class would refuse to compile.

Other ways

My research found other mentions.  If you got lazy, you could have C extend A, and implement Bi.  Then you wouldn’t have to write the interface Ai and C would be a little smaller since it would only inject the B implementation and have a bMethod() delegate.

Another way was to have the 2nd class as a static inner class.  Although I have no issue with this implementation working, as soon as I see ‘inner’, I’m led to believe its re-use value becomes a bit more limited and certainly more cumbersome to refer to.

Notes

BTW, if you want to find a decent explanation of what to do and an interesting reading of a Mixin pattern implemented in Java, then see here.

* I say ‘limitation’ in quotes because apart from the well known diamond inheritance problem that crops up with multiple inheritance in C++, from what I read, using multiple inheritance could be a code smell.  Certainly the ambiguity that comes from not knowing exactly which one will be called or whether or not you’ll know at compile time, or run-time is a concern.  (Don’t delay the Bad-news)

Inline Java In Perl

A former perl guru colleague of mine showed me Inline::Java, a way to embed Java in your perl programs and call perl from your Java classes.

The way it works is it invokes javac and creates some bytecode.  It then runs its own perl mapper (reflecting on said bytecode) so that the Perl code can use the Java public methods and attributes.

If you reference a java package outside the scope of your code (eg java.util or your own packages in a separate jar), then this module will also reflect those too.  You can specify a CLASSPATH environment variable so it knows where to look for these jars.

According to the bugs db there weren’t too many though how active the project still is remains to be seen.  Apparently the implementation can be a bit slow but there is a JNI option to speed things up.  I also suspect there is some problem with more unique java properties, apparently the module balks when it tries to see the Oracle 10 JDBC driver jar because of a public synchronized property.

Regardless if you’ve got Perl code that you want to migrate to Java, this would be a nice first step to bridge the gap.

See these sub modules for more info on how you can bridge the gap from the Java side

Inline::Java::Callback, Inline::Java::PerlNatives, Inline::Java::PerlInterpreter

Based on this, the equally cool, Java::Swing project emerged which leverages on the above.

Java Application Examples Blog

Ok, so I went to uni, and in uni they are big about plagiarism.  Not big in the sense they promote it, but big in that if you do it, you may as well consider yourself chemically castrated with no hope for a career in <chosen field> or especially academia ever again.

Uni made me wary of copying work.  It frustrated me to see other students copy assignments the night before something was due.  If you weren’t working something out yourself, you were missing out on the richness of the experience of, well, learning what the assignment was supposed to teach you. 

All this, work it out yourself, got turned on its head when I entered the professional programmer world.  Mentors advised to read as many code samples as possible, it will help you learn.  And whilst code samples aren’t necessarily cheating, and using this code in your own work provided you cite it and the license permits, should also be ok, it took a long time to get away from the stigma obtained during my time at uni…. which really when you think about people who further their academic careers by way of research papers that require you to reference other peoples work, is a really dumb stigma to get across.  I put it down to the plagiarism fear engulfing what should be best practice in normal circumstances.

So with that guilt trip swept away, there was a great blog: Top 5 Websites for Java Application Examples which referenced Java2s, Java DB, and Java Galaxy.  All sites that have come up in my Google searches before when I’ve lapsed my memory and forgotten the trivial convert something to a byte array or whatever other simplistic, seldom used, grassroots technique.

Whilst you cant be taught on these alone, the fact that they support you when you are the most stressed and your memory works its least efficient means I have no problem in recommending these sites 🙂

Building Java Applications with Windows Azure

Looking for a place to host my own home grown apps, I came across an interesting presentation about using Windows Azure cloud to run Tomcat and a JVM in the Microsoft cloud solution. See Building Java Applications with Windows Azure

The presentation basically says Azure can run any native code, which means java.exe and tomcat.  Native programs that runs off a batch file with no specific registry key or lowlevel system dependencies or installers are more likely to run in Azure.

Azure has worker roles and web roles.  Web roles are used for hosted apps with .net/php and IIS and not used here, however the worker role is used to run native code.  It can be bound to a network port (ie port 80)

The Microsoft support comes in with an Eclipse plugin to access your resources in the cloud from within Eclipse.  There is a jar that wraps up the RESTful interface to Azure that your app would normally use to access the clouds resources with Java helper classes and provides some other .NET helper classes.

It also comes with some helper stuff to setup Tomcat – ‘Tomcat Solution Accelerator’ – to configure Tomcat to make it very light in terms of OS dependencies.  It also has monitoring of Tomcat to let Azure know to restart the app if it fails and also help indicate to MS there is a problem with the particular server that instance in their cloud is perhaps not working as it should.

I do like that you get to choose the versions of Tomcat and Java you want, and there doesn’t seem to be much of a reason you couldn’t apply this to other languages and appserver environments.  (Grails/Jetty? – and hopefully Glassfish, but that may need a bit more config work to pack it up and install on the cloud).  That last point sounds a bit negative, you could probably get a service on a VM linux host that means you dont have to fudge around so much, but still the novelty polyglot value of having JVM and .NET in the same cloud environment may actually outweigh the negative of the DIY setup.  The presentation explains how the Tomcat is packaged and shows the contents of the packaging scripts to give you an understanding of how to do the same for another appserver.

One nice thing about the Azure platform itself is that you have production and staging slots – you can have a production app in the cloud, and also a staging version too – and swap them over when you are happy with Staging.

The other aspect is the queues/worker facility to allow for concurrency when running your app across multiple nodes, asynchronous architectures and scalability.

To try it out, you’ll get free access to Azure while its in CTP status (till Jan 09), and then MS will start asking for money. Apparently, Dominoes pizza is testing out their next version of their ordering webapp on the platform, if you wanted a vote of confidence too

Azure Java SDK available here: windowsazure4j.org