Archive for the ‘Java’ Category

JavaFX Questions

Tuesday, August 19th, 2008

Sun has released a JavaFX preview. Having played around with it, here are my questions:

  • Will using the scenegraph api consume less resources than a comparable app developed using DHTML? In Meebo is what’s wrong with the web (cached), Uncov writes that Meebo consumes 39Mb RAM over-and-above that of Firefox. Running a basic JavaFX app (JRE1.6u7) consumes about 33Mb “VM Size”, i.e. private process memory.
  • Why is interpreted JavaFX script slow, when interpreted javascript is fast enough for client-side work? Web apps don’t necessarily have to compute prime numbers.
  • Silverlight will consume markup generated from any web server. JavaFX requires a server-side compiler, or a precompiled script. Any client-side plugin ignores PHP at it’s own peril.

JavaFX API documentation

Sunday, August 17th, 2008

Since JavaFX is still under active development, the JavaFX API docs could do with some serious link-love. Currently, version 0.2 of JavaFX docs ranks in Google.

JavaFX Type Casting

Sunday, August 17th, 2008

I have been playing a little bit more with JavaFX. Unfortunately the language reference isn’t particularly complete, and it turns out that type casting in JavaFX is via the as keyword. (Thanks Andres Almiray for the tip!)

For example,

var myWidth = (e.node as Rectangle).width

Incidentally, the performance of the drop shadow effect leaves much to be desired, especially if the shape is sufficiently large. During animation, the effects should be cached and preference should be given to inaccurate but speedy rendering. For instance, during rendering, the effect should be timed and if it is too slow, then a cached bitmap should be used.

The drop shadow is a rather important visual effect, especially given that Windows XP has been decorating all their windows with a shadow for 6 years, I hope Sun doesn’t drop the ball on this in JavaFX 1.0.

import javafx.scene.image.*;
import javafx.application.*;
import javafx.animation.*;
import javafx.scene.effect.*;
import javafx.scene.paint.*;
import javafx.scene.geometry.*;
import javafx.scene.text.Text;
import javafx.input.*;

var imX:Number=0;
var WIDTH:Number=400;

Frame {
    closeAction:function() { java.lang.System.exit(1); }
    stage: Stage {
        fill:Color.web('#333333')
        content: [
            Text { content:"Click on rectangle to make it smaller and observe increased frame rate" x:10 y:10 fill:Color.ORANGE},
            Circle { cache:true centerX:400 centerY:100 radius:80 fill:Color.YELLOW },
            Rectangle {
                cache:true
                x:bind imX y:100 arcWidth:20 arcHeight:20
                width:WIDTH height:WIDTH*0.75
                fill:Color.web('#6699ff')
                effect: DropShadow { radius:20 color:Color.web('#111111') offsetX:10 offsetY:10 }
                onMouseClicked: function (e:MouseEvent) {
                    (e.node as Rectangle).width  = (e.node as Rectangle).width  * 0.70;
                    (e.node as Rectangle).height = (e.node as Rectangle).height * 0.70;
                }
            },
        ]
    }
    visible:true height:768 width:1024
    title:"DropShadow Test"
}
Timeline {
    repeatCount:Timeline.INDEFINITE autoReverse:true
    keyFrames: [
        KeyFrame {
            time: 3s
            values: { imX => 800 tween Interpolator.EASEBOTH }
        }
    ]
}.start();

Clairvoyant Interaction

Tuesday, August 12th, 2008

This page is where I keep track of interaction design patterns. It will be particularly useful to implement these behaviors in JavaFX/Flex base-classes for nodes so that UX designer don’t have to nitpick over details like these:

  1. Yorai discusses the effect of mouse clicks and shift click, control click on focus, selection, activating in-place editing, dragging
  2. Raymond Chen discusses how a sequence of two single clicks is converted into a double-click event, and how the designer should assume that single click has occurred even if the user has double-clicked because the user double-clicks on everything (I have watched my wife do that). This is known as debouncing
  3. Just for completeness, Raymond Chen discusses triple-clicks.
  4. When waiting for a potential double click, onDragBegin() should not fire unless the mouse has moved a certain minimum distance (this is known as drag tolerance).
  5. Draggable, Droppable, Sortable
  6. Once a mouse is captured during drag-and-drop, when the mouse hovers over other objects, it should fire onDragOver instead of onMouseEnter.
  7. Robert Biggs of Vertigo discusses the minutae of drag and drop parameters
  8. A pretty complete framework for mouse-dragging … we can probably implement this for JavaFX
  9. Dragging should also trigger scrolling in containers

JavaFX for Experienced Programmers

Saturday, August 9th, 2008

What JavaFX is not

JavaFX is not Java. It is a brand new language that builds on top of the JVM and the runtime libraries.  There is a new syntax, and a lot of new syntactic sugar aimed that reducing the quantity of code needed to

  • create and animate user interfaces
  • update user interfaces as model data changes
  • update model data from the user interface

A Quick Taste of JavaFX for the Impatient

// hello.fx (.fx is the only allowed file extension, hello.jfx will not work)
//import javafx.ex.swing.*;
import javafx.ext.swing.SwingFrame;
import javafx.ext.swing.Label;
import javafx.scene.paint.Color;java.lang.System.out.println(”Step 1″);
SwingFrame {
  title: “Chui’s Counterpoint”
  visible: true
  content: Label {
    text: “Hello World!”
  }
}
java.lang.System.out.println(”Step 2″);

Building and running is straightforward

javafxc hello.fx
javafx hello

This yields a standard ugly Swing Frame with “Hello World” label.

The important take-away is

  1. There is no main loop
  2. Although the code looks declarative, it is actually run imperatively, statement by statement.
  3. Instantiation of classes does not require a “new” keyword
  4. There is no need to assign the newly instantiated class to a variable
  5. There is no messy getContentPane().add(myJLabel)

Syntax Nit-picking

It appears to me that spaces are optional in JavaFX. For instance:

content:Label{text:”Hello”width:50}

is valid syntax. There is usually some measure of benefit in enforcing readability in a language. Ignoring spaces also lead to some potential disambiguation issues. For instance, FORTRAN “for” loops are difficult to parse. do 10 i = 1, 5 could potentially mean assignment do10i=1.5 if the comma was mistyped, and replaced with a period.

I found the syntax makes it difficult to decide where to place the closing braces. For example, should we prefer the following - where the closing brace lines up with the content attribute:

  content: Label {
    text: “Hello World!”
  }

or should we prefer this - where the closing brace lines up with the constructor?

  content:
    Label {
      text: “Hello World!”
      color: Color.web(”#336699″)
    }

This leaves a hanging indent, similar to Python. There’s nothing wrong with hanging indents, but a language should make it easy for teams to just stick with one system.

I suspect the latter style is more useful, since it makes it easier to move elements around).  You will need to customize your editor to indent code upon carriage return following an attribute.

Java Problem #1: Too many statements are required to initialize a user interface

JavaFX solution: Declarative User Interfaces using Object Initializers

A common problem encountered developing user interfaces in Java, is the number of statements it takes to accomplish particular tasks. For instance, to add a JLabel in swing would require three statements:

JLabel myJLabel = new JLabel();
myJLabel.setText(”Hello”);
frame.getContentPane().add(myJLabel)

C# exponents would probably note the how JavaFX also uses Object Initializer syntax to reduce the amount of code written. The following is the C# equivalent (from msdn)

StudentName student = new StudentName { FirstName = “Craig”, LastName = “Playstead”, ID = 116 };

So the Java example above could be rewritten in JavaFX as a single expression:

  content: Label {
    text: “Hello World!”
  }

Java Problem #2: Binding user interface to data is not baked into the Java, but requires libraries to implement cooperating classes

User interface components like JTable require a cooperative class to implement a specific Model interface, in order for the user-interface to be able to consume the data. This makes the user-interface king, as it dictates how data is represented internally, otherwise, additional work would be required to write adapters so that data could be adapted to a particular model.

JavaFX solves this by automatically wiring up update handlers using the bind keyword. In the example below, a Text node is bound to myString. When the value of myString is changed by the background thread called timeline, the Text node’s content will be updated automatically.

// bind.fx
import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.text.Text;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.lang.Duration;

var myString = “Hello World!”;
Frame {
    width: 150
    height: 50
    visible: true
    stage: Stage {
        content: [
            Text {
                content: bind myString
                x: 0
                y: 10
            }
        ]
    }
}
var timeline = Timeline {
    keyFrames: [
        KeyFrame {
            time: Duration { millis: 1000 }
            action: function() {
                myString = "Goodbye World";
            }
        },
        KeyFrame {
            time: Duration { millis: 2000 }
            action: function() {
               
myString = "Hello World";
            }
        },
    ]
    repeatCount: 3
}
timeline.start();Decompiling bind.class with jad java decompiler yields the following nuggets:

1. The timeline keyframe has a Function instance

new Function0() {
  public void lambda()
  {
     bind.myString.set(”Goodbye World”);
  }
}

2. myString is a static variable in the bind class and it is not strongly typed at all.

public class bind implements Intf, FXObject {
  public static final ObjectVariable myString;
}

The question arises then, how do we integrate ordinary POJOs into JavaFX to make them observable? Perhaps the easiest way is to marshall data as JSON, and then recreate the instances using JavaFX classes. The JavaFX classes could be created automatically via annotations on the original POJO class definitions.

Binding to expressions

JavaFX permits binding to expressions. For instance, we can replace the example above with the following:

// bind.fx
import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.text.Text;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.lang.Duration;

var myString = “Hello World!”;
Frame {
    width: 150
    height: 50
    visible: true
    stage: Stage {
        content: [
            Text {
                content: bind "JavaFX says: ".concat(myString)
                x: 0
                y: 10
            }
        ]
    }
}
var timeline = Timeline {
    keyFrames: [
        KeyFrame {
            time: Duration { millis: 1000 }
            action: function() {
                myString = "Goodbye World";
            }
        },
        KeyFrame {
            time: Duration { millis: 2000 }
            action: function() {
               
myString = "Hello World";
            }
        },
    ]
    repeatCount: 3
}
timeline.start();

Running the compiled class file through the Jad decompiler yields this interesting method called getStaticDependents()

protected Location[] getStaticDependents()
{
    return (new Location[] {
        arg$0, bfx$0selector
        // arg$0 is myString, bfx$0selector is “JavaFX says: “

    });
}

public String computeValue()
{
    return bfx$0selector.get() == null ? null : ((String)bfx$0selector.get()).concat((String)arg$0.get());
}

Presumably, the purpose of getStaticDependents is to construct a giant dependency graph so that when one item updates, the dependent values will be recomputed.

 

Java Problem #3. Updating the underlying model from User Interface is not baked into the language

Writing code to update model is repetitive and adds little joy to a developers daily work. In Java, much of the drudgery can be taken out by using Binding frameworks. This usually involves calls to a binding library that converts user-interface values into model values. For instance, “1.25″ has to be parsed to 1.25 and followed by updating the underlying property on the model. There are several competing Binding frameworks, Swing Data Binding aka JGoodies Binding, Beans Binding, JBind, Castor. Some would say that too much effort is being devoted to something so fundamental.

JavaFX’s approach is to get rid of external libraries, and put it in the language instead via the keyword “bind … with inverse”.

// twoway.fx
// demonstrates two way binding
import javafx.ext.swing.SwingFrame;
import javafx.ext.swing.TextField;
class Person
{
    attribute name: String
        on replace oldVal = newVal { java.lang.System.out.println(oldVal.concat(” updated to “).concat(newVal)); }
}
var person = Person { name: “Chui Tey” }
SwingFrame {
    width: 400
    title: “Two way binding”
    visible: true
    content: TextField {
        editable: true
        width: 250
        text: bind person.name with inverse
    }
}

There are two new constructs introduced here.

Firstly, the declaration “with inverse” allows the TextField to update the underlying model. (omitting “with inverse” results in an illogical AssignToBoundException).

Secondly, we have created a trigger, which is an analog of setter() methods in Java. The syntax is a mix of SQL triggers and ruby blocks. It’s not particularly pretty, and I have a dislike of introducing new syntax when a good old lambda would have sufficed. e.g.

class Person
{
    attribute name: String
        function onReplace(oldVal, newVal) { java.lang.System.out.println(oldVal.concat(” updated to “).concat(newVal)); }
}

However, the new syntax allowed slice assignments to be expressed. I have not delved into this, but would have thought it is better to extend the function() syntax to take the slice assignments rather than having a new construct altogether. As an old BASIC programmer, the idea of OPEN FILE FOR READ is anathema to building good libraries, and makes code difficult to introspect.

Unaddressed Issues

While JavaFX is an improvement on Java for building RIA applications, I feel it has not completely addressed the issues of making it easy for designers to create interactive components. For instance, there is no clear path for a programmer to prototype using Swing components, and then a designer replaces the swing buttons, textboxes and listboxes with a totally custom UI, while retaining the original behaviors.

There is also no clear guidance for using custom renderers for plain-old-objects. For example, WPF has a concept of DataObjects, where plain-old-objects are embedded within a UI container, and specialized renderers are registered to render these objects when they are encountered. 

JavaFX is an improvement, but Java could adopt some of the changes too

As a language that is intended to solve some of Java’s deficiency in the construction of user interfaces, binding of data, and change notification, JavaFX has addressed these issues reasonably. However, there is no reason why Java couldn’t adopt Object Initializers as a way to simplify coding.

Comparing Owner Drawn in Winforms vs Swing

Monday, May 12th, 2008

I was having a play with custom renderers in Java Swing, and comparing them with the effort required in .NET. I find that in this case, the Swing approaches the problem at a higher level of abstraction (less effort), at the expense of a lot of new objects being created, while .NET goes for a straightforward custom paint.

Here’s an example in Swing, custom rendering JListbox control. Notice that we return a JLabel control here. This is what Swing does by default. We can also choose to return any controls, like combobox, et. c. There’s no additional painting required. In this sense, JListbox resembles a repeater control we see in WPF. The downside is a JLabel control is returned for every visible item in the listbox. Custom drawing can be done by creating an Anonymous inner class with an overridden onPaint handler.

                    jList1.setCellRenderer(new ListCellRenderer() {

                        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                                // By default, listbox renders using a label
                                JLabel display = new JLabel(value.toString());
                                display.setOpaque(true);
                                display.setBackground(isSelected ? Color.GRAY : Color.WHITE);
                                return display;
                        }
                    });

Contrast this with the J# implementation of custom painting in .NET (sourcecode nicked from MSDN), lots of low level painting, but no new objects being created or garbage collected. However, it’s not clear if you can reuse the paint() routine from an existing control.

private void listBox1_DrawItem(Object sender,
    System.Windows.Forms.DrawItemEventArgs e)
{
    // Set the DrawMode property to draw fixed sized items.
    listBox1.set_DrawMode(DrawMode.OwnerDrawFixed);
    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
    // Create a new Brush and initialize to a Black colored brush
    // by default.
    Brush myBrush = Brushes.get_Black();
    // Determine the color of the brush to draw each item based on the
    // index of the item to draw.
    switch (e.get_Index()) {
        case 0 :
            myBrush = Brushes.get_Red();
            break;
        case 1 :
            myBrush = Brushes.get_Orange();
            break;
        case 2 :
            myBrush = Brushes.get_Purple();
            break;
    }

    // Draw the current item text based on the current Font and the custom
    // brush settings.
    e.get_Graphics().DrawString(System.Convert.ToString(listBox1.
        get_Items().get_Item(e.get_Index())), e.get_Font(), myBrush,
        RectangleF.op_Implicit(e.get_Bounds()), StringFormat.
        get_GenericDefault());
    // If the ListBox has focus, draw a focus rectangle around the selected
    // item.
    e.DrawFocusRectangle();
} //listBox1_DrawItem

A Better DateTime Library for Java

Thursday, November 1st, 2007

lshift writes about how difficult it is to use Java’s simple date parser to take into account daylight savings, and offers a workaround. Then refers us to joda, a better java date time library.

SimpleDateFormat assumes, if it’s not told, that what it’s parsing is in the system timezone, so in London the string from before [ed: 3 Oct 2007] is interpreted as midnight on the 3rd of October, British Summer Time; i.e., eleven at night on the 2nd, UTC. That’s not a bad assumption, although I didn’t see it documented anywhere, and fits well with the rest of the formatting APIs and locales and so on. The problem is that there’s no way to stop it behaving like that.

via lshift, via tony

REST-compatible Ajax Patterns

Wednesday, June 6th, 2007

Can AJAX be used to strengthen REST-style programming? Yes! Here are some common scenarios where AJAX is better than standard HTML.

User authentication

Display authentication dialog on the URL where access is attempted, instead of redirecting to a logon screen, and then redirecting back.

Dialogs

Present dialogs using DHTML instead of popping up windows. URLs should be permanent if they are meant to be bookmarkable. Dialogs are temporal, and have no need for URLs.

ASP.net or JSF backbutton

The curse of the backbutton goes away when ajax is used with ASP.net or JSF applications. Instead of building up a history list of POSTs to the same page, back button works again, and brings user to the previous screen. (Note: 10 June 2007 - Turning on SmartNavigation in ASP.net has the same effect, through using an IFrame to postback.)

Wizards (Guided User Interaction)

Since wizards encapsulate actions within a single dialog, an Ajax implementation can progressively gather data until user finally commits the transaction.

Refreshing Value-Observer Pattern

This is part of the pop-up window problem. When a pop-up window mutates state, the parent window may need to refresh. Although this is possible via javascript, there is an element of cooperation that is required between the pop-up window and the originating window. This can limit reuse. This leads to an interesting question: what I like about simple URLs is that you can reuse and bookmark resources. What I don’t like about URLs is they pretty much suck for modal interaction, or where gosub style navigation is involved. How do you approach these in your web apps?

I’m keen to hear from you if there are more cases when you think Ajax is appropriate. Let me know!

JavaFX

Wednesday, May 16th, 2007

Cedric Beust hates it. Sam Ruby thought that its Excel-like dynamic binding is pretty cool. Dare Obasanjo thought that having choices are good. Srikumar Subramanian over at Lambda The Ultimate thought that it reminded him of AppleScript.

I saw JavaFX back when it was known as F3. If you take a look it’s history, it was initially started as a DSL to build GUIs. Having databinding makes sense. The dynamic binding referred to by Sam Ruby might enable some interesting animation effects, for instance, animating a skeleton-like object, where position of objects depends on where the other linkages are. There are a few other features, like asynchrony, which will be useful in an animation-rich language.

However, I believe JavaFX could have done a better job of designing an animation language more like Scratch, where it is easy to read (or visualize) the many threads of interaction that may occur. Or having a language where transitions can be easily expressed (e.g. tweening and easing a shape). Instead of a DSL for laying out GUIs, JavaFX should have looked to languages like Simula, which would have expressed behaviours better.

What do you think? What are the opportunities that JavaFX has missed out on?

Technorati: javafx jfx

Command-line debugging with Java

Friday, March 30th, 2007

Steps to debug Java apps in stone-age style:

  1. Run your program with additional switches
    java -Xdebug -Xrunjdwp:transport=dt_shmem,server=y,address=MyAppName,suspend=n -cp . test
  2. Run the command line debugger
    bin/jdb.exe -connect com.sun.jdi.SharedMemoryAttach:name=MyAppName
  3. Tell the debugger where the sources are
    sourcepath C:/Cygwin/Home/Chui
  4. Show list of threads, suspend the threads, display call stack, and step through code
$ bin/jdb.exe -connect com.sun.jdi.SharedMemoryAttach:name=MyAppName
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
Initializing jdb ...
> threads
Group system:
  (java.lang.ref.Reference$ReferenceHandler)0x14e Reference Handler cond. waiting
  (java.lang.ref.Finalizer$FinalizerThread)0x14f  Finalizer         cond. waiting
  (java.lang.Thread)0x150                         Signal Dispatcher running
  (java.lang.Thread)0x151                         Attach Listener   running
Group main:
  (java.lang.Thread)0x1                           main              running
> thread 1
main[1] suspend 1
main[1] where
  [1] java.io.FileInputStream.readBytes (native method)
  [2] java.io.FileInputStream.read (FileInputStream.java:199)
  [3] java.io.BufferedInputStream.read1 (BufferedInputStream.java:256)
  [4] java.io.BufferedInputStream.read (BufferedInputStream.java:317)
  [5] sun.nio.cs.StreamDecoder.readBytes (StreamDecoder.java:264)
  [6] sun.nio.cs.StreamDecoder.implRead (StreamDecoder.java:306)
  [7] sun.nio.cs.StreamDecoder.read (StreamDecoder.java:158)
  [8] java.io.InputStreamReader.read (InputStreamReader.java:167)
  [9] java.io.BufferedReader.fill (BufferedReader.java:136)
  [10] java.io.BufferedReader.readLine (BufferedReader.java:299)
  [11] java.io.BufferedReader.readLine (BufferedReader.java:362)
  [12] test.getName (test.java:10)
  [13] test.main (test.java:21)
main[1] step
>
Step completed: "thread=main", test.getName(), line=10 bci=22

Netbeans Autosubmit Drop Down Boxes

Tuesday, March 27th, 2007

The immediate attribute against the dropdown box is a bit misleading. This is wholly different from the autopostback=”true” attribute on ASP.net.

With JSF, you need to write your own javascript, or use the IDE context menu to write one for you.

Netbeans JSF Autosubmit DropDown Box

Here’s a code sample showing how to change the contents of a second dropdown box based on the value of the first one.

    public void dropDown1_processValueChange(ValueChangeEvent event) {

        String newValue = (String) event.getNewValue();
        java.util.ArrayList options = new java.util.ArrayList();
        if (newValue.equals("Australia"))
        {
            options.add(new Option("Sydney"));
            options.add(new Option("Canberra"));
            options.add(new Option("Brisbane"));
            options.add(new Option("Perth"));
            options.add(new Option("Melbourne"));
        } else if (newValue.equals("US")) {
            options.add(new Option("Washington"));
            options.add(new Option("New York"));
            options.add(new Option("Los Angeles"));
        } else if (newValue.equals("Japan")) {
            options.add(new Option("Tokyo"));
            options.add(new Option("Saitama"));
            options.add(new Option("Niigata"));
        }

        int size = options.size();
        Option[] optarr = new Option[size];
        options.toArray(optarr);
        dropDown2DefaultOptions.setOptions(optarr);
    }

CachedRowSetDataProvider Bug when removeRow and appendRow called without commitChanges

Monday, March 26th, 2007

Here’s the test case and stack trace

    public String btnTest_action() {

        getMaintdayitemDataProvider().removeRow(getMaintdayitemDataProvider().getCursorRow());
        getMaintdayitemDataProvider().appendRow();
        getMaintdayitemDataProvider().cursorLast(); //
        return null;
    }

java.lang.IllegalArgumentException: CachedRowSetRowKey[2]
        at com.sun.data.provider.impl.CachedRowSetDataProvider.setCursorRow(CachedRowSetDataProvider.java:346)
        at com.sun.data.provider.impl.CachedRowSetDataProvider.cursorLast(CachedRowSetDataProvider.java:415)
        at precisweb.maintday.btnTest_action(maintday.java:678)

Netbeans Visual Web Selecting Rows

Saturday, March 24th, 2007

The UI presentation layer doesn’t hold state about which rows were selected.

Winston Prakash outlines how selecting a single row in Netbeans JSF table can be done, but it was a little roundabout.

Here’s a simpler take on it:

Bind a TableRowGroup’s selected attribute to a property on your page.


       <ui:tableRowGroup
             binding="#{Page1.tableRowGroup2}"
             id="tableRowGroup2"
            selected="#{Page1.selected}" 
            sourceData="#{Page1.myDataProvider}"
            sourceVar="currentRow">

Next just write the callback function, in our case, the selected row is the current cursor row, but it could be anything of course:

public boolean getSelected()
{
    RowKey rk = (RowKey) getValue("#{currentRow.tableRow}");
    return rk.equals(myDataProvider.getCursorRow());
}

Changing up the datasource name in a Netbeans project

Friday, March 23rd, 2007

In your personal directory, there is a Netbeans configuration file called context.xml, it has a list of datasources and their jdbc URLs

C:\Documents And Settings\Chui\.netbeans\5.5\context.xml


<context name="java:comp">
    <context name="env">
        <context name="jdbc">
            <object name="TravelPack" class="com.sun.rave.sql.DesignTimeDataSource">
                <arg class="java.lang.Boolean" value="false"/>
                <arg class="java.lang.String"/>
                <arg class="java.lang.Boolean" value="true"/>
                <arg class="java.lang.String" value="org.apache.derby.jdbc.ClientDriver"/>
                <arg class="java.lang.String" value="jdbc:derby://localhost:1527/travel"/>
                <arg class="java.lang.String"/>
                <arg class="java.lang.String" value="travel"/>
                <arg class="java.lang.String" value="D536B001AA3434DE"/>
            </object>

Start up Netbeans, in your session bean, each of the CachedRowSet has a named datasource in the property sheet, you may need to change it:

Netbeans change datasource name

And that’s it!

NetBeans, Derby, JSF and Jetty

Sunday, March 4th, 2007

Netbeans 5.5 has made developing web apps almost as easy as Microsoft’s flagship Visual Studio. However, there are still elements which can still be hard to figure out. Here are some personal notes:

1. The Derby databases are located in your home directory, under .netbeans-derby. (In Netbeans, Tools, Java DB Database, Create Java DB Database … reveals the derby.system.home)

e.g. C:\Documents And Settings\Chui\.netbeans-derby

2. Deploying JSF applications on Jetty requires a minimum Jetty-6.1.2.rc0. Previous versions fail parsing faces-context.xml, due to the logging interface not being completely implemented. (Bug number: JETTY-222)

3. Deploying database backed webapps on Jetty requires the webapps-plus config (for JNDI to work).

java -jar start.bat etc/jetty.xml etc/jetty-plus.xml

(Drop the .war in webapps-plus directory)

4. Configuring JNDI on Jetty requires the following file in your web app

webapps-plus/WebApplication2/WEB-INF/jetty-env.xml

<?xml version="1.0" ?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.mortbay.org/configure.dtd">
<Configure class="org.mortbay.jetty.webapp.WebAppContext">
  <!-- Add a DataSource only valid for this webapp                     -->
  <New id="mydatasource" class="org.mortbay.jetty.plus.naming.Resource">
    <Arg>jdbc/TravelPack</Arg>
    <Arg>
     <New class="org.apache.derby.jdbc.ClientDataSource">
        <Set name="databaseName">travel</Set>
        <Set name="password">travel</Set>
        <Set name="serverName">localhost</Set>
        <Set name="portNumber">1527</Set>
        <Set name="user">travel</Set>
    </New>
    </Arg>
<Configure>

5. derbyclient.jar needs to be in Jetty’s lib directory

Full Text Indexing in Ruby is Faster than Java

Wednesday, November 22nd, 2006

Jim Wiseman John Wiseman, who is porting Ferret to Lisp, reports on the blazing performance of Ferret.

(Ferret was originally a port of Lucene, but recent alteration to the file format has increased performence 5x over GCJ, and then the author ported to C to get an order of magnitude improvement.)

The moral of the story is not one of premature optimization, but working with pliable languages vs working with brittle ones.

ActiveX is the weakest link

Thursday, July 27th, 2006

Once in a while, it is gratifying to see how Microsoft’s embrace and extend comes back and bite them in the a***. Take Microsoft’s Internet Explorer, back when MS was defending their Windows OS turf against Netscape’s Browser OS. Microsoft, in their infinite wisdom, decided to extend the browser to include ActiveX applets. Now there is already a large base of ActiveX components on the Windows platform, so naturally, adding ActiveX components to web browsers would help entrench Microsoft’s dominance on the client side right?

As history has turned out, the answer is a resounding NO. Despite Microsoft’s security push on Windows XP to secure the operating system (which in-turn brought on Longhorn delays), ActiveX applets has become Internet Explorer’s Achiles heel. Spyware and malware authors are exploiting Active X vulnerabilities to hijack user’s PC, turning once healthy operating system into zombies, controlled by botnets.

Take a look at the Month of Browser Bugs weblog. Almost every Internet Explorer crash is due to a badly written ActiveX component. No matter how hard Microsoft works, the surface area of Active X components is simply too big to defend. Worse still, ActiveX on MS browsers have been supported for years, meaning Microsoft would have to take a quite bit of flak should they even attempt to disable ActiveX support.

Note, I am not referring to malicious ActiveX components, which Microsoft has partially addressed in XP SP2. XP SP2 adds a small hurdle that stops Internet Explorer users from accidentally installing ActiveX components. The crashes referred to above are ActiveX controls developed by Microsoft. A skilled programmer can engineer a crash that lets them install their software on your computer without your permission. I didn’t realize how many there are that are enabled for use with Internet Explorer. Some of them deal with the amazing page transition effects you see when you visit some web sites. Others deal with Windows HTML Help. Useful as they are, I’d rather not have these snazzy things if it means I don’t have to wipe my computer clean every year.

Now, some readers might wonder what about Firefox. Firefox supports applets too. However, these applets are not of the ActiveX variety. Firefox supports Java applets. The difference? ActiveX components are typically developed in C, C++, and VB. C and C++ are programming languages where the programmer has to take extra care to manage memory allocation and deallocation, otherwise, a program simply crashes. ActiveX components written in VB are markedly safer, as long as these VB components do not in turn use ActiveX components written in C or C++. In contrast, applets written in Java (like VB applets) suffer none of the problems of memory management (i.e. does not result in memory exceptions). In addition, Java applets can call a very limited number of routines that are developed in C, and this makes Java runtimes easier to defend against malicious websites.

Microsoft can’t afford to annoy clients who have developed legitimate business applications based on ActiveX applets, but at the same time Microsoft can’t concentrate on new product lines if it is constantly defending undefendable ground. Readers, if you were Bill Gates, what would you do? Would you cut your losses and run?

JRuby on Rails

Sunday, June 11th, 2006

This piece of news about JRuby on Rails ought to make James McGovern sit up.

Incidentally, I have been experimenting with a Rails clone in PHP called Cake PHP. It was pleasant, and remarkably close to Rails. Given how widely PHP is supported in the web hosting world, Cake seems to give a PHP developer a reasonable headstart.

I’d have loved to have the default admin screens that Django provides though.

Transporting Data in Web Services

Monday, March 27th, 2006

Jim Waldo on language independent means of transporting data:

First of all, it means that you need to have a language-independent mechanism for passing data from one place to another. But there is no more a language-independent way of expressing data than there is a language-independent way of expressing objects. If I tell you that a data type is an int, you don’t know its size unless you know if it is an int in Java, of C (well, even then you won’t necessarily know) or C++. But you do know that I’m not talking about COBOL; but if you want to talk COBOL you need to know how to translate my int into your PIC 9(x) for some value of x.

The language of integration should be based around the language of humans, not the language of computers. Here’s a check list for anyone crafting an interface for integration that humans can understand.

  • Integers - if range is not specified, then it is the entire universe of possible integers
  • Date and time - either use UTC or timezone and daylight savings information
  • Currency - specify units and timestamp
  • Floating point - don’t use this! use decimals instead

Anything else I missed?

A forum with no members

Saturday, March 11th, 2006

Netbeans has a code colloboration feature and integration into real-time public chat rooms. Let’s see, I signed up an account and browsed the list of public discussions.

A big list shows up and signing into a few of them turned out to be empty.

How’s a new guy supposed to find some help?

A list of active and public discussions would be handy, or just cull inactive discussions periodically.

Another option is to limit the creation of new discussions when there are too few people on the system and funnel them to a few more populated areas.