Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, January 11, 2014

Builder pattern using Java 8

I work in an environment where a great deal of our day to day scripting tasks occur through calling remote services as opposed to working with the database.

For a lot of scripting tasks I've often used Groovy and one of the most useful features of Groovy specifically for that task has been it's built in fluent Builders.

Now Groovy builders exploit a few Groovy language features that are never going to make it into Java.

Most notably Groovy builders make use of Groovy's Meta programming features which isn't coming to Java any time soon.

However a key feature that Groovy builders have is their hierarchical approach to building constructs.

This allows the builders to neatly and safely create nested tree like constructs which can be used to model everything from UX form layouts to XML.

This approach we can at least model quite succinctly using Java 8 lambda expressions.

For my sample I decided to take a reasonably simple Maven pom file and see if I could create a builder to handle that.

All the code for the builder is available on Github here.

The pom.xml file is as follows:

 <?xml version="1.0" encoding="UTF-8"?>  
 <project xmlns="http://maven.apache.org/POM/4.0.0"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
   <modelVersion>4.0.0</modelVersion>  
   <groupId>com.github</groupId>  
   <artifactId>lambda-builder</artifactId>  
   <version>1.0-SNAPSHOT</version>  
   <dependencies>  
     <dependency>  
       <groupId>junit</groupId>  
       <artifactId>junit</artifactId>  
       <version>4.11</version>  
     </dependency>  
     <dependency>  
       <groupId>commons-beanutils</groupId>  
       <artifactId>commons-beanutils</artifactId>  
       <version>1.7.0</version>  
     </dependency>  
   </dependencies>  
   <build>  
     <plugins>  
       <plugin>  
         <groupId>org.apache.maven.plugins</groupId>  
         <artifactId>maven-compiler-plugin</artifactId>  
         <configuration>  
           <source>1.8</source>  
           <target>1.8</target>  
           <fork>true</fork>  
           <compilerArgument>-proc:none</compilerArgument>  
         </configuration>  
       </plugin>  
     </plugins>  
   </build>  
 </project>  

Here is the sample code for the builder to build this model:

     MarkupBuilder pom = new XmlMarkupBuilder(true, "pom")  
         .at("xmlns", "http://maven.apache.org/POM/4.0.0")  
         .at("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")  
         .at("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd");  
     pom.el("modelVersion", "4.0.0");  
     pom.el("groupId", "com.github");  
     pom.el("artifactId", "lambda-builder");  
     pom.el("version", "1.0-SNAPSHOT");  
     pom.el("dependencies", () -> {  
       pom.el("dependency", () -> {  
         pom.el("groupId", "junit");  
         pom.el("artifactId", "junit");  
         pom.elx("version", version::get);  
       });  
       pom.el("dependency", () -> {  
         pom.el("groupId", "commons-beanutils");  
         pom.el("artifactId", "commons-beanutils");  
         pom.elx("version", version::get);  
       });  
     });  
     pom.el("build", () -> {  
       pom.el("plugins", () -> {  
         pom.el("plugin", () -> {  
           pom.el("groupId", "org.apache.maven.plugins");  
           pom.el("artifactId", "maven-compiler-plugin");  
           pom.el("configuration", () -> {  
             pom.el("source", 1.8);  
             pom.el("target", 1.8);  
             pom.el("fork", true);  
             pom.el("compilerArgument", "-proc:none");  
           });  
         });  
       });  
     });  


A few notes on this in general:

  • I created a special form of some the methods which takes a java.util.function.Supplier as a parameter, and allows you to delay evaluation of a value until you traverse the builder.
  • I eschewed method chaining (although I catered for it in the builder). Trying both methods I personally felt this was a lot cleaner.
  • Java doesn't have all syntax sugar that Groovy has, so I used a java.lang.Runnable for the functional interface which reduced the syntax creating a closure, with the downside that you have to have a handle on the initial builder object.
Nowhere as nice as Groovy builders but nevertheless a great step forward. Can't wait for Java 8.





Thursday, November 14, 2013

Adding Java 8 Lambda goodness to JDBC

Data access, specifically SQL access from within Java has never been nice. This is in large part due to the fact that the JDBC api has a lot of ceremony.

Java 7 vastly improved things with ARM blocks by taking away a lot of the ceremony around managing database objects such as Statements and ResultSets but fundamentally the code flow is still the same.

Java 8 Lambdas gives us a very nice tool for improving the flow of JDBC.

Out first attempt at improving things here is very simply to make it easy to work with a java.sql.ResultSet.

Here we simply wrap the ResultSet iteration and then delegate it to Lambda function.

This is very similar in concept to Spring's JDBCTemplate.

NOTE: I've released All the code snippets you see here under an Apache 2.0 license on Github.

First we create a functional interface called ResultSetProcessor as follows:

@FunctionalInterface
public interface ResultSetProcessor {

    public void process(ResultSet resultSet, 
                        long currentRow) 
                        throws SQLException;

}

Very straightforward. This interface takes the ResultSet and the current row of the ResultSet  as a parameter.

Next we write a simple utility to which executes a query and then calls our ResultSetProcessor each time we iterate over the ResultSet:

public static void select(Connection connection, 
                          String sql, 
                          ResultSetProcessor processor, 
                          Object... params) {
        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            int cnt = 0;
            for (Object param : params) {
                ps.setObject(++cnt, param));
            }
            try (ResultSet rs = ps.executeQuery()) {
                long rowCnt = 0;
                while (rs.next()) {
                    processor.process(rs, rowCnt++);
                }
            } catch (SQLException e) {
                throw new DataAccessException(e);
            }
        } catch (SQLException e) {
            throw new DataAccessException(e);
        }
}

Note I've wrapped the SQLException in my own unchecked DataAccessException.

Now when we write a query it's as simple as calling the select method with a connection and a query:

select(connection, "select * from MY_TABLE",(rs, cnt)-> {        System.out.println(rs.getInt(1)+" "+cnt)
});


So that's great but I think we can do more...

One of the nifty Lambda additions in Java is the new Streams API. This would allow us to add very powerful functionality with which to process a ResultSet.

Using the Streams API over a ResultSet however creates a bit more of a challenge than the simple select with Lambda in the previous example.

The way I decided to go about this is create my own Tuple type which represents a single row from a ResultSet.

My Tuple here is the relational version where a Tuple is a collection of elements where each element is identified by an attribute, basically a collection of key value pairs. In our case the Tuple is ordered in terms of the order of the columns in the ResultSet.

The code for the Tuple ended up being quite a bit so if you want to take a look, see the GitHub project in the resources at the end of the post.

Currently the Java 8 API provides the java.util.stream.StreamSupport object which provides a set of static methods for creating instances of java.util.stream.Stream. We can use this object to create an instance of a Stream.

But in order to create a Stream it needs an instance of java.util.stream.Spliterator. This is a specialised type for iterating and partitioning a sequence of elements, the Stream needs for handling operations in parallel.

Fortunately the Java 8 api also provides the java.util.stream.Spliterators class which can wrap existing Collection and enumeration types. One of those types being a java.util.Iterator.

Now we wrap a query and ResultSet in an Iterator:

public class ResultSetIterator implements Iterator {

    private ResultSet rs;
    private PreparedStatement ps;
    private Connection connection;
    private String sql;

    public ResultSetIterator(Connection connection, String sql) {
        assert connection != null;
        assert sql != null;
        this.connection = connection;
        this.sql = sql;
    }

    public void init() {
        try {
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();

        } catch (SQLException e) {
            close();
            throw new DataAccessException(e);
        }
    }

    @Override
    public boolean hasNext() {
        if (ps == null) {
            init();
        }
        try {
            boolean hasMore = rs.next();
            if (!hasMore) {
                close();
            }
            return hasMore;
        } catch (SQLException e) {
            close();
            throw new DataAccessException(e);
        }

    }

    private void close() {
        try {
            rs.close();
            try {
                ps.close();
            } catch (SQLException e) {
                //nothing we can do here
            }
        } catch (SQLException e) {
            //nothing we can do here
        }
    }

    @Override
    public Tuple next() {
        try {
            return SQL.rowAsTuple(sql, rs);
        } catch (DataAccessException e) {
            close();
            throw e;
        }
    }
}

This class basically delegates the iterator methods to the underlying result set and then on the next() call transforms the current row in the ResultSet into my Tuple type.

And that's the basics done. All that's left is to wire it all together to make a Stream object. Note that due to the nature of a ResultSet it's not a good idea to try process them in parallel, so our stream cannot process in parallel.

public static Stream stream(final Connection connection, 
                                       final String sql, 
                                       final Object... parms) {
  return StreamSupport
                  .stream(Spliterators.spliteratorUnknownSize(
                          new ResultSetIterator(connection, sql), 0), false);
}

Now it's straightforward to stream a query. In the usage example below I've got a table TEST_TABLE with an integer column TEST_ID which basically filters out all the non even numbers and then runs a count:


     long result = stream(connection, "select TEST_ID from TEST_TABLE")
                .filter((t) -> t.asInt("TEST_ID") % 2 == 0)
                .limit(100)
                .count();
   
And that's it!, we now have a very powerful way of working with a ResultSet.

So all this code is available under an Apache 2.0 license on GitHub here. I've rather lamely dubbed the project "lambda tuples, and the purpose really is to experiment and see where you can take Java 8 and Relational DB access, so please download or feel free to contribute.

Sunday, July 17, 2011

Java 8.0 Wishlist (Take 2)

Ok so it's it been a while since my last article on this topic...

The comments of course have been first rate, with opinions on the wish-list have ranged from outright agreement to threats of violence for even having such boneheaded ideas.

It's all good of course, the thing that I love about the Java community is that we take the ideas and actually question them. Something I felt the .Net world could do more with.

But anyway It's worth going through the list and giving a little rationale and meat on the wish-list, specifically on those that seemed to generate a lot of comments, so here goes...

Properties.
Now I'm going to debate the OO nature of properties. Fact is that - for better or for worse - JavaBean style properties have become baked into Java and it's frameworks. So why not at the bare minimum tell the compiler you want to generate getter and setter methods with syntax sugar. And yes IDE's generate this for you, but I'd still prefer for the sake of brevity get rid of code that does stuff all.

Operator Overloading.
Easily the most contentious point. However let me give you my background: I recently did a lot of work doing monetary calculations. which  defined in an Excel spreadsheet by an Actuary. The only way I could get Java code to match the excel spreadsheet was to use ye olde BigDecimal. The code that came out is painful to say the least, mostly due to the lack of operators. Now BigDecimal is on the operator overloading todo list for Oracle, however it's painful having to wait, and the fact is that it's hard to build very expressive arithmetic types in Java.

Alternative deployment formats besides the JVM and  a classpath.
Ok this one seemed poorly presented. Basically I want to be able to compile a set of Java classes down into a native executable and deploy that. Even if all the executable does is wrap the classes together with a JVM. You ask why; that's easy I want to run Java apps on iOS.

Parameter names in method calls.
Ok so lets assume I have a method as follows:
public void crappyGFXtask(int startx, int starty, int secondx, int secondy, int lastx, int lasty)
I dare you write the code to call it, leave it for a few days and then go back to it, and see if you can make sense of the parameters. Named parameters simply give you ability to map the parameter names to values ala Objective-C so your call to the method would look something along the lines of:
crappyGFXtask(startx:10, starty:11, secondx:25, secondy:40, lastx:myVariable, lasty:myVariable)

Proxies on Abstract classes.
Yes Spring does this already, but guess what: I don't use Spring in every Java project I do (yes pigs are flying). It's a generally useful feature and JDK support would be sweet.

Ok hope that clarifies things.

Tuesday, April 26, 2011

Java 8.0 Wishlist

With Java 7 almost out the door talk has now shifted to Java 8 and of course it's the perfect time for me to add my own $0.02 on my own wishlist.

Properties.
Dunno what you can do here without annoying a few people. However I'd happily settle for some type of shorthand notation for getters and setters.

Operator overloading.
This one pops up at just about every Java release. Now it seems that there are plans in the works to add indexers to collections and such like. Quite frankly if you're gonna do that, why not add a full complement of fixed operator overloadings, maybe taking some ideas from how Groovy does it

Alternative deployment formats besides the JVM and a class path.
When you have to do one of those client Java applications that everyone claims nobody does, the Java deployment model really bites: Basically I want to create a fully contained application for a target platform. Now if all this contained application does at the end of the day is bootstrap a JVM together with a classpath who cares. It's also worth pointing out that this would allow Java applications to run quite easily on iOS, that is; if someone takes the time to do the port.

Parameter names in method calls.
Nice to have, but it would make DSLs in java nicer.

Finish Autoboxing.
I still can't do 1.toString().

Proxies on Abstract Classes.
Not sure about the technical constraints on this, but it would be great if you could also create proxies on abstract classes and not just on interfaces.

Make JavaFX useful.
Ok so JavaFX is not actually part of the JDK. Whatever the case, it's Oracle's chance to make client side Java really slick.

Well that's my list for now...

Friday, February 18, 2011

Using Google Contracts for Java with IntelliJ IDEA.

The first step after obtaining the Google Contracts for Java Jar and adding it to your project, is to enable Annotation processing support in IDEA.

To do this go to open the Settings window (IntelliJ IDEA > preferences on Mac) and go to Compiler > Annotation Processors.

Now do the following steps:

  • Check the Enable Annotation processing option.
  • Select the Obtain processors from project classpath option.
  • In the Processed Modules table click the Add button and select the Module for which you want to enable Contracts for.
  • Hit Apply and you are ready to rock.


To test this you can add a basic contract annotation to a method in a class, here is one that I created using the @Requires annotation to ensure that the integer method parameter "c" has a value greater than zero:

import com.google.java.contract.Requires;

public class TestSomeContracts {

@Requires({"c > 0"})
public void testContract(int c) {

}

}

Now when you compile you wont get much feedback as to wether the annotation was processed or not, as the contract syntax is correct, so lets modify it a bit to generate a compile splat by changing the variable name of the precondition:

@Requires({"cs > 0"})
public void testContract(int c) {

}

When you build the module, you will now get a compilation failure which kinda integrates into IDEA, in that you can click on the error in the messages window and it will take you to the line that failed. Unfortunately IDEA wont highlight the line in your Editor or anything fancy like what you get in Eclipse, but it's good enough to work with.



Using a class with contracts.

After reverting and compiling the class I created a simple test case to test the contract by passing in data that violates the contract (ie. an integer less than 1):


import org.junit.Test;

public class TestSomeContractsTest {


@Test
public void testContract() {
new TestSomeContracts().testContract(-1);
}

}

I run the test… and... it passes!

In order to actually work, Google Contracts needs to do some bytecode shenanigans in order to actually enforce the contract definitions during runtime. Currently they have two modes of operation, an offline instrumenter which is a post compilation processor which weaves in the contracts into a compiled class, and a java agent.

For development the most convenient method to use is the java agent.

To use the agent in IDEA, click the Select Run/Debug Settings drop down and select the Edit configurations option. Expand the defaults entry and select the JUnit option (or TestNG or just plain Application) and add the following to the VM parameters field:

-javaagent:[path to the Google Contracts for Java jar file]

I Also remove an existing configuration so that it picks up the new option when I run the test again.

Now I run the test again and - voila - nice big splat when I run the test and pass invalid data to the method:

com.google.java.contract.PreconditionError: c > 0
at TestSomeContracts.com$google$java$contract$PH$TestSomeContracts$testContract(TestSomeContracts.java:9)
at TestSomeContracts.testContract(TestSomeContracts.java)
at TestSomeContractsTest.testContract(TestSomeContractsTest.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:65)

On a final note. Google contracts is still pretty fresh, so here's hoping IDE support will improve if the project takes off. I must also say that I'm not too fond of the current mechanisms for enforcing the contract. Hopefully Google might take a page from Lombok and do to weaving at compile time.

Tuesday, October 26, 2010

Does Java need a "Linux moment"?

Does anyone remember that one of the reasons Linux or GNU/Linux (sorry Richard Stallman) was created, was to create a Unix like environment which was free and open to use and not encumbered by the licensing restrictions of the AT&T's original Unix.

With all the stuff happening with Java right now, being a Java developer has become a depressing experience, and it's getting really hard to see a positives for the platform.

Perhaps Java needs it's own "Linux moment".

A Java (but not Java) platform that is free and open and built on the same principles that made Linux a success, with the potential for the same type of success that Linux has enjoyed.

I don't know if it's even feasible, but it's certainly becoming an appealing thought.

Sunday, September 26, 2010

The Next Big Java Language; my $0.02

Time to to add my $0.02....

What is the Next Big JVM Language going to be?

I've been watching the whole evolution of alternative languages on the JVM for a few years now. Long enough to start tracing the hype around the different languages.

Yet none of these languages are really mainstream, despite their apparent advantages.

I think the reason for this has absolutely nothing to do with the technical features (or lack thereof) of any of these languages.

I think the NBJL will be the one that large organisation or group of organisations with enough clout and deep enough pockets is actually willing to go out and effectively market both to decision makers and developers.

No doubt Java did strike a chord with mainstream developers, but quite honestly was that more to do with Sun's aggressive marketing campaign or because it of it's many technical merits?


Saturday, August 14, 2010

Why Java is more open than .Net

First of all, lets clarify a few things: Open does not necessarily mean free, and indeed Open Source, secondly in saying that Java is open, I also don't mean that it couldn't be more open than it already is and that the current processes don't have some painful problems regarding openness.

With that out of the way, why is Java more open than .Net?

Lets start with a Simple question: Can anyone show me a .Net 3.5 (Never mind .Net 4.0) certified implementation, that also has certified implementations of all the important .Net technologies that actually make .Net useful like WCF, WPF, WWF, WIF etc, etc. so that I can take my .Net 3.5 App written on Microsoft's .Net implementation and dump it unchanged onto this implementation onto - say Solaris - and it will run no problem regardless of what frameworks and features of those framework I used?


While you are looking it up, here are some more questions:

  • How do go about (or can I even) license .Net from Microsoft?

  • How do I get a say in the specifications for new or existing .Net technologies?

  • Can I actually get my .Net implementation and appropriate frameworks rubber stamped by some certification authority?

  • Does .Net have some type of philosophy regarding platform neutrality?


  • Here are the answers to those questions from a Java perspective:

  • I go to Oracle apply for a Java License, pony up some cash, agree to some terms, then I get a nice kit from Oracle and go forth an implement.

  • I join the Java Community Process and give input to the various Java Specification Requests, I can even submit new Java Specification Requests.

  • I run my implementation of a Java Specification Request against the Technology compatibility kit for that Java Specification Request and not I can say my implementation is certified.

  • Java has had the concept of Write Once Run Anywhere from the beginning and it's backed into Java and the JCP.


  • So what does this mean, and why does it make Java more open?

    It means; that as an end user of Java I can pick and choose the best Java implementations around, and if I decide that I want to change the underlying platform or even the implementation I can do so with relatively little fuss.

    I have in the past run the same Java program happily on OSX, Windows, AIX on Solaris running on Intel, PowerPC and Sparc respectively.

    I have also developed on JBoss and deployed on Glassfish.

    In other words; I as an end user am not locked into any specific Java provider.

    But what about Mono and Ecma?.

    Yes the CLR (and I think C# as well) is an Ecma standard which Java is not.

    But the CLR and C# alone maketh not a development platform and the stuff that makes .Net useful is not very open at all, and as much a The Mono community likes to play it down a cloud still hangs over Mono regarding patents. (BTW: If any Mono guys ever read this, it's fair to say that Mono hasn't cost Microsoft a lot so far, if Android where to run Mono, the cost to Microsoft might be in the billions, can you guarantee Microsoft's behavior when it's losing market share and money?)

    Things may of course change, Microsoft may actually put forward a formal licensing program, and together with the ECMA standardization, and then when I can run all of .Net anywhere on any implementation, then I can say .Net is more open than Java.

    Friday, June 25, 2010

    Oracle and the Sun exodus

    So Oracle has had quite a good quarter, with profit jumping 24%.

    What makes this interesting, is that Oracle claimed that $400 million worth of profit came from the sale of Sun gear, which is quite interesting especially that before the sale Sun hadn't really been making money even in the good times.

    At the same time James Gosling is comforting the hordes of former Sun employees leaving Oracle.

    Quite honestly though, I think the whole exodus of Sun employees leaving is being overblown by the media.

    When you buy a company that is floundering like Sun was, you generally have to take drastic measures in order to bring that company back from brink, and drastic measures in the corporate world normally means doing lots of nasty things.

    Oracle has a reputation for being to integrate companies it purchases quite well, so it's therefore fair to say that they are pretty good at doing said nasty things.

    Now to take it a step further, Sun was not in a fantastic place when Oracle bought it, no doubt it needed some rather drastic measures to get things going again, so I can imagine Oracle had to do some really nasty things.

    As a result you are going to get many people who leave, many of whom are good people who you don't want to lose, but it's unfortunately par for the course.

    To be totally honest It didn't even bother me when James Gosling left Oracle.

    Consider that he has pretty much had no publicly visible direct influence on core Java since it got handed over to the JCP which was 12 years ago.

    Now don't get me wrong, He's left a big hole in Java for Oracle, and I'm hoping that he stays involved in Java, heck, maybe now he can contribute more directly to Java and the community than he could while he was working for Sun.

    Sunday, August 10, 2008

    A simple MP3 Player in JavaFX

    This is pretty much my first attempt at JavaFX and after looking around I wasn't able to find much about using the media player capabilities of JavaFX so I decided to create a simple MP3 player to basically get up and running with JavaFX.



    So, for a start what does JavaFX give us in terms of media APIs.

    Well the JavaFX SDK contains the javafx.scene.media package which contains the classes for using media within your application.

    This package consists of the following classes:

  • Media : This class wraps a media source, i.e: in this case the location of the MP3 file.

  • MediaPlayer : This class provides functionality to drive the playback of a Media instance.

  • MediaError: This class represents an error that occurs during media playback.

  • MediaTimer: This class allows you to execute actions at an interval during the playback of media.

  • MediaView: This class is a visual component for displaying your media in the case of video.


  • For the purposes of this blog I'm only going to focus on the Media class, MediaPlayer class and MediaError class since these are enough to create a very basic MP3 player.

    Media Playback using the MediaPlayer class.
    So the first thing to do is create a most basic MediaPlayer instance:

    var player =
    MediaPlayer {
    repeatCount:MediaPlayer.REPEAT_FOREVER
    onError: function(e:MediaError) {
    display = e.message;
    }
    };


    You can see here that I've set two attributes: repeatCount and onError.

    The repeatCount attribute indicates if the media should loop or play once and then stop. The values for repeatCount are defined as constants on the MediaPlayer class, I've selected MediaPlayer.REPEAT_FOREVER in order to loop playback.

    Note: if you leave out repeatCount, playback will not occur (and no error is thrown either if you don't set it, which led to a rather annoying few hours for me).

    The onError attribute sets a closure (anonymous function) which gets executed when an error occurs. The closure is passed an instance of MediaError to indicate what happened. In my example I simply set a variable called display, which I bound to a Text node in the UI.

    Controlling the MediaPlayer class.
    The next thing we need to do define a method to control your player. MediaPlayer has two methods on it which allow you to control it: play() which starts or resumes playback and pause() which allows you to stop (but not reset) the current media playback in the player. For my example I wrote a very simple Button which stops and starts my MediaPlayer instance based on the button's state and the player's state:

    Button {
    enabled : bind enabled
    text: bind text
    action: function() {
    if (text == "Stop") {
    player.pause();
    text = "Play"
    } else if (player.media != null and text == "Play") {
    player.play();
    text = "Stop";
    }
    }
    }

    Nothing very fancy here, when the Button is clicked in Playing state I call player.pause(), if it's in Stopped state I check firstly that there is media available for the player and then that the button is in a state for me to start playing.

    Creating a Media instance for the MediaPlayer class
    The last thing really left to do is select some media for playback. Now the JavaFX SDK doesn't wrap all of the Swing API, only a select set of components which you can find in the javafx.ext.swing package. Most notably it's doesn't wrap any of the standard Swing dialogs including javax.swing.JFileChooser. The good news is that's it's easy to call JFileChooser from within JavaFX code. Once again I used a javafx.ext.swing.Button to call my code to select media and set it in my media player instance:

    var fileBtn: Button
    component:
    fileBtn = Button {
    text: "File"
    action: function() {
    var fc = new JFileChooser();
    var mp3Filter = new ExtensionFileFilter();
    mp3Filter.addExtension("mp3", "MP3");
    fc.addChoosableFileFilter(mp3Filter);
    var result = fc.showOpenDialog(fileBtn.getJButton());
    if (result == JFileChooser.APPROVE_OPTION) {
    var fFile = fc.getSelectedFile();
    display = fFile.getName();
    var file = fFile.toURL().toExternalForm();
    file = file.replaceAll(" ","%20");
    if (file != player.media.source) {
    player.pause();
    player.media = Media {source:file};
    text = "Play";
    enabled = true;
    }
    }
    }

    }



    This code basically calls a JFileChooser which selects .mp3 files from the file system using a simple javax.swing.filechooser.FileFilter instance FileExtensionFilter - which I wrote for my purposes - to get all the .mp3 files in the file system.

    Note that when you call showOpenDialog() on the FileChooser you have to pass in a java.awt.Component instance. The Button class does not implement this even though it's wraps a Swing JButton component. However Button does give you a method getJButton() which returns the underlying JButton instance, which you can use to pass to the FileChooser.

    Finally once you have the select .mp3 file, the last thing you need to do is create Media object and pass it to the MediaPlayer instance. The Media class has an attribute: source which is a string URL pointing to the location of the media. the Media object will also only accept escaped URLs, which java.io.File.toURL() does not do. This means you have manually escape the URL string before you pass it to the Media object.

    And that's it really, the full source code for my player is available here.

    Wednesday, August 6, 2008

    Java 7.0 or Java.next?

    A while back I was in a WCF master class hosted by Juval Lowy the MS software legend.

    At the time Visual Studio 2008 was a pending release so most of the people were not yet familiar with the language changes in C#.

    Juval took a little time to demonstrate the closures in C# to an impressed bunch of hardcore .Net programmers.

    At the time I had been regularly writing ruby scripts and all I could think of when I saw the C# closures syntax is: "Man that looks terrible".

    Ever since then, I can't help but get the feeling that if MS keeps chucking new features into C# it's not going to look pretty in a few releases.

    But regardless of the impact of those features to the core C# language. MS has managed to - with the help of frameworks to make use of the features - create a whole lot of excitement around C# and .Net.

    And in the IT industry, excitement around products is important unless you want to leak market share.

    It unfortunately also been a couple of years since there's been any excitement around Java.

    So what is a direction-less Java developer to do?

    One of the options is the Java.next option: keep the JVM but use another language to run on top of it.

    This has got quite a few advantages:
  • You can maintain the investment in Java while moving onto a new language.

  • You have an nice way to re-skill developers quickly.

  • You have a clean slate to start from when you design the language.

  • You can generate excitement while placating your very corporate customers.

  • As a developer you have a nice new toy to play with.


  • But before you can do this there are some requirements for corporate IT to accept this:
  • It must have vendor support, and by vendor support I mean the big guys; IBM, Oracle, Sun etc. etc.

  • It has to be very easy to to move from Java to Java.next. In fact ideally it should be a superset of Java but that might be pushing it :-).

  • It has to seamlessly interoperate with all the existing Java frameworks and libraries.

  • IDE support needs to be on par with Java.

  • JCP certification wouldn't hurt.


  • Another option is the Java 7.0 option: simply add new language features to Java to at least maintain parity with other languages. And that of course comes with the risk of messing up the language. Furthermore the changes need to added within a certain time line in order to not create the perception that the language is behind the times.

    And then if that fails there is always the COBOL option: leave the language be and then for us developers; when the Java well runs dry we become COBOL style system maintainers or we simply dump the platform all together and start from scratch.

    Sunday, August 3, 2008

    Java and the closures hall of shame

    So, to see how far the closures rabbit hole goes I decided to make a list of all the languages in the top ten on the Tiobe index which have no closures support or no confirmed closures support in an upcoming version.

    The initial list consists of these languages:
    - Java.
    - C.
    - C++.
    - PHP.

    Oops I forgot about C++0x and it looks like it has closures support, remember I said confirmed closures support in an upcoming version.

    Oh and lets not forget PHP 5.3 and the closures rfc that's already in HEAD.

    Therefore the refined list looks as follows:
    - Java.
    - C.

    Now what about C. It's true that ANSI C forbids nested functions but as it turns out GCC has a few extensions which allow you to do closures. It's also worth considering if C belongs here since it's modern use case and characteristics tends to place it in a different category to the rest of the languages on the index. On those grounds I'm going to apply Occam's razor and remove C from the list.

    The final list looks as follows:
    - Java.

    This means that after the next iteration of language versions, Java will lack in capabilities compared to competing languages. Now I can carry on coding without closures - albeit somewhat unhappily. But bear in mind that Java increasingly has to compete with other languages. And if Java is perceived to be obsolete it's going to be a harder sell in the enterprise.

    Now I know that time is running out for finalizing Java 7.0 but for goodness sakes Sun you really need to do something.

    Now purely from my point of view I wouldn't be upset with either of the following:
    - Pushing out the Java 7.0 time line in order to add these language features.
    - Make another language such as Groovy a required part of the Java 7.0 spec.

    Monday, July 28, 2008

    (Yet another) Benchmark of the CLR vs the JVM

    I read this blog entry today on "This Code Goes to Eleven" regarding a JVM vs CLR benchmark.

    I decided to redo the benchmark. The first thing I did is slightly tweak the Java version (found here) to use System.currentTimeMillis() as opposed to creating a new Date object which IMHO is fairer test with the C# .Net version. The C# version was unchanged.

    I then ran the program in both the JVM's client profile and server profile ("java -client BubbleSort" and "java -server BubbleSort respectively").

    To provide some background. Sun's JVMs run in two profiles: the server profile which is optimised for environments which have loads of memory and CPU time and doesn't really have UI interaction, whereas the client is designed to work with more constrained UI centric environments.

    My machine specs were as follows:
    - Windows XP SP2 32-bit
    - Intel(R) Core(TM)2 Duo CPU 2.33GHz
    - 4096MB of memory

    This was the outcome (click to enlarge):



    The results are noteworthy; for one thing the client profile for the JVM is considerably slower than either the CLR or the JVM server profile. Furthermore the JVM running in server profile is markedly faster than the CLR version.

    But what have I actually proved?

    Absolutely nothing really.

    To illustrate, lets take this another step: I took the same test and I ran it on my Ubuntu 8.04 partition on the same machine (once again click to enlarge):



    As it turns out the Linux version of the JVM running the same program in server mode is slightly faster overall than it's Windows counterpart and the client mode is on average slower than it's Windows counterpart:

    And that's the problem with this whole benchmark.

    You can never simply make a blanket statement and say Java is faster than .Net. There are several reasons for this.

    A JVM is only as fast as it's implementation allows it to be. IBM's JVMs will perform differently to Sun's JVMs to Oracle's JVMs to Apple's JVMs since the guts of the JVM are implemented quite differently for each vendor. Each company's has engineers who will approach the JVM design differently and have a different set of priorities which may get dictated by the market segment within which they compete.

    Secondly a JVM is also constrained by it's platform. If you have a JVM which makes a system call which is slow, or has to generate native code which is slow it's going make your program slow. This means that a Java program performs differently across different operating systems.

    Thirdly .Net is supposed to be Microsoft's pre-eminent development tool for the Windows platform. It's fair to say that MS can tweak their stuff for Windows like no one else can (In fact many people have complained that they purposefully do this). The fact that Java does beat .Net on Windows is quite surprising

    Finally the usage of Java and .Net in the industry has taken the development of the CLR and JVM down different directions. Java - at least from Sun's point of view - took the high road and thus has had a lot of work done for big iron type environments, meaning that their JVM performs better in server environments than client environments. MS on the other hands needs to keep both environments as happy as possible without rocking the boat too much.

    Saturday, May 24, 2008

    Is Java the new C?

    I've been watching the language changes being proposed by the community for Java 7.0 like a hawk.

    Alex Miller's Pure danger tech blog has become one of my favourite reads as a result.

    However I'm pretty sure I'm not the only one who seems to be rather disappointed about what came out of JavaOne this year regarding the proposed Java language features.

    It seems that many of the changes will probably be postponed until Java 8.0.

    Maybe this is not such a bad thing though.

    If I look at the message coming out from JavaOne I could summarise it as being: "Please use Java as a platform but you don't need to use the Java language at all".

    In fact I have have a vast array of excellent choices:

  • If I want a highly productive platform for doing web development, use JRuby.

  • If I want a highly productive platform for my existing Java Developers use Groovy.

  • If I want a concise type safe platform with high productivity use Scala.

  • If I want a mainstream language with Java benefits and high producivity (when it matures) use Jython.


  • Of these languages, Jython (Python in Java) and JRuby (Ruby in Java) are the most "mainstream" being in the top ten on the Tiobe index with Python and Ruby respectively sandwiching C# - which in itself is quite amazing considering that neither have had C#'s marketing.

    Groovy and Scala are a little less mainstream but both have broken into the top 50 with Groovy at number 33 behind Smalltalk and Haskell and Scala finally breaking into the top 50.

    Would I still need to write stuff in Java? sure, but only for those bits and pieces which need some low level stuff where speed becomes important especially considering that Java is the only language in the list which still supports primitives, In this scenario the Java language takes on roll much like C.

    In fact I'd even go so far to say that Java needs to stay the way that it is in in order to keep it viable for this very important role.

    After all we wouldn't want to turn it into the new C++.

    Maybe then we should stop regarding Java as the new Cobol but rather look at it as the new C.

    Wednesday, April 30, 2008

    A Javaphile's guide to .Net

    It's time to know your enemy :-)

    Here is the quick and dirty guide to the major .Net libraries and technologies...


    CLR.
    This is the Common Language Runtime, the runtime for all programs compiled into .Net IL bytecode.

    ADO.Net.
    This is the data access API for accessing, equivalent in Java would be JDBC.

    ASP.Net.
    This is the web technology for .Net, in encompasses both a basic CGI model and the higher level component model. The equivalent in Java would be Servlet and JSP and a certain amount of JSF.

    Windows Worflow Foundation.
    Basically a visual graph orientated DSL for defining workflows, ala JBPM.

    Windows Communication Foundation.
    This is M$'s managed component framework. It bears many similarities to EJB3. It lacks some of the features of EJB3 but does have very powerfull remoting features. It is Microsofts SOA strategy and thus has full support for WS-death*.

    Windows Presentation Foundation.
    This is M$'s definitive new GUI framework and it's replacement for MFC. It forms the basis of the Silverlight framework. Basically the UI is defined in an XML schema called XAML and it links to a .Net class which handles the events and exposes the XAML object model.

    Silverlight.
    A RIA framework, and M$'s flash killer. Silverlight contains a subset of the Windows Presentation Foundation API and and some APIs for doing Web 2.0 stuff.

    LINQ
    This stands for Language Integrated Natural Query. Basically a system for using object based predicates to query an underlying data source. The idea is that you ditch a query language and use a .Net based language to define constraints to query your data. This then runs on top of LINQ implementations such an ORM tool or an XML Dom. There isn't anything comparable in the Java world, the closest is the predicate system for DB40.

    Friday, April 18, 2008

    Five things I like in .Net that I miss in Java

    1. Assemblies.
    .Net assemblies (like a jar file) have proper versioning, and when you reference them as a dependency you can also include the version of a specific assembly. The result is the ability to have different versions of the same assembly running at the same time, the correct one being resolved by the CLR.

    2. Leadership.
    .Net has strong leadership in the form of Anders Hejlsberg. Java is getting closures but C# has them. the downside is that C# is fast approaching C++ bloatiness.

    3. Container model.
    It seems .Net has dumped the container model of COM+ that Java eventually emulated in EJB. WCF (EJB like managed component model) can be deployed however you like. Most importantly you can write a plain old console application and launch WCF from within it, much in the same manner in which you would launch Spring.

    4. Operator overloading.
    Nuff said really. It's worth mentioning though that operator overloading in C# doesn't hold much of a candle to Ruby or Scala.

    5. Unchecked exceptions.
    I know Java also has unchecked exceptions, the big difference is that because .Net doesn't have them, it can make a lot of code a lot cleaner.

    Thursday, April 10, 2008

    My Java 7 wishlist

    These are a few of my own ideas about what I think should be in Java 7. These are partly compiled from things I both like and hate about C# and other ideas borrowed from other languages and - at least as far as I know - some of my own ideas.

    Also I will point out that I am not including closures or type inference or any other functional language stuff. Frankly this has been discussed ad-nauseam, however I will point out that I am absolutely for these features, all of them.

    Here we go:

  • Delegates have never really been a hit with the Java folk. Lets keep it that way.

  • I can live with UnReified generics, but wildcards have gotta go.

  • Fix Autoboxing. In my opinion a job half done. I want to be able to write 1.toString() now!

  • Structs suck! James Gosling was right.

  • I like the idea of properties in Java, but only for binding purposes. basically I want to be able to bind to a fixed type safe Java construct as opposed to using a string to denote a property name.

  • While we're at it, lets add some shorthand notation for getters and setters.

  • Dynamic proxy support for abstract classes.

  • Inheritance for static members.

  • Dynamic invocation blocks. This is an idea for Java that I thought of around the time Rails was causing noise. Basically what this is, is the ability to dynamically handle method calls similar in the way that that Ruby or Smalltalk handle messages or method calls which are not actually implemented. By default an exception is thrown if the method does not actually exist, however the method which handles this can be overriden, as is the case with the ActiveRecord framework which uses this to do dynamic finders. There is no reason we couldn't have something similar in Java. Basically it would work like this: Interface and abstract methods no longer need to be implemented by concrete classes provided that the class implements an Interface similar to java.lang.reflect.InvocationHandler (which is used to do the same thing for dynamic proxies). The compiler could simply substitute the unimplemented method with the invoke method on the InvocationHandler. This would then be completely type safe and provides a similar level of guarantee to the caller as you would have implementing the method normally.

  • Bundle Groovy or JRuby as part of the JRE It's time for the JVM to strike out and provide alternatives. Admittedly groovy might be better, since it was designed with the Java API in mind and presents a bit less overhead.

  • A Range object.

  • Flesh out the String class with useful static utilities, those that inevitably end up in a StringUtils class which get rewritten for every project I've ever worked on like isEmpty() to determine if a string is null or empty.

    These beauty is that many of these features (except maybe for properties) require no new additions to the basic language structure and for the most part can use a bit of compiler magic and some new libraries.

    Let me know what you think.
  • Wednesday, March 5, 2008

    The bride of FrankenStack

    Spring killed the J2EE store. And we used Spring to create a FrankenStack.

    What is a FrankenStack?

    A FrankenStack is a unified framework of many frameworks put together. Basically goo trying to make a whole bunch of third party frameworks talk to each other in an attempt to create a cohesive architecture.

    J2EE developers who hop over to Spring enamoured by the possibility of the POJO and Spring create an App server using Spring are especially adept at creating FrankenStacks.

    Right but this is a .Net blog.

    Anyone who has ever recently worked in .Net will notice the plethora of frameworks which have emerged from M$ in an effort to dislodge Java from the Data Center.

    The - non exhaustive - list is as follows:
    - WCF
    - WPF
    - SilverLight
    - WWF
    - ASP.Net
    - ADO.Net
    - DLinq
    - Xlinq
    - Linq
    - Atlas toolkit
    - BizTalk

    These technoligies cover everything from managed components to web services to RIA toolkits to AJAX toolkits to ORM toolkits.

    Many of these toolkits are fully integrated into about every aspect of the Windows World.

    Basically M$ has taken FrakenStack to the next level: they have created a shrink wrapped Frankenstack.