Tuesday, March 25, 2008

Summer of code 2008: what will you be doing?

As posted earlier that OpenMRS is participating in Google Summer of Code as a mentoring open source project. Working with OpenMRS will be highly rewarding knowing that you are single-handedly affecting the lives of people in developing nations ravaged by HIV/AIDS. If you are a student (undergaduate/graduate) you are eligible! So go apply for summer of code with OpenMRS! Student applications opened up yesterday and will be accepted up until Monday, March 31st 2008.

Stop by #openmrs on irc.freenode.org for more information -- ask for docpaul or burke.

Monday, March 24, 2008

Update: weird properties bug in the prototype

Okay, I sent an email to the kijaro mailing list and apparently the runtime library only has support for read-write properties. Which does indeed explain the bugs I was experiencing.
The respone:

Hi robby, thanks for testing, i will incoporate test cases based on your examples
in the test suite.
Currently properties is in a weird state between version 3 and unpublished version 4
of the spec. I've done major design changes. I have rewrittent the runtime support,
drop the writeonly properties from the spec, etc.

Currently the runtime library (java.lang.Property and helper classes)
only support read-write property, i think it explain these bugs.

Expanding on Properties

It it worth nothing that in groovy, properties already exist. let's give an example:

class Book {
String title;
}
def gina = new Book();
gina.title = "Groovy In Action";
println gina.title;


Groovy basically generates the getters/setters behind the scenes, but in essence these are for all intensive purposes -- properties. I felt that this needed to be addressed.

Sunday, March 23, 2008

Java gets some Properties.

There is a proposal to add properties to java. Properties will eliminate the need for getters/setters in the usual javabeans pattern style. I'm sure you wanna see some code examples, so as usual, i'll give you the way it's done currently, in this case following the JavaBeans spec of specifying a getter/setter. To run this code you'll need to go and check out the prototype compiler from the subversion repository at java.net. You will need to register. After you have done that type:
svn checkout https://kijaro.dev.java.net/svn/kijaro/branches/properties kijaro --username username --password yourpassword
replace username and yourpassword with the username and password you registered with.

Apache Ant is required to build the compiler.

Now to compile it (instructions are for users running linux;
if running windows i assume you know your OS properly to adjust this).
1) type cd kijaro/langtools/make
2) type ant -Dboot.java.home=$JAVA_HOME
3) now to compile the code you'll do /path/to/kijaro/bin/kijaro-javac /path/to/ClassName.java setting your classpath as needed.
4) To run this, you can either use /path/to/kijaro/bin/kijaro-java /path/to/ClassName or you can use your installed JRE and do: java /path/to/ClassName

That's all you need to know to run this code. Questions? email me.


/**
* Created: Mar 23, 2008 9:13:54 PM
*
* @author Robert O'Connor
*/
public class BeanExample {
private String userName;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public static void main(String[] args) {
BeanExample example = new BeanExample();
example.setUserName("rob");
System.out.println(example.getUserName());
}
}

The getters/setters are boiler-plate code that just isn't necessary. Most IDEs will generate getters/setters for you with the click of a mouse; but still it makes your code verbose. Now I wrote three examples for properties, since there are three types: read-only,read-write and write-only. Each example showcases just one of those types for reasons of simplicity. First, I'll tackle the example of a read-only property.


/**
* Created: Mar 22, 2008 5:37:41 PM
*
* @author Robert O'Connor
*/
public class ReadOnlyPropertiesExample {
private String userName;
public property String name get { return userName; };

public ReadOnlyPropertiesExample() {
this.userName = "rob";
}

public static void main(String[] args) {
System.out.println(new ReadOnlyPropertiesExample().userName);
}

}

Already, you can see that we've removed a great deal; and it's not that as verbose as the JavaBean example. Now let's see what happens if I try and write to the property? It's a compile-time error; or at least it should be. As of the latest prototype compiler, it didn't complain and happily let me write to the property. Now let's see a properties example that behaves properly as defined by the spec.


/**
* Created: Mar 23, 2008 8:11:41 PM
*
* @author Robert O'Connor
*/
public class ReadWritePropertiesExample {

private String userName;
public property String name
get { return userName; }
set(String name) { userName = name; };

public static void main(String[] args) {
ReadWritePropertiesExample example = new ReadWritePropertiesExample();
example.userName = "rob"; // set the name
System.out.println(example.userName); // output it.
example.userName = "robby"; // set it to something different
System.out.println(example.userName); // output the new value
}
}

Okay, this is a read-write property; note that example.userName is NOT using direct field access. The final example is a write-only example; note that it is a compile-time error to attempt to retrieve the value; however the compiler currently let's you do it; which in my opinion is bad. I coded against the spec, so to circumvent that, I defined a getter (I know properties are supposed to eliminate those, but I needed a way to test that the value was set properly.)


/**
* Created: Mar 23, 2008 8:45:02 PM
*
* @author Robert O'Connor
*/
public class WriteOnlyPropertiesExample {
private String userName;
public property String name set;

/**
* this is used purely to check that the property set the field's value properly.
* @return the username
*/
public String getUserName() {
return userName;
}

public static void main(String[] args) {
WriteOnlyPropertiesExample example = new WriteOnlyPropertiesExample();
example.userName = "rob"; // we can only *SET* it since it's write-only
System.out.println(example.getUserName());
example.userName = "robby";
System.out.println(example.getUserName());
}

}

Okay, now that you've gotten a taste of what's to come (if this makes it passed the JCP that is!) go out and play!

Saturday, March 22, 2008

Futurama fans: Listen up

There's a nifty unix command you can enter to get random futurama quotes:
curl -Is slashdot.org | egrep '^X-(F|B)' | cut -d \- -f 2

Okay, so how does it work? Let's look at what curl -Is slashdot.org returns:

HTTP/1.1 200 OK
Date: Sun, 23 Mar 2008 01:04:28 GMT
Server: Apache/1.3.37 (Unix) mod_perl/1.29
SLASH_LOG_DATA: shtml
X-Powered-By: Slash 2.005000198
X-Leela: I'm a millionaire! Suddenly I have an opinion about the capital gains tax.
Cache-Control: private
Pragma: private
Vary: User-Agent,Accept-Encoding
Connection: close
Content-Type: text/html; charset=iso-8859-1

Pretty neat eh?
Now, what it does is it looks for lines that start with "X-" and contain F or B after the "X-"; thus bringing up Fry or Bender quotes only :).

Wanna make some money while making a difference?

Hey guys,

OpenMRS is an open source medical records system that is used in many third-world developing countries where HIV/AIDS is an epidemic. Now here's where you can make a difference: They are participating in Google Summer of Code. You can make $4500 this summer while making a difference in the lives of people ravaged by the HIV/AIDS epidemic in developing third-world countries. Here's how it works: at the beginning you will get $500; after the mid-term evalations you will get $2000; at the end you will get the final $2000. Check out the projects you could potentially work on! For an overview click here.

Apply here.

Drop by #openmrs on irc.freenode.org for more information. Ask for docpaul, burke or bwolfe

Friday, March 21, 2008

Swing first class w/ FCM.

I got to play with the First-Class methods (FCM) prototype; it's pretty cool. So here we go: Java version then FCM version.

To run the FCM version: compile it using the prototype; then simply type: java FCMGui and you're set. If you need help feel free to e-mail me.


import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
* Created: Mar 19, 2008 5:48:43 PM
*
* @author Robert O'Connor
*/
public class UsualJavaGui {
JFrame frame = new JFrame("Usual Java Example");
JButton button = new JButton("Press me");

public UsualJavaGui() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed");
}
});
frame.add(button);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
new UsualJavaGui();
}
});

}
}

Standard java Swing GUI with a frame and a button; press it a message appears in your console. Now, FCM version:


import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;

/**
* Created: Mar 21, 2008 6:55:52 PM
*
* @author Robert O'Connor
*/
public class FCMGui {
JFrame frame = new JFrame("FCM Example");
JButton button = new JButton("Press Me");

public FCMGui() {
button.addActionListener(#(ActionEvent evt) {
System.out.println("Button pressed");
});
frame.add(button);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(# { new FCMGui();
});

}
}

Same thing: But what the hell is going on? First off, what we declared is called an anonymous inner method; if you remember, it's a First-Class method meaning that it exists in itself. Currently in java, a method must be enclosed in a class, and cannot be referred to on a first-class level.

Automatic Resource Management Blocks (ARM) in action

I've been a busy blogger lately. Here's my experiment with Automatic Resource Management Blocks (ARM). First, I will show you how resource management is done in java; then i'll give you the ARM way to do things. To run the ARM example you need the latest cice/arm prototype. Now, let's see the java way.
But before I do, You'll need the following (copy and paste it into a text file and name it "names.txt" (no double quotes):
 
Josh Bloch
Bob Lee
Doug Lea

By the way, the names here are of the authors of the Concise Instance Creation Expression/Automatic Resource Management Blocks proposal. Okay, now that you have the file needed to run this program. Save names.text to the same directory where your class will reside and I assume you know how to compile/run a java program.
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.io.File;

/**
* Created: Mar 21, 2008 12:46:07 AM
*
* @author Robert O'Connor
*/
public class JavaExample {
BufferedReader r = null;

public JavaExample() {
try {
r = new BufferedReader(new FileReader(new File("names.txt")));
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(r!=null)r.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

public static void main(String[] args) {
new JavaExample();
}
}

It is overly verbose and cumbersome to clean up resource leaks that could occur. if I eliminated the finally block from my above example and an exception occured, the stream would never be closed and would leak. So we have to use a try-catch-finally to clean up. Remember, finally blocks are always executed. Closing the stream throws an exception so we have to catch that too! Enter Automatic Resource Management Blocks (ARM).

 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
* Created: Mar 21, 2008 12:25:43 AM
*
* @author Robert O'Connor
*/
public class ARMExample {
BufferedReader r = null;

public ARMExample() throws IOException {

do (r = new BufferedReader(new FileReader(new File("names.txt")))) {
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
}
}
public static void main(String[] args) throws IOException {
new ARMExample();
}

}

That is NOT a do-while loop, or a loop at all for that matter. It is the automatic resource management block. As you can see it drastically reduced the boiler plate code, try-catch-finally; it doesn't eliminate unchecked exceptions. You still have to catch what's being thrown and recover from it if possible. The point is to manage your resources automatically, eliminating resource leaks.

Thursday, March 20, 2008

Swinging: BGGA style.

So, to continue on with my playing w/ java closures, I now present Swing event handling: BGGA Style. Again, to compile this you will need the BGGA prototype. You can run it using your installed jre.

First, i'll show you the java version:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
* Created: Mar 19, 2008 5:48:43 PM
*
* @author Robert O'Connor
*/
public class UsualJavaGui {
JFrame frame = new JFrame("Usual Java Example");
JButton button = new JButton("Press me");

public UsualJavaGui() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed");
}
});
frame.add(button);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
new UsualJavaGui();
}
});

}
}

I think you get the gist of what it does. Now the BGGA version.

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;

/**
* Created: Mar 19, 2008 7:35:15 PM
*
* @author Robert O'Connor
*/
public class BGGAGui {
JFrame frame = new JFrame("BGGA Frame");
JButton button = new JButton("Press me");

public BGGAGui() {
button.addActionListener({ActionEvent evt => System.out.println("Button pressed");});
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
// thanks to neil gafter!
SwingUtilities.invokeLater({ => new BGGAGui(); });

}
}

What occurs within the the addActionListener() is that when you click the button, that closure is invoked; it does the same thing the java one does (print "Button pressed" to the screen). I'm not sure how to write the invokeLater() method using BGGA to reduce its verbosity. If anybody knows, could you tell me? When the code is executed; the closure is executed and a frame is displayed; yadda yadda.

Wednesday, March 19, 2008

Concise Instance Creation Expressions (CICE)

Another proposal CICE is being put out there for Java 7. To compile the code posted here you will need the latest cice prototype. You can run it using your installed jre. Now, let's get down to the code! First I'm gonna show you the current Java version, then I'll show you the CICE version.

Java Version

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;

/**
* Created: Mar 19, 2008 5:48:43 PM
*
* @author Robert O'Connor
*/
public class UsualJavaGui {
JFrame frame = new JFrame("Usual Java Example");
JButton button = new JButton("Press me");

public UsualJavaGui() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed");
}
});
frame.add(button);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
new UsualJavaGui();
}
});

}
}

Now, the main problem people have with java is that it's overly verbose, and they're right in that aspect. CICE aims to reduce that verbosity; by making it more concise and to the point. Now you know the basics of that implementation; it's a simple JFrame with a button that when you click it will display a message in your console.

Now the same app but with CICE:

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
* Created: Mar 19, 2008 5:57:45 PM
*
* @author Robert O'Connor
*/
public class CICEGui {
JFrame frame = new JFrame("CICE Gui");
JButton button = new JButton("Press me");

public CICEGui() {
button.addActionListener(ActionListener(ActionEvent e){
System.out.println("Button pressed");
});
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(Runnable() {
new CICEGui();
});
}
}


The above is a lot less verbose; What's missing? You'll notice the difference primarily in the main() method and the addActionListener() method call to attach the event listener to my JButton.
What's missing? That's right the
public void run() { ... }
and
public void actionPerformed(ActionEvent e) { ... }
How can this be and how do I get access to the ActionEvent reference? Well notice the following:
button.addActionListener(ActionListener(ActionEvent e) {
System.out.println("Button pressed");
});
I passed in the ActionEvent parameter to the Concise Instance Creation Expression! Using CICE, I was able to eliminate the methods. Also note, that I was able to eliminate using the word new is not needed with CICE. I was also able to state my intent cleanly, and in a lot less verbose way. How many lines were eliminated between the Java version and the CICE version?

(rob-laptop)rob@~/playground/src/main/java$ wc -l misc/UsualJavaGui.java misc/CICEGui.java
43 misc/UsualJavaGui.java
34 misc/CICEGui.java
77 total
(rob-laptop)rob@~/playground/src/main/java$

Well, that's 9 lines! Why should you have to type out the method definition if there is only ONE method in the interface or abstract class?

Groovy is kinda really groovy

public class StringTester { 
    public static void main(String[] args) {
        System.out.println(new String("foo") == "foo"); 
    }
}

Now the above code will evaluate to false. However if I changed it to:
"foo" == "foo"
it will be true. Reason: Java interns String literals. This is precisely why using == on String isn't advised. However groovy converts all == instances to .equals() so we basically get the same result as if we interned the String in java. This makes sense, since in groovy there are no primitive data types; it uses the wrapper classes from java. Integer, Double, Byte, etc. More information about the wrapper classes can be found here.
class StringTester { 
    static void main(args) {
        println new String("foo") == new String("foo") 
        println new String("foo") == "foo"
        println "foo" == "foo" 
    }
}

All three cases will evaluate to true. Now we can modify the java code so that it behaves the same way groovy did:

public class StringTester { 
    public static void main(String[] args) {
        System.out.println(new String("foo").intern() == "foo");
        System.out.println(new String("foo").intern() == new String("foo").intern()); 
    }
}

Now both will evaluate to true! Interesting thing =)

For more information about interned Strings check out this

Monday, March 17, 2008

Closures in java: Fibonacci gets some closure

So, in my previous post I promised an example; it's a simple example. In order to compile it you will need to download the BGGA prototype. You can run it using your installed jre. I'll fiddle with it some more but i wanted to put this one up, so here we go:

public class FibonacciSequenceWithClosures {
public static void main(String[] args) {
int fib = {int n => fib(n)}.invoke(Integer.parseInt(args[0]));
System.out.println(fib);
}

/**
* Helper method to recursively calculate the
* n-th number in the fibonacci seqeunce.
* @param n
* @return the n-th number
* @throws IllegalArgumentException if you pass in a negative number
*/
public static int fib(int n) {
if(n < 0) {
throw new IllegalArgumentException("Must be Postive!");
} else if(n == 1 || n==2) {
return 1;
} else {
return fib(n-1) + fib(n-2);
}
}
}



What's going on here? Let's examine it line by line. First you've got your familiar standard class definition; I declare a variable named fib, I'm sure you're asking the what the heck is
 int fib = {int n => fib(n)}.invoke(Integer.parseInt(args[0]));
Answer: it's a closure! We'll examine that line closer.
int fib = { int n => fib(n)}.invoke(Integer.parseInt(args[0]));
First, we have the parameters that we're passing into the closures, then you see
int fib = { int n => fib(n)}.invoke(Integer.parseInt(args[0]));
and you're probably wondering what in god's name that operator is, it's the closure operator! Now, the final piece:
int fib = { int n => fib(n)}.invoke(Integer.parseInt(args[0]));
What i'm doing here, is calling the invoke method on the closure itself, and passing in the first argument passed to the program via a command-line argument. Finally, After all this is done, I print the value returned from the closure that i stored in the variable fib and we're done. You'll get a StackOverFlowException if you pass too large a number. I could probably fix this, but this is sufficient for a simplistic example.

Closures in java

I have the tendency to come off as a real idiot sometimes; and I tend to evangelize anything that looks remotely cool; and that's true, but BGGA closures, looks interesting to me. However, after I watched Josh Bloch's The Closures Controversy [slides] a few weeks ago, I got very turned off. The latest prototype looks a little bit better. I'll fiddle with it and post the code I wrote up here. Once again, I've yet to play with it, but perhaps it's better? All I know is that the groovy-like syntax for the closure operator piques my interest.