Friday, August 17, 2007

Little JRuby experiment

Today I ran a Ruby program from a previous post with JRuby. I worked without modifications!

It's very nice to know that you can access Java libraries from within a Ruby. For example I decided to do a little experiment to create a TreeModel to display the contents of the loaded XSD definition in a JTree.

Here's an initial (and incomplete) implementation of the model:


require "java"
include_class 'javax.swing.JTree'
include_class 'javax.swing.JFrame'
include_class 'javax.swing.JScrollPane'
include_class 'java.awt.BorderLayout'
include_class 'javax.swing.tree.TreeModel'

class XsdTreeModel
include TreeModel
attr_reader :schema

def initialize(s)
@schema = s
end

def getChild(a,i)
case a
when XSDInfo::SchemaInformation
return a.elements.values[i]
when XSDInfo::SchemaElement
return a.element_type
when XSDInfo::SchemaComplexType
return a.attributes.values[i]
end
end
def getChildCount(a)
case a
when XSDInfo::SchemaInformation
return a.elements.length
when XSDInfo::SchemaElement
return 1
when XSDInfo::SchemaComplexType
return a.attributes.length
else
return 0
end
end
def getIndexOfChild(a,h)
case a
when XSDInfo::SchemaInformation
return a.elements.values.index(h)
when XSDInfo::SchemaElement
return 0
when XSDInfo::SchemaComplexType
return a.attributes.index(h)
else
return -1
end
end

def getRoot()
return @schema

end

def isLeaf(o)
return false
end

# Interface methods without implementation

def addTreeModelListener(l)
end
def removeTreeModelListener(l)
end
def valueForPathChanged(arg0, arg1)
end
end




Now we can use it:


sc = XSDInfo::SchemaCollection.new
sc.add_schema XSDInfo::SchemaInformation.new("xhtml1-strict.xsd")
sc.namespaces.each {|ns| sc[ns].solve_references sc}
a_schema = sc[sc.namespaces[0]]

f = JFrame.new
f.setSize(300,300)

f.getContentPane.setLayout(BorderLayout.new)
tree = JTree.new
sp = JScrollPane.new(tree)

tree.setModel(XsdTreeModel.new(a_schema))
f.getContentPane.add(sp,BorderLayout::CENTER)

f.setVisible(true)


Running this program generates the desired tree: