Sunday Dec 16, 2007

I just completed a new Netbeans JRuby tutorial. This tutorial will show you how you can easily package up your Ruby application into a single Jar file.
 

Check out the tutorial here,  Swing with JRuby part II: Packing JRuby Desktop Application

 

This tutorial focuses on how to package existing Ruby application. If you are looking for tutorial on how you can create JRuby desktop application from scratch, you may find the tutorial I had created earlier helpful:

 Swing with JRuby: Developing Desktop Application with JRuby and Java Swing API

 

Tuesday Sep 11, 2007

Recently a developer has emailed me for any suggestions and tips for SCJP (Sun Certified Java Programmer) exam preparation. I took SCJP exam about two years ago. Just as I typed up replying email I found that these tips are quite useful for anyone, especially students who plan to take SCJP certification exam.

Get an exam prep book

You can find a few SCJP prep book on amazon. I actually went to a bookstore near my house and skim through a few. The one I picked was "SCJP Sun Certified Programmer for Java 5 Study Guide by Kathy Sierra, Bert Bates" and it is simply amazing. This book covers all the topics. It's the only main material I used for preparation. It does more than getting me through the exam, it did a great job laying solid foundation on Java as well. I still keeps it on handy on my bookshelf.

Is only one book enough?

Yes, one is enough. I'm not getting commission or anything advertising this book. I think any exam prep books can get you through the exam if you really work it, cover to cover that is.

Someone told me about 'certification exam braindump' ?

Check out some braindump websites. Don't get confuse with those website that try to sell you their exam prep material. There are web forums where people post their study tips and exam experience. These braindumps won't tell you what's on exam but give you an idea of what it's like.

Again, it's really your choice if you want to purchase some sample test questions from many vendors advertising on Google (they are actually the same company). Going through enough braindumps sample test questions may help you passing the exam, but what's missing will still be missing - the solid knowledge foundation.

What about Sun practice exam?

Sun practice exam will surely help. I got a chance to go through Sun SCJP practice exam questions after I got my cert. I found it to be much more informative and right on the exam topic than of other vendors. My advice on this though is, no matter how many preps you have, do not to take them for grant, use them as supplementary material to your learning.

Yes, I am ready to take on the exam!

This is in fact, my most critical tip for SCJP exam preparation. When you feel you're ready, take a deep breath and slowly go through each of the exam objectives (in the book's index or listed on Sun website). Without looking at any notes, write down everything you understand about each objective. Then check for correction. This will help making sure that you really have good understanding on all topics and boost your confidence.

Do I need to practice?

Practice makes perfect! I passed the exam with pretty good score for someone who doesn't do Java everyday. If you work with real-world Java everyday, there should be no problem. If not, try out as many sample code (from prep book) as possible. Hand-typing the code will make it stick to your brain better than just reading through the text.

Ok, I'm a Java guru and I've read quite a number of Java book, I shouldn't need the exam prep material right?

Studying normal Java book does not ensure that you'll pass the exam. Regular Java book aims to give you enough knowledge to do real-world work, unfortunately, what you'll find on the exam is a different story. To pass the SCJP, you also needs to know some non-common-sense stuffs, theoretical topics, in and out, and the "nice to know" of Java. That's why I really suggest you grab a prep book, it help you with that.

One more thing(s):

Of course I won't tell you what's on the exam =). Here are few things I think you should get solid understanding of before taking the test. They are not as trivial as they seem to be!


  • Threading

  • Array, Generic, and collections

  • Object-oriented concept

  • Inner class and anonymous classes


Hope this help and good luck =]

Sunday Sep 02, 2007

There're a number of way to do XML serialization in Java. If you want fine-grained control over parsing and serialization you can go for SAX, DOM, or Stax for better performance. Yet, what I often want to do is a simple mapping between POJOs and XML. However, creating Java classes to do XML event parsing manually is not trivial. I recently found JAXB to be a quick and convenient Java-XML mapping or serialization.

JAXB contains a lot of useful features, you can check out the reference implementation here. Kohsuke's blog is also a good resource to learn more about JAXB. For this blog entry, I'll show you how to do a simple Java-XML serialization with JAXB.

POJO to XML

Let's say I have an Item Java object. I want to serialize an Item object to XML format. What I have to do first is to annotate this POJO with a few XML annotation from javax.xml.bind.annotation.* package. See code listing 1 for Item.java

From the code
@XmlRootElement(name="Item") indicates that I want <Item> to be the root element.
@XmlType(propOrder = {"name", "price"}) indicates the order that I want the element to be arranged in XML output.
@XmlAttribute(name="id", ...) indicates that id is an attribute to <Item> root element.
@XmlElement(....) indicates that I want price and name to be element within Item.

My Item.java is ready. I can then go ahead and create JAXB script for marshaling Item.

//creating Item data object
Item item = new Item();
item.setId(2);
item.setName("Foo");
item.setPrice(200);
.....

JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(item, new FileWriter("item.xml")); //I want to save the output file to item.xml

For complete code Listing please see Code Listing 2 (main.java). The output Code Listing 3 item.xml file is created. It looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:item ns1:id="2" xmlns:ns1="http://blogs.sun.com/teera/ns/item">

<ns1:itemName>Foo</ns1:itemName>
<ns1:price>200</ns1:price>

</ns1:item>

Easy right? You can alternatively channel the output XML as text String, Stream, Writer, ContentHandler, etc by simply change the parameter of the marshal(...) method like

...
JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(item, <java.io.OutputStream instance>); // save xml output to the OutputStream instance

...
JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(item, sw); //save to StringWriter, you can then call sw.toString() to get java.lang.String

XML to POJO

Let's reverse the process. Assume that I now have a piece of XML string data and I want to turn it into Item.java object. XML data (Code listing 3) looks like

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:item ns1:id="2" xmlns:ns1="http://blogs.sun.com/teera/ns/item">
<ns1:itemName>Bar</ns1:itemName>
<ns1:price>80</ns1:price>
</ns1:item>

I can then unmarshal this xml code to Item object by

...
ByteArrayInputStream xmlContentBytes = new ByteArrayInputStream (xmlContent.getBytes());
JAXBContext context = JAXBContext.newInstance(Item.getClass());
Unmarshaller unmarshaller = context.createUnmarshaller();
//note: setting schema to null will turn validator off
unmarshaller.setSchema(null);
Object xmlObject = Item.getClass().cast(unmarshaller.unmarshal(xmlContentBytes));
return xmlObject;
...

For complete code Listing please see Code Listing 2 (main.java). The XML source can come in many forms both from Stream and file. The only difference, again, is the method parameter:

...
unmarshaller.unmarshal(new File("Item.xml")); // reading from file
...
unmarshaller.unmarshal(inputStream); // inputStream is an instance of java.io.InputStream, reading from stream

Validation with XML Schema

Last thing I want to mention here is validating input XML with schema before unmarshalling to Java object. I create an XML schema file called item.xsd. For complete code Listing please see Code Listing 4 (Item.xsd). Now what I have to do is register this schema for validation.

...
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
.newSchema(new File("Item.xsd"));
unmarshaller.setSchema(schema); //register item.xsd shcema for validation
...

When I try to unmarshal XML data to POJO, if the input XML is not conformed to the schema, exception will be caught. For complete code Listing please see Code Listing 5 (invalid_item.xml).


javax.xml.bind.UnmarshalException
- with linked exception:
javax.xml.bind.JAXBException caught: null
[org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: 'item1' is not a valid value for 'integer'.]

Here I change the 'id' attribute to string instead of integer.

If XML input is valid against the schema, the XML data will be unmarshalled to Item.java object successfully.

I leave out detail on data encryption and XML digital signature and gazillion of things you can do with JAXB. My goal here is to make the case for JAXB as an alternative way for XML serialization. For more information on JAXB, please check out these links:

- Kohsuke's blog
- Netbeans 6 JAXB tutorial
- Java EE 5 JAXB tutorial

This blog copyright 2009 by teera