Luxembourg Java User Group – Fun with Lego, Wii and Bluetooth
Posted by Sébastien Stormacq in Java on 20/02/2009
Last Tuesday, the Luxembourg Java User group (YaJuG) held its first 2009 meeting and the agenda was quite fun.
The slides (in french) are available and the full video of the sessions will be posted soon. A short, one minute, video overview of the evening is also published. |
Create a reusable PieChart component with JavaFX – Part I
Posted by Sébastien Stormacq in Java on 15/02/2009
In my last blog entry, I described how to code asynchronous remote communications between a JavaFX application and a REST service.
I used, as sample JavaFX application, a pie chart component.
In this blog entry, I will explain how to build a PieChart, i.e. a reusable JavaFX class to be embedded in your own applications.
This blog entry will be in two parts :
-
Part 1 will describe the basic of creating a Pie Chart component (this blog entry)
-
Part 2 will describe how to make the component nice looking by adding behavior and 3D effects (to be published soon)
Before writing any piece of JavaFX code, you will need to download and install the JavaFX SDK, either standalone, either bundled with NetBeans IDE.
As a component user, I would like a reusable component with an easy to use API that let me specify the following :
-
the values to be part pf the pie chart
-
the center and size of the component
-
the colors to be used
These will be the public attributes that end users will be able to specify. Because I want the component to be easy to use, all these attributes (except the pie chart values) will have defaults, freeing component users to specify a value for each of these.
The first draft of the code will therefore look like this :
public class PieChartFX extends CustomNode {
public-init var colors = [ Color.rgb(83,130,161), Color.rgb(0,84,128), Color.rgb(248,152,29), Color.rgb(194,205,0), Color.rgb(255,199,38), Color.rgb(253,185,19)];
public-init var radius: Integer = 100; public-init var center = 125; public var values = [ 0.0 ]; }
The values are expressed as an array of values.
center and radius are self explaining
The colors are expressed as an array of Color that will be used in a sequential order in the Pie.
The default values for the colors are the one from the Sun Color Palette, feel free to replace with whatever makes sense for you.
What makes a Pie ?
Technically, drawing a Pie is very easy. A Pie is a set of Arc components, all having the same center and where the sum of Arc’s angles is a full circle, i.e. 360 degrees.
There are two main steps in your Pie drawing code
-
Step 1 : convert the array of (arbitrary) values to an array of values where the sum is 360, each value being proportional to the original array value. For example, when the component user is giving us [25, 50, 25] it will be converted to [90, 180, 90]
This array will contain the angle values for each part of the Pie -
Step 2: draw an Arc component of the given angle (see Step 1), starting at the angle where the previous Arc finished. Our code will need to count the sum of angles we’ve drawn so far.
Actually, to make the drawing code easier, I chose to build two arrays : one to contain the angle values, the other to contain the start angle values.
Code goes like this :
//count the total values of the sequence var totalValue: Number = 0;
for (v in values) totalValue += v;
var sum = 0.0;
//create array of ANGLE_VALUES, sum is 360, //pondered by percentage of each value for (v in values) { var percentage: Number = (v / totalValue); var newAngle = 360 * percentage; insert newAngle into ANGLE_VALUES; insert sum into START_VALUES; sum += newAngle; }
Having these two arrays will make the drawing code itself extra simple : just walk through each of these arrays and create an Arc with the corresponding start angle, angle value and color.
def ARCS : Arc[] = for (angle in ANGLE_VALUES ) {
var start = START_VALUES[ indexof angle];
Arc { centerX: center centerY: center radiusX: radius radiusY: radius startAngle: start length: angle type: ArcType. ROUND fill: colors[(indexof angle) mod colors.size()] } }
The code above will create an array of Arc instances, in the order of the values computed in the ANGLE_VALUES array. The colors will be using in the corresponding order of the colors array, going back (mod) to the first one when all colors have been used.
Creating the component
Classes that extends CustomNode must overwrite the create() method to actually return something displayable in a Scene.
public override function create(): Node { return Group { content: bind ARCS; } }
In this code, we create a Group object made of our previously build array of Arc.
Redrawing when values changes
Wouldn’t it be cool to have our Pie Chart to redraw itself automatically when the user change the array of values, either replacing values, removing some or inserting new ones ?
JavaFX makes it very simple to code this type of behavior with two keywords : bind and on replace. Bind allows to link, at runtime, the value of a variable or attribute with the value of an expression. Each time the expression is changed, the value is recalculated and updated.
On replace behaves like a trigger in a RDBMS, it allows to execute code when the value of a variable or attribute is changing.
First, we want to recompute our angles when the values provided are changing.
public var values = [ 0.0 ] on replace oldValue[firstIdx .. lastIdx] = newValues { ... }
The code between { and } is the code listed above to compute ANGLE_VALUES and START_VALUES
Secondly, I want my ARC array to be changed each time new values are provided. This is where the bind keyword is used, just replace the ARC definition listed above with
def ARCS : Arc[] = bind for (angle in ANGLE_VALUES ) { ... }
Using the component
In your Main class, use the code below to actually create and display a PieChart
Stage { title: "Application title" width: 250 height: 270 scene: Scene { content: PieChartFX { values: [ 110, 50, 80, 10, 30] } } }
The end result is displayed below.
My next blog entry will improve this component : we will add some 3D look and we will add code to slightly move a piece out of the PieChart when the mouse is over it. Full source code will be provided.
Stay Tuned !
JavaFX asynchronous communication with JSON and REST based web services
Posted by Sébastien Stormacq in Java on 19/01/2009
While writing Rich Internet Application with JavaFX is relatively easy and well documented, fetching data from remote sources seemed more obscure to me. The documentation is minimal and I did not found any good tutorial describing the various techniques available to connect to a remote web service and how to parse the results.
While this blog entry do not aim at being such a tutorial, I will just give an example I developed over the week end to integrate a JSon based REST web service from a JavaFX application.
(For those of you interested in database access, my colleague Octavian just published a blog entry on the subject).
Let’s first start with the REST web service. Once you have installed the appropriate plugin into NetBeans, it is as simple as creating a web application, then creating a REST based web service.
I used the json.org supplied JSon Java classes to create the output message.
The web service I created just return 4 random values, between 0 and 100. The syntax of the returned message is
{“Values”: 21, 35, 76, 82}
And the code is as follow :
@Path("values") public class ValuesResource { Random rand = new Random(new java.util.Date().getTime()); @GET @Produces("application/json") public String getValues() { String result; try { result = new JSONStringer() .object() .key("Values") .array() .value(rand.nextInt(100)) .value(rand.nextInt(100)) .value(rand.nextInt(100)) .value(rand.nextInt(100)) .endArray() .endObject().toString(); } catch (JSONException e) { e.printStackTrace(); result = "{ \"error\" : \"" +e.getLocalizedMessage() + "\" }"; } return result; } }
I deployed this on GlassFish v3 and tested from command line with curl :
marsu:~ sst$ curl http://localhost:8080/WebApplication1/resources/values {"Values":[94,61,26,72]}
In my JavaFX application, I want to call this web service on a regular basis. I therefore choose to use the Timer and TimerTask Java classes to wrap the calling code and execute it on a regular time-based interval.
The first piece of code is a custom TimerTask. It wraps the JavaFX provided RemoteTextDocument, a very easy to use class that wraps the HTTP communication.
var values : Number[]; class Task extends TimerTask { override function run() { var request : RemoteTextDocument = RemoteTextDocument { url: "http://localhost:8080/WebApplication1/resources/values"; } var returnValue: String = bind request.document on replace { if (request.done) { var data : JSONArray = new JSONObject(returnValue).getJSONArray("Values"); for (i in [0..data.length() - 1]) { insert data.getDouble(i)into values; } } } } };
The RemoteTextDocument as three useful attributes :
-
url, the URL to connect to ;
-
done, a flag indicating that the connection is completed ;
-
document, the text returned by the URL connection
The URL connection is made automatically when creating an instance of the class.
To get access to the document in an asynchronous way, I am using the bind and on replace capabilities provided by JavaFX.
My returnValue variable is bound to request.document, meaning that every time request.document is modified, returnValue is updated to reflect the new value.
The on replace trigger, allows to execute some code when the value of returnValue is changing, basically, it parses the resulting String with the Java based JSon classes and create an array of Number.
Easy to write, to read and very efficient !
The last step is to create a Java Timer to trigger the TimerTask on a regular basis. I want this process to start as soon as the JavaFX application starts. JavaFX does provide a run() function for this purpose.
function run( args : String[] ) { def timer : Timer = new Timer("TimerThread"); def task : Task = new Task(); //run the TimerTask immediately and every 5 secs timer.schedule(task, 0, 5000); //more JavaFX line of code, notably create the Stage and Scene etc ... }
Et voila … the JavaFX application will start polling the REST web service every 5 secs. I further bounded the array of Number prepared by the TimerTask to a PieChart component. The net result is a self-refreshing pie chart as shown below. The PieChart JavaFX component will be described in a later blog entry. |
|
JavaFX for my kids
Posted by Sébastien Stormacq in Java on 03/01/2009
A year ago, I quickly developed a small application to learn my kid to use a keyboard and create words by typing letters. The application shows a word (usually the first name of a family member) and he must type the same word by clicking on the keyboard letters.
The application is providing sound-based feedbacks to pronounce the first name and each letter typed.
I used Java and Swing, the result is showed in the screen shot below.
Pretty simple but highly effective, my 4 years old boy loves to play this little game.
As you can see from the screenshot above, I am a software guy, not an graphical artist.
When JavaFX came in last December, I wanted to see how easy (or not) it would have been to re-write this application with a somewhat more appealing and modern graphical user interface.
The result is this new application, entirely similar in terms of functionalities but with a different look and feel.
I also added some animations, the letter symbols zoom in and out when the mouse is over the letter and the box is highlighted when the user clicks on it.
There is more or less 500 lines of JavaFX code needed to write this application, roughly 20% less lines of code than the “equivalent” Swing application.
For the curious, you can download the source code.
Platform Popularity and Job Posting
Posted by Sébastien Stormacq in Java on 17/11/2008
One of the interesting way to mesure the popularity of a software platform or framework is to capture the number of job posting requiring experience with the platform or the framework.
This is the type of search indeed.com allows to conduct. And guess what ? GlassFish experience appearing in job postings increased ~700% during the last two quarters ! More than 6 times the growth of popularity of the other application servers.
Stil looking for evidences of GlassFish adoption ?
Using HermesJMS to browse GlassFissh’s JMS queues
Posted by Sébastien Stormacq in Uncategorized on 12/11/2008
GlassFish includes Sun’s implementation of JMS , known as OpenMQ . When developing SOA applications with Java CAPS or OpenESB , you will most probably end up using JMS queues and topics as loosely coupled communication mechanism between components of your application.
However, as great are GlassFish and OpenMQ, they lack a graphical tool allowing to browse queues and topic. Developing JMS applications without such a tool is a frustrating task, to say the least.
Here comes HermesJMS. Quoted from their web site :
|
“ HermesJMS is an extensible console that helps you interact with JMS providers making it easy to browse or search queues and topics, copy messages around and delete them. It fully integrates with JNDI letting you discover administered objects stored, create JMS sessions from the connection factories and use any destinations found” |
Configuring HermesJMS to connect to OpenMQ is not intuitive at all and I found very few resources on the web explaining how to do it.
At this stage, I would like to thank Michael Czapski and Thomas Barrett for having showed me the steps required to configure HermesJMS and for all the work they did to prepare a great CEC 2008.
Step 1 : Start Hermes JMS
The easiest way to start Hermes JMS is using Java Web Start. You can do that from their web site or using the icon below (requires Java SE 6+, if you have older versions of Java, other links are provided on Hermes JMS’ web site)
Note that it will only work if your Java MQ is installed to use default port 7676.
Step 2 : Create a JavaMQ session
Replace <new> with JavaMQ and click the Apply button.
Step 3 : Add Java MQ JARs files to the classpath
Click on the Providers Tab on the bottom of the screen, right click anywhere inside the Classpath Groups pane and choose Add Group.
Name the group JavaMQCLasspahGroup (or whatever meaningful name you want). Right-click on the long button called Library and choose Add JAR(s).
Navigate to your GlassFish application server’s imq/lib directory. For OpenESB installed to OPENESB_HOME it will be something like : $OPENESB_HOME\glassfish-v2-ur2-b04-patch-20080929\imq\lib
This should work whether the imq/lib comes from Java MQ 4.1, OpenESB installation, GlassFishESB installation or Java CAPS 6 installation.
Choose the 10 following JARs. Not all may be required by we did not spend the time figuring out the minimum necessary set.
-
fscontext.jar
-
imq.jar
-
imqadmin.jar
-
imqbroker.jar
-
imqjmx.jar
-
imqutil.jar
-
imqxm.jar
-
jaxm-api.jar
-
jhall.jar
-
jms.jar
Allow Hermes to scan the JARs.
Once the JARs are scanned the Library will list all the JARs. Click the Apply button. Your screen should now look like this :
Click on Apply, then OK
Right-click the JavaMQ session and choose Edit to open configuration dialogue again.
Pull down the Loader menu and choose the JavaMQClasspathGroup. Pull down the Class menu and choose the com.sun.messaging.QueueConnectonFactory class. Click OK
Step 4 : Add an existing JMS queue / topic to your session
The last step is to actually add the queues and topics you want to monitor
Right-click JavaMQ session and choose New->Add queue …
and be sure to choose the name of an existing queue or topic.
Step 5 : Enjoy browsing your queues and topics
Once the Java MQ session is configured and queues of interest are configured we can interact with the Java MQ broker, view messages in destinations, truncate destinations (delete all messages) and so on. The functionality of Hermes JSM can be used as required.
UPDATE : OpenMQ FAQ now has a topic on HermesJMS Integration. It also describes how to connect to a remote broker, not running on the localhost.
Happy Birthday NetBeans
Posted by Sébastien Stormacq in Java on 20/10/2008
This week, NetBeans is turning 10 years old. Join me in congratulating our team and all persons involved on that project during the last decade.
I still can remember this day when I first downloaded NetBeans 1.0 beta. At that time I was using a Windows based Java text editor, Kawa … and Symantec and Microsoft where the masters of the Java IDE world with Symantec Cafe and Visual J++. For a full review of the Java IDE 10 years ago, read this article.
You can read the original NetBeans press release on lwn.net.
Virtual Box in Headless Mode, RDP, Sun Rays, Mac ….
Posted by Sébastien Stormacq in General on 16/09/2008
I am at SIBOS this week, on Sun’s booth, demonstrating our Open Suite for Swift Solution to customers and prospects.
The demo has been prepared by Patrice in a Virtual Box image and requires significant resources to run as it includes, Java CAPS, Directory Server, Oracle XE, Microsoft MQ, Websphere MQ etc …
Our initial plans was to install that demo on our booth’s Sun Ray server but the machine was not sized appropriately to handle a dozen Sun Ray clients running Star Office, Firefox and, at the same time, our huge Swift demo VM.
The solution was :
- Start the VM on my own laptop, in headless mode (my laptop acting as a Virtual Server)
- On the Sun Ray, start our RDP client to connect to running VM, over the air
The full picture is then
Sun Ray device ---> Sun Ray Server ---> RDP Client ---> Virtual Box ---> Swift Demo
This setup works great ! People are always quite impressed when I plug my Sun Badge in a Sun Ray client and instantly receive my Windows screen running in a VM on another machine.
It is important to understand that Virtual box *is* the RDP server here, independently of any OS running as guest. This setup will also work with Linux or Solaris guest. Read this article to find more about Virtual Box’s headless capabilities.
Sun Ray Branding
Posted by Sébastien Stormacq in General on 16/09/2008
SunRays are our ultra thin desktop clients, part of our Desktop Virtualization solution. These little business oriented devices generaly adopt a sobre grey look but do you know they can be custom branded too ? This is what we did for ING Netherlands, currently adopting these desktop devices to reduce their maintenance costs, simplify the desktop administration and meet their CO2 objectives by significantly reducing power and cooling needs. |
Open Source Distribution and Support – the best of both worlds
Posted by Sébastien Stormacq in Uncategorized on 14/09/2008
Many customers are asking for the latest and greatest features from our development trees, while asking at the same time for the security of a support contract.
Developers wants to work with the latest stable builds, Managers wants the security of 24/7 support and legal indemnifications.
Until today, customers had either to download the latest stable build from our open source and community web sites (such as OpenSSO, OpenESB), either to subscribe to the commercial equivalent of these tools (Access Manager, Java CAPS) .
Once again, Sun is changing the rules.
GlassFishESB will be the officially supported version of the community open source project OpenESB, with stable releases on a more frequent basis than the commercial equivalent Java CAPS, also based on OpenESB.
GlassFishESB is the fourth release vehicle for Java CAPS, the others being ESB Suite, MDM Suite and, the full Java CAPS. Confused ? Check this table to compare our four offerings.
But we don’t want to leave our Java CAPS customers behind, therefore the components that are being released with GlassFish ESB are targeted for use by Java CAPS customers as well. The objective being that Java CAPS or ESB Suite customers can use all of the capabilities released with GlassFish ESB at the time they are available.
Further, going forward, customers who buy the higher levels Suites should not be "disadvantaged" in terms of either not having access to new components and also having access to them at the same time. In other words, we want customers of the "suites" to have the benefits and flexibility of the community approach as well
Similarly, OpenSSO Express is the supported version of OpenSSO, available to Access Manager customers. Access Manager releases are published every 12-15 months, while OpenSSO Express releases are planed every 3 months.
Can we get the best of both worlds ? You bet !