Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday, July 13, 2008

JavaFX Script Overview

Introduction

In this post I'll show a little program written in JavaFX Script that exercises some of its features such as graphics, data binding and programming language interaction.

This is the first of a series of posts exploring these features across different platforms such as Silverlight or Flex.

The example


A little program that calculates and plots a polynomial that touches four points selected by the user. The user can move any of the given points in the screen and the polynomial will be recalculated and replotted while moving it.

Neville's algorithm

The Neville's algorithm is used to calculate the polynomial that traverses the points selected by the user.



The user will select a series of points (x0,y0),(x1,y1),etc. that will be used as the input for this algorithm given that y0 = f(x0). Each entry of the Q matrix will stored as a Polynomial object, so the final result Qn,n will be the Polynomial to be plotted.

More information on this algorithm can be found in its Wikipedia page, its MathWorld page or a Numerial Analysis book such as the one by Burden & Faires.

JavaFX Script

Although JavaFX Script is a very interesting language, the biggest problem of working with it today its that is still on development, so there're many sites that contain tutorials and code snippets that references APIs or language constructs that are no longer valid. The James Weaver’s JavaFX Blog
and the JavaFX wiki were very useful resources to find out about the latest updates. Also the Converting JavaFX™ Script Programming Language Code from Interpreted to Compiled Syntax guide provides nice information on language changes.

I think this will be solved as soon a the first official release of the JavaFX SDK is published.

For now, the code snippets shown in this post were created using the build from July 11, 2008.

The program

The final program looks like this:



The applet can also be found here.


Implementing Neville's algorithm

In order to obtain the polynomial for the given selected points using Neville's algorithm we required a polynomial class with a couple of operations for multiplication and addition.


class Polynomial {
attribute coefficients : Number[];

function evaluate(x:Number):Number {
var result = 0.0;
for(i in [0..(sizeof coefficients) - 1]) {
result = result + coefficients[i]*Math.pow(x,i);
}
return result;
}

function multiplyByTerm(coefficient:Number,exponent:Integer):Polynomial {
var origExponent = sizeof coefficients;
if (coefficient == 0.0) {
return Polynomial{coefficients:[]}
} else {
return Polynomial {
coefficients: for (i in [0 .. (origExponent + exponent - 1) ])
if (i < exponent) 0
else coefficients[i - exponent]*coefficient
}
}
}

function multiply(p : Polynomial):Polynomial {
var parts = for (i in [0 .. (sizeof coefficients) - 1])
p.multiplyByTerm(coefficients[i],i);

var result = Polynomial{coefficients:[]};
for (part in parts) {
result = result.add(part);
}
return result;
}

function add(p : Polynomial):Polynomial {
var length1 = sizeof coefficients;
var length2 = sizeof p.coefficients;
var result:Number[];

if (length1 == length2) {
result = for(i in [0 .. length1 - 1])
coefficients[i] + p.coefficients[i];
} else {
if (length1 > length2) {
result = for(i in [0 .. length2 - 1])
coefficients[i] + p.coefficients[i];
for (i in [length2 .. length1 -1]) {
insert coefficients[i] into result
}
} else {
result = for(i in [0 .. length1 - 1])
coefficients[i] + p.coefficients[i];
for (i in [length1 .. length2 -1]) {
insert p.coefficients[i] into result
}
}
}
return Polynomial {
coefficients: result
};
}

function toString():String {
var result:java.lang.StringBuilder = new java.lang.StringBuilder();
var firstTime = true;
result.append("<html>");
for (i in [0 .. (sizeof coefficients) - 1]) {
var theIndex = (sizeof coefficients) - 1 - i;
if (Math.abs(coefficients[theIndex]) > 0.000001) {
if (not firstTime) {
result.append(" + ");
}
if (theIndex != 0) {
result.append("{%3.3f coefficients[theIndex]}x");
if (theIndex != 1) {
result.append("<sup>{theIndex}</sup>");
}
} else {
result.append("{%3.3f coefficients[theIndex]}");
}
firstTime = false;
}
}
result.append("</html>");
return result.toString();
}
}


Some elements of the JavaFX Script language that were really useful include the Sequence Comprehensions. Also the embedded expressions in string are an interesting feature.

An element to convert the coordinates between the screen and the Cartesian plane is also required to implement the algorithm.

The following code shows the implementation of this converter.


class PlaneToScreenConverter {
attribute screenMaxX : Number;
attribute screenMaxY : Number;
attribute screenMinX : Number;
attribute screenMinY : Number;
attribute planeMinX : Number;
attribute planeMinY : Number;
attribute planeMaxX : Number;
attribute planeMaxY : Number;


function convertToScreenX(x:Number):Integer {
var m = ((screenMaxX - screenMinX)/(planeMaxX - planeMinX));
var b = screenMinX - planeMinX*m ;
return (m*x + b).intValue();

}
function convertToScreenY(y:Number):Integer {
var m = ((screenMaxY - screenMinY)/(planeMaxY - planeMinY));
var b = screenMinY - planeMinY*m ;
return (m*y + b).intValue();
}
function convertToPlaneX(x:Integer):Number{
var m = ((planeMaxX - planeMinX)/(screenMaxX - screenMinX));
var b = planeMinX- screenMinX*m ;
return (m*x + b).intValue();

}
function convertToPlaneY(y:Integer):Number {
var m = ((planeMaxY - planeMinY)/(screenMaxY - screenMinY));
var b = planeMinY - screenMinY *m ;
return (m*y + b).intValue();
}
}


Finally we can implement the algorithm as follows:


class MRow {
attribute polynomials : Polynomial[];
}

class NevilleCalculator {
attribute converter : PlaneToScreenConverter;

function createPolynomial(points: FunctionPoint[]):Polynomial {
var numberOfPoints = sizeof points;
var matrix = for(i in [0..numberOfPoints - 1])
MRow {
polynomials:(for (j in [0..i])
Polynomial{coefficients:[]})} ;

for(i in [0..numberOfPoints - 1]) {
matrix[i].polynomials[0] =
Polynomial {
coefficients:[ converter.convertToPlaneY(points[i].y) ]
};
}

var xs = for(i in [0..numberOfPoints - 1]) converter.convertToPlaneX(points[i].x);
var ys = for(i in [0..numberOfPoints - 1]) converter.convertToPlaneY(points[i].y);

for(i in [1..numberOfPoints-1]) {
for(j in [1..i]) {
var q = xs[i]-xs[i-j];
var p1 = Polynomial { coefficients: [-1.0*xs[i-j]/q,1.0/q] };
var p2 = Polynomial { coefficients: [xs[i]/q,-1.0/q] };

matrix[i].polynomials[j] =
p1.multiply(matrix[i].polynomials[j-1]).add(p2.multiply(matrix[i-1].polynomials[j-1]));
}
}
return matrix[numberOfPoints-1].polynomials[numberOfPoints-1];
}
}


The MRow class was created because I was unable to create a sequence of sequences.


Plotting the function

In order to generate screen points for a given polynomial, a FunctionPlotter class was created as follows:


class FunctionPlotter {
attribute converter : PlaneToScreenConverter;
attribute steps = 250;
attribute initialX = -1.0;
attribute finalX = 1.0;

attribute poly = Polynomial {
coefficients:[0,0,1]
}
on replace {
points = getPolyPoints();
}

attribute points = getPolyPoints();

function getPolyPoints():Number[] {
var m = (finalX - initialX)/(250 - 0);
var b = finalX - m*250;
var increment = Math.abs(converter.planeMaxX - converter.planeMinX) / steps;
var currentX = Math.min(converter.planeMaxX , converter.planeMinX);
var i = 0;
var result = for (x in [0..steps*2 - 1]) 1.0;
while (i < steps*2) {
var currentY = poly.evaluate(currentX);
result[i] = converter.convertToScreenX(currentX)*1.0;
result[i+1] = converter.convertToScreenY(currentY)*1.0;

currentX = currentX + increment;
i = i + 2;
}
return result;
}
}


Connecting all the elements


Now that we have all the pieces of the program we can connect them using data binding.

Data binding provides a very nice way for expressing connections between parts of the UI and the model of the application.

For our program we want to allow the user to move around the control points (the blue circles) and have the polynomial recalculated and replotted while moving them. In order to accomplish this we need to create the following databinding connections:



The code that represents the "model" section of the diagram is the following:


var userPoints =
Domain {
points: [
FunctionPoint{
x: 100
y: 300 },
FunctionPoint{
x: 200
y: 400 },
FunctionPoint{
x: 350
y: 300 },
FunctionPoint{
x: 400
y: 200 }

]
}

var converter = PlaneToScreenConverter {
screenMaxX: 480
screenMaxY: 0
screenMinX: 0
screenMinY: 480
planeMinX: -20
planeMinY: -20
planeMaxX: 20
planeMaxY: 20
}

var nevilleCalculator = NevilleCalculator {
converter: converter
}


var plotter = FunctionPlotter {
poly: bind nevilleCalculator.createPolynomial(
for(p in userPoints.points)
FunctionPoint{x:p.x,y:p.y})
converter: converter;
}


Notice that in the bind expression of the poly property of the FunctionPlotter we use a for comprehension instead of passing the complete collection. This is required to allow the update of the polynomial when moving just one point.

The UI part of the program looks like this:


Application {
stage:
Stage {
content:
ComponentView {
component:
BorderPanel {
background: Color.WHITE
top:
Label {
text: bind plotter.poly.toString()
}

center:
Canvas {
content: [
...
]
}
}
}
}
}


Notice that the label is also bound to the polynomial of the function plotter.

The plotted function line and the control points are located inside the canvas with the following code:


Polyline {
stroke:Color.BLACK
points: bind plotter.points
},
Group {
content: bind for (p in userPoints.points)
Group {
content: [
Circle {
centerX: p.x
centerY: p.y
radius:10
fill: Color.BLUE

var dragStartX:Number;
var dragStartY:Number;
onMousePressed:
function(event:MouseEvent) {
dragStartX = p.x;
dragStartY = p.y;
}
onMouseDragged:
function(event:MouseEvent):Void {
p.x = dragStartX + event.getDragX();
p.y = dragStartY + event.getDragY();
}
},
Text { x: p.x+4,y:p.y+10,
content: bind "({%3.2f converter.convertToPlaneX(p.x)},{%3.2f converter.convertToPlaneY(p.y)})" }
]}
}


The mouse pressed and mouse dragged handler are used to allow the user to move the control points.

Also inside the canvas is the code for the axis and the grid.


Group {
content: for(x in [0 .. Math.max(converter.screenMaxX,converter.screenMinX)/24])
Line {
stroke:Color.CYAN
startX: x*24, startY:converter.screenMinY
endX:x*24 , endY:converter.screenMaxY
}
},
Group {
content: for(y in [0 .. Math.max(converter.screenMinY,converter.screenMaxY)/24])
Line {
stroke:Color.CYAN
startX:converter.screenMinX,startY:y*24
endX:converter.screenMaxX, endY:y*24
}
},
Line {
startX: Math.abs((converter.screenMaxX - converter.screenMinX)/2)
startY: converter.screenMinY
endX: Math.abs((converter.screenMaxX - converter.screenMinX)/2)
endY: converter.screenMaxY
stroke:Color.BLACK
strokeWidth:2
},
Line {
startX: converter.screenMinX
startY: Math.abs((converter.screenMaxY - converter.screenMinY)/2)
endX: converter.screenMaxX
endY: Math.abs((converter.screenMaxY - converter.screenMinY)/2)
stroke:Color.BLACK
strokeWidth:2
},




Final words

JavaFX Script provides a nice programming language and powerful graphics and UI elements. One of the most interesting features is data binding. It will be very interesting to see how this feature is implemented in the other platforms.

The biggest problem right now is that JavaFX Script is on development so it's difficult to get documentation of the last changes. Also another problem is that right now in order to create an applet all the Jars of the distribution must be included adding a couple of MB to the size of final download.


Code for this post can be found here.

The applet can also be found here.

Thursday, May 1, 2008

Mutiple representations of an object with Tom mappings

This post shows an example of how Tom object mappings could be used to provide multiple pattern matching representations of objects of the same class.

Introduction

As shown in previous posts, I really like F# Active Patterns and Scala Extractors. Among other things these features allows to create multiple pattern matching representations of objects . One of the ideas behind these concepts is "Views" presented by Philip Wadler in the Views: A way for pattern matching to cohabit with data abstraction paper.

It is possible to use Tom object mappings(explained here) to get a similar effect.

Example

For this example, an alternative representation for a Complex number will be created. A complex number could be represented by Cartesian coordinates (real and imaginary parts) and by Polar coordinates (angle and modulus).

This example is used to present Views, Extractors and Active Patterns.

The Apache Commons Complex class will be used as the complex number implementation.

First, a mapping for the Complex sort needs to be created.


%include { double.tom }

%typeterm Complex {
implement { org.apache.commons.math.complex.Complex }
is_sort(t) { t instanceof org.apache.commons.math.complex.Complex }
equals(t1,t2) { t1.equals(t2) }
}



Then, a mapping for the Complex number with Cartesian coordinates is created. Since the Complex class is in Cartesian coordinates only the getReal and getImaginary accessors are required.


%op Complex Complex(real:double,img :double ) {
is_fsym(t) { t instanceof org.apache.commons.math.complex.Complex }
get_slot(real, t) { t.getReal() }
get_slot(img, t) { t.getImaginary() }
make(real,img) { new org.apache.commons.math.complex.Complex(real,img) }
}


Finally a mapping for the Polar representation. Since the Complex class stores the number in Cartesian coordinates a conversion must be applied to get the angle and modulus slots. Also the polar2Complex method is used to create a Complex instance using the Polar symbol.


%op Complex Polar(m:double,a :double ) {
is_fsym(t) { t instanceof org.apache.commons.math.complex.Complex }

get_slot(a, t) { Math.atan2(t.getImaginary(), t.getReal()) }

get_slot(m, t) {
Math.sqrt(t.getReal() * t.getReal() +
t.getImaginary() * t.getImaginary()) }

make(radial,modulus) {
org.apache.commons.math.complex.ComplexUtils.polar2Complex(
radial,
modulus) }
}



A use of these mappings is the following:


Complex c = new Complex(3,3);

%match(c) {
Polar(m,a) -> {
System.out.println(
String.format("%f,%f",`m,`a ));
}
}


Also given that a make declaration was added to the mappings we can use the object creation syntax as follows:


Complex c2 = `Polar(3,Math.PI/2.0);

%match ( c2){
Complex(r,i) -> {
System.out.println(
String.format("%f,%f",`r,`i));
}
}

Wednesday, April 9, 2008

Pattern matching on Java objects with Tom

This post presents a quick overview of the mechanism that Tom provides to enable pattern matching on plain Java objects.

Mappings

Tom performs pattern matching on special data structures defined using Gom. However there's a mechanism that allows the mapping parts of an object to data structure that could be used to perform pattern matching.

In section 8.1 Hand-written mappings, a nice explanation of this mechanism . Also there's a very interesting video available from Tom's site where Tom is used to manipulate Java Persistence API objects.

Mappings for java.io.File

For this example we will create mappings for the java.io.File class . The first step is to create the sort definition for the File class.


%typeterm FileSystemElement {
implement { java.io.File }
is_sort(t) { t instanceof java.io.File }
equals(t1,t2) { t1.equals(t2) }
}


Inside of Tom constructs the sort that represents files will be called FileSystemElement. Basic operations must be provided in order to specify: the class that is being mapped (implement), a predicate to determine if is a valid element (is_sort) and an equals criteria (equals).

Now we need to create a operator or constructor that represents files. Here's the definition for that element.


%op FileSystemElement File(name:String, parent:FileSystemElement) {
is_fsym(t) { (t instanceof java.io.File) &&
((java.io.File)t).isFile() }
get_slot(name, t) { t.getName() }
get_slot(parent, t) { t.getParentFile() }
make(name,parent) { new java.io.File(parent,name) }
}


This %op definition says that we're defining a File which belongs to the FileSystemElement sort. In particular we're going to use this definition to represent java.io.File instances that refer to a file, the is_fsym definition verifies this. Now we define two slots one for the name of the file and another to the java.io.File definition of the parent. Finally a make allows us to use the backquote(`) syntax to create instances of File.

A use of this definition is the following:


File f = new File("/tmp/test.txt");

%match(f) {
File(name,parent) -> {
System.out.println("File name "+`name);
System.out.println("Parent "+`parent+" "+`parent.getClass());
}
}


By running this program we get:


File name test.txt
Parent /tmp class java.io.File


Notice that by calling getClass on parent we get java.io.File.

Mapping for directories

Using handwritten mappings allows you to expose only the parts of an object that are interesting for a certain problem. This powerful notion is present in other languages like Scala with the use of Extractors or F# with Active Patterns and originally from Views in Haskell.

For example now we're going to create a definition that represents directories which is another mapping from java.io.File.


%op FileSystemElement Directory(name:String,
parent:FileSystemElement,
children:Children )
{
is_fsym(t) { (t instanceof java.io.File) &&
((java.io.File)t).isDirectory() }
get_slot(name, t) { t.getName() }
get_slot(parent, t) { t.getParentFile() }
get_slot(children, t) { createFromArray(t.listFiles()) }
make(name,parent, children) { new java.io.File(parent,name) }
}


Notice that the is_fsym definition checks identifies a java.io.File instance that refers to a directory. Also notices that for this definition we're exposing the child files and directories.

In order to expose a sequence of elements we need to create a separate mapping. For example the above example mentions the Children sort which is defined as:


%typeterm Children {
implement { java.util.ArrayList<java.io.File> }
is_sort(t) { t instanceof java.util.ArrayList }
equals(t1,t2) { t1.equals(t2) }
}

%oparray Children Children(FileSystemElement*) {
is_fsym(t) { t instanceof ArrayList }
get_element(l,n) { l.get(n) }
get_size(l) { l.size() }
make_empty(n) { new ArrayList<java.io.File>(n) }
make_append(e,l) { addToFileArrayList(e,l) }
}


Notice that the %oparray definition contains special mapping for array-like collections. In section 8.1.4 Using list-matching there's more information about this element and about the %oplist element which allows the mapping of list-like collections.

The addToFileArrayList is a static method that creates an ArrayList from the result of calling java.io.File.listFiles().

Example: listing a directory

With the definitions available above we can write a small program that lists a directory:


File homeDirectory = new File("/home/ldfallas");

%match(homeDirectory) {
Directory(_,_,Children(_*,f,_*)) -> {
%match(f) {
File(name,_) -> { System.out.println("File: "+`name); }
Directory(name,_,_) -> { System.out.println("Directory: "+`name); }
}
}
}


As explained in a previous post, since Children(_*,f,_*) has no restriction on f then the body of the case will be executed for all possible child file of the specified directory.


Example: Files with same name


The following example tries to find two files stored in two separate directories in the same level.


...
%match(homeDirectory) {
Directory(_,_,Children(_*,Directory(dir1,_,Children(_*,File(name,_),_*)),
_*,Directory(dir2,_,Children(_*,File(name,_),_*)),
_*)) -> {

System.out.println("File name "+`name);
System.out.println(`dir1);
System.out.println(`dir2);
}
}


Notice that this little example will show all the pairs of files with the same name stored in two different directories at the same level.

Friday, April 4, 2008

Data structure traversal with Tom

Strategies provide a nice mecanism for operations that require data structure traversal. This post presents a brief overview of the strategies implementation in Tom.

Strategies

Tom incorporates the concept of strategy which provides a nice way to perform operations that traverse heterogeneous data structures. These operations could be complete/partial tree transformations or queries.

The paper The Essence of Strategic Programming by Ralf Lämmel, Eelco Visser and Joost Visser gives a very nice implementation-independent definition for the concept. From this paper:


The key idea underlying strategic programming is the separation of problem-specific ingredients of traversal functionality (i.e., basic actions) and reusable traversal schemes (i.e., traversal control).


This paragraph mentions two very interesting characteristics of strategic programming: the separation of problem-specific code from traversal code and the use of reusable traversal schemes.

Example

The following example , taken from the Wikipedia entry for the Visitor pattern, shows how strategies are used to print the parts of a data structure.

Given the following definitions:


module Cars
imports String
abstract syntax

Wheel = Wheel(name:String)

Engine = Engine()

Body = Body()

Wheels = Wheels(Wheel*)

Vehicle = Car(engine:Engine,body:Body,wheels:Wheels)


We can write the following strategy to print all the parts of a Car:


%strategy PrintStrategy() extends Identity(){
visit Wheel {
Wheel(name) -> { System.out.println("Visiting " + `name+ " wheel"); }
}

visit Engine {
Engine() -> {System.out.println("Visiting engine");}
}

visit Body {
Body() -> {System.out.println("Visiting body");}
}

visit Vehicle {
Car(_,_,_) -> { System.out.println("Visiting Car"); }
}
}


We can apply this strategy the following way:


public static void main(String[] a) throws Exception {
Vehicle v =
`Car(Engine(),
Body(),
Wheels(Wheel("front left"),
Wheel("front right"),
Wheel("back left"),
Wheel("back right")));
`TopDown(PrintStrategy()).visit(v);
}


Running this program shows:


Visiting Car
Visiting engine
Visiting body
Visiting front left wheel
Visiting front right wheel
Visiting back left wheel
Visiting back right wheel


As shown in this example, the problem-specific code is located in the definition of PrintStrategy and the traversal code is reused from the existing TopDown strategy.

The ability of switching traversal schemes is very powerful, for example say that we want to print the parts of the data structure starting with the leafs. We can reuse the existing BottomUp strategy the following way:


...
`BottomUp(PrintStrategy()).visit(v);


This program shows:


Visiting engine
Visiting body
Visiting front left wheel
Visiting front right wheel
Visiting back left wheel
Visiting back right wheel
Visiting Car


Just scratch the surface

A very detailed explanation of this feature is provided in the Introduction to strategies and Strategies in practice sections of the Tom manual.

Also there're several incarnations of this concept in other languages and platforms. For more information check the The Essence of Strategic Programming paper.

Wednesday, March 26, 2008

Pattern matching with Tom

In this post I'm going to show a small overview to the Tom pattern matching compiler for Java.

Tom

Tom is an extension to the Java language which adds a constructs for describing data structures and powerful pattern matching features for manipulating those data structures.

Tom distribution includes a command line compiler and a Eclipse plugin. Also nice documentation is found and examples are found in its website.

The documentation available from the website includes a nice step by step introduction to the features available in the product. Here I'm going to show a little overview of some of them.

All the snippets for this post were created using the Eclipse plugin.

Data structure definition

Tom provides a way for data structures that could be easily instantiated and manipulated with pattern matching. These data types are also called algebraic data types which are very similar to those available in languages such as Haskell.

These data types could be defined inside a Java class by using the %gom { } block or defining the types in a file with .gom extension. Instructions on how to do this are available in the Separating Gom from Tom section of the documentation.

For the rest of this post we're going to use the following definitions to show examples with Tom.


module Company
imports int String
abstract syntax

Person = Person(companyId:int,name:String,age:int)

Persons = Persons(Person*)

Worker = Employee(personId:int)
| Contractor(name:String)

Workers = Workers(Worker*)

Group = DepartmentGroup(department:Department)
| Committee(name:String, members:Workers)

Department = SimpleDepartment(name:String, leader:Worker, members:Workers)
| MultiDepartment(name:String, leader:Worker, subDepartments:Departments)

Departments = Departments(Department*)

Groups = Groups(Group*)

Company = Company(name:String,members:Persons,groups:Groups)


Reading for the bottom to the top, these definitions describe a Company data structure which has name, a collection of persons and a collection of groups inside the company. Groups could be Departments or a Committees. Departments could be simple (SimpleDepartment) or have sub departments(MultipleDepartment). Also the members of the Committees or Departments could be employees or contractors.

In order to use these definitions we need to create a file with .t extension. This file will have both Java and Tom elements mixed together. For example here's the creation of an instance of the data structures defined above in Main.t :

   
import langexplr.tomtests.company.types.*;

public class Main{
%include{ int.tom }
%include{ company/Company.tom }

static Company createCompanyData() {
return `Company("MyCompany",
Persons(Person(1,"John",43),
Person(2,"Kim",33),
Person(3,"Maria",27),
Person(4,"Luis",34),
Person(5,"Mary",34),
Person(6,"Bill",24)),
Groups(
DepartmentGroup(
SimpleDepartment(
"HR",
Employee(2),
Workers(Employee(1),
Employee(6),
Contractor("Lisa")))),
DepartmentGroup(
SimpleDepartment(
"Finance",
Employee(5),
Workers(Contractor("William")))),
DepartmentGroup(
MultiDepartment(
"Systems",
Employee(5),
Departments(
SimpleDepartment(
"Development",
Employee(3),
Workers(Contractor("Charlie"))),
SimpleDepartment(
"QA",
Employee(4),
Workers(Contractor("Lily")))))),
Committee("Party",Workers(Employee(2),Employee(5)))
));
}
...


Notice the backquote character used at the beginning of the call to the Company constructor. This element is used to differentiate the Java and Tom syntax elements.

Matching

Tom provides a powerful pattern matching mechanism that eases the manipulation of complex tree structures. In order to use this feature, a %match statement is provided. This statement is barely similar to a switch statement in Java or C# but using patterns instead of literals. A simple example of this feature is the following:


static void nameTest(Company c) {
String name = "";
%match (c){
Company(theName,_,_) -> { name = `theName; }
}
System.out.println(name);
}


In this example the name of the company is extracted and assigned to the name variable. The %match statement receives an element, in this case the instance of the Company datatype. This element is tested against one or more patterns, in this case only one pattern is provided. If the pattern matches, then the code on the left of the arrow ( -> ) is executed.

The pattern Company(theName,_,_) says, that we're expecting an instance of the Company datatype and that the name( the first argument of the constructor) will be assigned to the theName variable. It also says that we will ignore the other two elements of the Company datatype. The variable theName could be used at the left side of this entry by using a backquote character at the beginning of the name.

List matching

One of the most interesting pattern matching elements provided by Tom is list matching which allows the creation of patterns on sequences of elements.

For example, say that we want to create a function that retrieves the name of an Person given its id and an instance of the Company. As a first version of this function, we can write:


static String getPersonNameByIdV1(int id,Company c) {
String name = null;
%match (c){
Company(_,Persons(_*,Person(empId,empName,_),_*),_) -> {
if (id == `empId) {
name = `empName;
}
}
}
return name;
}


It is important to remember that in the definitions of the data structures, the Persons element is defined as Persons = Persons(Person*) which means that its constructor receives a any number of Person instances.

Now the Company(_,Persons(_*,Person(empId,empName,_),_*),_) pattern says: match a person inside a company and assign empId and empName to its id and name .

Given that "_*" is a wildcard, notice that there are many ways to match this pattern. As explained in the List matching section of the documentation, since there's several ways to match this pattern, the block will be executed with every possible match. This means that empId and empName will be bound to the id and the name of every person. Given this we can ask if (id == `empId) { ... } and assign the name that we found.

Non-linear patterns

Another powerful pattern matching element that Tom provides is the ability to use one variable several times in the same pattern.The first use will bind the variable to a value, the other uses will compare the current element with the bound value. This feature, called Non-linear patterns, introduced here. It allows the creation of more expressive patterns, for example we can rewrite the previous method the following way:


static String getPersonNameByIdV2(int id,Company c) {
String name = null;
%match (int id,c){
empId,Company(_,Persons(_*,Person(empId,empName,_),_*),_) -> {
name = `empName;
}
}
return name;
}


Here we specify two arguments to the %match construct. The first is the requested id and the second is the Company instance. Notice that in the pattern we match the id with the empId free variable the first time, and then we use it to match the requested person. Now we're putting a restriction on the Person we're looking for, so we can remove the if statement from the body.


A final example

For the final example I'll write a function that prints the names of all the members of a given department . Here's the code:


static void printNameOfPeopleWorkingInDepartment(String departmentName,Company c) {
System.out.println("People working in "+departmentName);
%match(String departmentName,c) {
deptName,
Company(_,
persons,
Groups(_*,
DepartmentGroup(
SimpleDepartment(
deptName,
_,
Workers(_*,worker,_*))),
_*)) -> {
%match(worker) {
Employee(id) -> { System.out.println(getEmployeeNameById(`id,c));}
Contractor(name) -> { System.out.println(`name);}
}
}
}
}


This pattern will first look for a SimpleDepartment with the specified name. Then for each worker it will extract the name given if it is an Employee or a Contractor.

MultiDepartment instances are not considered. In future posts another Tom feature will be used to deal with these elements.

Code for this post can be found here.

Tom provides lots of features not covered here. Its distribution includes documentation and a lot of examples.

Thursday, December 20, 2007

Combining iterators in Java

In this post I'm going to show a little experiment for combining iterators in Java.

A couple of week a ago I read an excellent blog entry by Debasish Ghosh called
Infinite Streams using Java Closures. In it an implementation of the Infinite Stream concept is presented with the help of Java closures.

For this post I wanted to show something related to this but using the Iterable/Iterator interfaces instead of a custom stream object. What interest me the most is the operations applied to stream objects such as map or filter but on iterators. These and other operations are defined for the IEnumerable/IEnumerator interfaces in C# with the extension methods defined in System.Linq.Enumerable.

Also, given the amount of discussion lately around Java closures I wanted to create this code using the Java closures prototype of the BGGA closures proposal to learn about it.

What I want to have is the following operations on iterators:


import java.util.*;

public class IteratorUtils {
public static <X,V> Iterable<V> map({X=>V} f,Iterable<X> i) {
return new EachElementIterable<X,V>(i,f);
}
public static <X> Iterable<X> take(int count,Iterable<X> i) {
return new TakeIterable<X>(i,count);
}
public static <X> Iterable<X> filter({X=>boolean} pred,Iterable<X> i) {
return new FilterIterable<X>(i,pred);
}
public static <X> Iterable<X> flatten(Iterable<Iterable<X>> multiIterator) {
return new FlattenIterable<X>(multiIterator);
}
}


The map operation takes a function and a iterator and generate another iterator with the function applied to each element. The take operation generates an iterator for a number of elements on another iterator. The filter operation takes a predicate and a iterator and returns another iterator with only the elements that applied to the predicate. The flatten operation takes an iterator of iterators and returns a flattened sequence of values.

Heres the iterator for the map operation:


import java.util.*;
public class EachElementIterable<T,J> implements Iterable<J>{
private Iterable<T> iterable;
private {T=>J} function;
public EachElementIterable(Iterable<T> iterable,{T=>J} function) {
this.iterable = iterable;
this.function = function;
}
public Iterator<J> iterator() {
return new EachElementIterator<T,J>(iterable.iterator(),function);
}

static class EachElementIterator<T,J> implements Iterator<J>{
private Iterator<T> iterator;
private {T=>J} function;
public EachElementIterator(Iterator<T> iterator,{T=>J} function) {
this.function = function;
this.iterator = iterator;
}
public J next() {
return function.invoke(iterator.next());
}
public boolean hasNext() {
return iterator.hasNext();
}
public void remove() {
}
}
}


The implementation is not as elegant as the one presented in the Infinite Stream entry, but it can be used with anything implementing Iterable.

Heres the iterator for the take operation:


import java.util.*;

public class TakeIterable<T> implements Iterable<T> {
private int count;
private Iterable<T> iterable;
public TakeIterable(Iterable<T> iterable,int count) {
this.count = count;
this.iterable = iterable;
}
public Iterator<T> iterator() {
return new TakeIterator<T>(iterable.iterator(),count);
}

static class TakeIterator<T> implements Iterator<T> {
private Iterator<T> iterator;
private int count;
private int current;
public TakeIterator(Iterator<T> iterator,int count) {
this.count = count;
this.iterator = iterator;
this.current = 0;
}
public T next() {
if (current++ < count) {
return iterator.next();
} else{
return null;
}
}
public boolean hasNext() {
return iterator.hasNext() && current < count;
}
public void remove() {
}
}

}


Here's the implementation of the filter iterator:


import java.util.*;

public class FilterIterable<T> implements Iterable<T> {
private Iterable<T> iterable;
private {T=>boolean} predicate;
public FilterIterable(Iterable<T> iterable,{T=>boolean} predicate) {
this.iterable = iterable;
this.predicate = predicate;
}
public Iterator<T> iterator() {
return new FilterIterator<T>(iterable.iterator(),predicate);
}

static class FilterIterator<T> implements Iterator<T> {
private Iterator<T> iterator;
private {T=>boolean} predicate;
private T currentValue;
boolean finished = false;
boolean nextConsumed = true;

public FilterIterator(Iterator<T> iterator,{T=>boolean} predicate) {
this.predicate = predicate;
this.iterator = iterator;
}

public boolean moveToNextValid() {
boolean found = false;
while(!found && iterator.hasNext()) {
T currentValue = iterator.next();
if(predicate.invoke(currentValue)) {
found = true;
this.currentValue = currentValue;
nextConsumed = false;
}
}
if(!found) {
finished = true;
}
return found;
}

public T next() {
if (!nextConsumed) {
nextConsumed = true;
return currentValue;
} else {
if (!finished) {
if(moveToNextValid()) {
nextConsumed = true;
return currentValue;
}
}
}
return null;
}
public boolean hasNext() {
return !finished &&
(!nextConsumed || moveToNextValid());
}
public void remove() {
}
}
}


And finally, here's the flatten iterator:


public class FlattenIterable<T> implements Iterable<T> {
private Iterable<Iterable<T>> iterable;
public FlattenIterable(Iterable<Iterable<T>> iterable) {
this.iterable = iterable;
}
public Iterator<T> iterator() {
return new FlattenIterator<T>(iterable.iterator());
}
static class FlattenIterator<T> implements Iterator<T> {
private Iterator<Iterable<T>> iterator;
private Iterator<T> currentIterator;
public FlattenIterator(Iterator<Iterable<T>> iterator) {
this.iterator = iterator;
currentIterator = null;
}
public boolean hasNext() {
boolean hasNext = true;
if (currentIterator == null) {
if (iterator.hasNext()) {
currentIterator = iterator.next().iterator();
} else {
return false;
}
}

while(!currentIterator.hasNext() &&
iterator.hasNext()) {
currentIterator = iterator.next().iterator();
}

return currentIterator.hasNext();
}

public T next() {
return currentIterator.next();
}

public void remove() {
}
}
}


We can combine these wrapper iterators to create operators on iterators of any kind for example:


ArrayList<String> anArray = new ArrayList<String>();
anArray.add("foo");
anArray.add("goo");
anArray.add("zoo");
...

for(String s : map({String s => "<li>"+s+"</li>"},
filter({String s => !s.startsWith("g")},
anArray))) {
System.out.println(s);
}


This example prints the "foo" and "zoo" between <li> and </li> tags. Also here I'm using Java static import to avoid writing IteratorUtils in every operation call.

Returning to the infinite stream operations, for me the most interesting thing about these wrapper iterators is that an iterator with a large amout of elements could be manipulated without consuming all of its elements in each step. For example take the following iterator:


public class NumericSequence implements Iterable<Integer>,Iterator<Integer>{
private int value = 0;
public NumericSequence() {
}
public NumericSequence(int start) {
value = start;
}
public Iterator<Integer> iterator() {
return this;
}
public Integer next() {
return value++;
}
public boolean hasNext() {
return true;
}
public void remove() {
}
}


We can manipulate this iterator using the operations and wrappers defined above:


for(int i : take(5,
filter(
{Integer x => x % 2 != 0 },
map( {Integer x=>x*x},
new NumericSequence())))) {
System.out.println(i);
}


This program prints only 1,9,25,49 and 81.

For the final example I wanted to create a little snippet that prints a list of friendly pairs of numbers. A Friendly Pair is a pair of numbers that share the common characteristic of having the same value as a result of the sum of all of its divisors divided by itself. Another nice definition of a Friendly number is presented here.

First we define some utilities:


public class IntegerIteratorUtils {
public static int sum(Iterable<Integer> integerIterable) {
int result = 0;
for(Integer i : integerIterable) {
result += i.intValue();
}
return result;
}
public static Iterable<Integer> divisors(int number) {
return
IteratorUtils.filter(
{Integer x => x != 0 && number % x == 0 },
IteratorUtils.take(number+1,new NumericSequence()));
}

public static int divisorFunction(int number) {
return sum(divisors(number));
}
}



Having these functions we can now calculate the pairs:


int max = 1000;
for(Pair<Integer,Integer> p :
filter( {Pair<Integer,Integer> p =>
divisorFunction(p.first)/(double)p.first ==
divisorFunction(p.second)/(double)p.second },
flatten(
map(
{Integer x =>
map({Integer ix => new Pair<Integer,Integer>(x,ix)},
take(max,new NumericSequence(x+1)))},
take(max,
new NumericSequence(1)))))) {

System.out.println("("+p.first.toString()+", "+p.second.toString()+")");
}


This program prints:


(6, 28)
(6, 496)
(12, 234)
(28, 496)
(30, 140)
(40, 224)
(66, 308)
(78, 364)
(80, 200)
(84, 270)
....


Code for this example was created with the closures prototype from 2007-11-30. Source can be found here.

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:

Wednesday, May 30, 2007

Using Scala Extractors with the XSD Schema Infoset Model

In this post I'm going to use Scala extractor objects with the Eclipse XML Schema Infoset Model to identify common ways of defining XML Schemas.

Hopefully I'm going to show that complex patterns on common Java objects can be identified using Scala extractors.

The Eclipse Schema Infoset Model is a complex EMF model the represents the W3C XML Schema. The Analyzing XML schemas with the Schema Infoset Model and Analyze Schemas with the XML Schema Infoset Model articles provide a nice explanation on how to work with this model.

For this post I wanted to create Scala patterns that identify common design patterns in Xml Schemas. There are four common patterns for XML Schemas: Russian Doll, Salami Slice, Venetian Blind and Garden of Eden.

The article Introducing Design Patterns in XML Schemas provide a nice explanation on each of this patterns. Also the article talks about a nice feature of NetBeans Enterprise Pack that allows the user to move a schema from one design pattern to another. More information on these design patterns can be found on the article Global vs Local from the xFront site.

The W3C XML Schema model is huge, but for this post I'm going to consider only a small subset.

The first step is the definition of the extractor objects that will be used to have access to certain properties of the Xml Schema Infoset model.


package langexplr.scalaextractorexperiments;

import org.eclipse.emf.ecore.resource._
import org.eclipse.emf.ecore.resource.impl._
import org.eclipse.xsd._
import org.eclipse.xsd.impl._
import org.eclipse.xsd.util._
import org.eclipse.emf.common.util.URI

object XSDSchemaParts {
def unapply(schema : XSDSchema) =
Some ((schema.getTargetNamespace(),
List.fromIterator(
new JavaIteratorWrapper[XSDTypeDefinition](
schema.getTypeDefinitions().iterator())),
List.fromIterator(
new JavaIteratorWrapper[XSDElementDeclaration](
schema.getElementDeclarations().iterator()))))

}

object XSDElementParts {
def unapply(elementDeclaration : XSDElementDeclaration) =
Some((elementDeclaration.getName(),elementDeclaration.getTypeDefinition()))


}

object XSDComplexType {
def unapply(typeDefinition : XSDTypeDefinition) =
if (typeDefinition.isInstanceOf[XSDComplexTypeDefinition]) {
val complexType = typeDefinition.asInstanceOf[XSDComplexTypeDefinition];
Some((complexType.getName(),complexType.getContent()))
} else {
None
}

}

object XSDSimpleType {
def unapply(typeDefinition : XSDTypeDefinition) = {
if (typeDefinition.isInstanceOf[XSDSimpleTypeDefinition]) {
Some(typeDefinition.asInstanceOf[XSDSimpleTypeDefinition])
} else {
None
}
}
}

object XSDParticleContent {
def unapply(p : XSDParticle) = Some(p.getContent())
}

object XSDSimpleSequenceModelGroup {
def unapply(complexTypeContent : XSDComplexTypeContent) = {
complexTypeContent match {
case XSDParticleContent(mg : XSDModelGroup)
if (mg.getCompositor().getName == "sequence") =>
Some(
List.fromIterator(
new JavaIteratorWrapper[XSDParticle](
mg.getContents.iterator())))
case _ => None
}
}



The XSDSchemaParts, XSDElementParts, XSDComplexType, XSDSimpleType, and XSDParticleContent extractor objects provide access to some properties of a model object. For example the XSDSchemaParts returns a tuple with the target namespace, the complex type definitions and the element definitions.

Also the XSDSimpleSequenceModelGroup provide an easy way to identify a common pattern that is the use of a XSD sequence as the type main element.

A class will be created for each design pattern. The following trait is the base for all of them:


trait XsdDesignPattern {
def name : String
def identify(schema:XSDSchema) : boolean
}



Now we can define each pattern:

Russian Doll

This design pattern says that the structure of the XML Schema is similar to the document structure. Only one public element is defined and all other elements are defined inside of it.

For example:


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://langexplr.blogspot.com/DocsRussianDoll"
xmlns:p="http://langexplr.blogspot.com/DocsRussianDoll"
xmlns="http://langexplr.blogspot.com/DocsRussianDoll"
elementFormDefault="qualified">
<xs:element name="page">
<xs:complexType>
<xs:sequence>
<xs:element name="header">
<xs:complexType>
<xs:sequence>
<xs:element name="content" type="xs:string" />
</xs:sequence>
<xs:attribute name="margin"
type="xs:integer" />
</xs:complexType>

</xs:element>
<xs:element name="body">
<xs:complexType>
<xs:sequence>
<xs:element name="paragraph"
type="xs:string" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="footer">
<xs:complexType>
<xs:sequence>
<xs:element name="content" type="xs:string" />
</xs:sequence>
<xs:attribute name="margin"
type="xs:integer" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>


The Scala code to identify this design pattern looks like this:


class RussianDoll extends XsdDesignPattern {
def name = "Russian Doll"
def identify(schema : XSDSchema) =
schema match {
case XSDSchemaParts(
namespace,
List(),
List(XSDElementParts(
name,
XSDComplexType(
null,
XSDSimpleSequenceModelGroup(elements))))) => {
true
}
case _ => false
}
}




Salami Slice

This design pattern says that all elements must be declared at the top level with the type declaration inside of them.

For example:


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://langexplr.blogspot.com/DocsSalamiSlice"
xmlns:tns="http://langexplr.blogspot.com/DocsSalamiSlice"
xmlns="http://langexplr.blogspot.com/DocsSalamiSlice"
elementFormDefault="qualified">

<xs:element name="content" type="xs:string" />
<xs:element name="paragraph" type="xs:string" />

<xs:element name="header">
<xs:complexType>
<xs:sequence>
<xs:element ref="tns:content" />
</xs:sequence>
<xs:attribute name="margin" type="xs:integer" />
</xs:complexType>
</xs:element>

<xs:element name="footer">
<xs:complexType>
<xs:sequence>
<xs:element ref="tns:content" />
</xs:sequence>
<xs:attribute name="margin" type="xs:integer" />
</xs:complexType>
</xs:element>

<xs:element name="body">
<xs:complexType>
<xs:sequence>
<xs:element ref="tns:paragraph" minOccurs="0"
maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="page">
<xs:complexType>
<xs:sequence>
<xs:element ref="tns:header" />
<xs:element ref="tns:body" />
<xs:element ref="tns:footer" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>



The Scala code to identify this design pattern looks like this:


class SalamiSlice extends XsdDesignPattern {
def name = "Salami Slice"
def identify(schema : XSDSchema) =
schema match {
case XSDSchemaParts(
namespace,
List(),
elements) => {
elementsWithReferences(elements)
}
case _ => false
}
// Utility methods

def forAllInnerElements(l : List[XSDElementDeclaration],
pred : XSDElementDeclaration => boolean) =
l.forall{
case XSDElementParts(
_,
XSDComplexType(null,XSDSimpleSequenceModelGroup(particles))) =>
particles.forall({
case XSDParticleContent(e:XSDElementDeclaration) => pred(e)
case _ => false })
case XSDElementParts(_,XSDComplexType(null,null)) => true
case XSDElementParts(_,XSDSimpleType(_)) => true
case _ => false
}

def elementsWithReferences(x : List[XSDElementDeclaration]) =
forAllInnerElements(
x,
(e:XSDElementDeclaration) => e.isElementDeclarationReference)

}




Venetian Blind

This design pattern says that there one global element and all other elements use types declared at the top level.

For example:


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://langexplr.blogspot.com/DocsVenetianBlind"
xmlns:tns="http://langexplr.blogspot.com/DocsVenetianBlind"
xmlns="http://langexplr.blogspot.com/DocsVenetianBlind"
elementFormDefault="qualified">

<xs:complexType name="sectionType">
<xs:sequence>
<xs:element name="content" type="xs:string" />
</xs:sequence>
<xs:attribute name="margin" type="xs:integer" />
</xs:complexType>

<xs:complexType name="bodyType">
<xs:sequence>
<xs:element name="paragraph" type="xs:string" minOccurs="0"
maxOccurs="unbounded" />
</xs:sequence>

</xs:complexType>

<xs:element name="page">
<xs:complexType>
<xs:sequence>
<xs:element name="header" type="tns:sectionType" />
<xs:element name="body" type="tns:bodyType" />
<xs:element name="footer" type="tns:sectionType" />
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>




The Scala code for this pattern looks like this:


class VenetianBlind extends XsdDesignPattern {
def name = "Venetian Blind"
def identify(schema : XSDSchema) =
schema match {
case XSDSchemaParts(
namespace,
types,
List(XSDElementParts(
_,
XSDComplexType(
_,
XSDSimpleSequenceModelGroup(elements))))) =>
elements.forall((e:XSDParticle) =>
elementWithTypeReferences(e,types))
case _ => false
}
def elementWithTypeReferences(e : XSDParticle, types : List[XSDTypeDefinition]) =
e match {
case XSDParticleContent(e:XSDElementDeclaration) =>
e.getTypeDefinition.getContainer.isInstanceOf[XSDSchema] &&
!(types.find ((t:XSDTypeDefinition) => t == e.getTypeDefinition)).isEmpty
case _ => false
}

}



Garden of Eden

This design pattern says that all the elements and types must be declared global.


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://langexplr.blogspot.com/DocsGardenOfEden"
xmlns:tns="http://langexplr.blogspot.com/DocsGardenOfEden"
xmlns="http://langexplr.blogspot.com/DocsGardenOfEden"
elementFormDefault="qualified">

<xs:complexType name="sectionType">
<xs:sequence>
<xs:element ref="tns:content" />
</xs:sequence>
<xs:attribute name="margin" type="xs:integer" />
</xs:complexType>

<xs:complexType name="bodyType">
<xs:sequence>
<xs:element ref="tns:paragraph" minOccurs="0"
maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>

<xs:element name="content" type="xs:string" />

<xs:element name="paragraph" type="xs:string"/>

<xs:element name="header" type="tns:sectionType" />

<xs:element name="body" type="tns:bodyType" />

<xs:element name="footer" type="tns:sectionType" />

<xs:complexType name="pageType">
<xs:sequence>
<xs:element ref="tns:header" />
<xs:element ref="tns:body" />
<xs:element ref="tns:footer" />
</xs:sequence>
</xs:complexType>

<xs:element name="page" type="tns:pageType" />
</xs:schema>



The Scala code for this pattern looks like this:


class GardenOfEden extends XsdDesignPattern {
def name = "Garden Of Eden"
def identify(schema : XSDSchema) =
schema match {
case XSDSchemaParts(
namespace,
types,
elements) =>
elements.forall((e : XSDElementDeclaration) =>
elementWithTypeReferences(e,types))
case _ => false
}

def elementWithTypeReferences(e : XSDElementDeclaration, types : List[XSDTypeDefinition]) =
e.getTypeDefinition.getContainer.isInstanceOf[XSDSchema] &&
((types.find ((t:XSDTypeDefinition) => t == e.getTypeDefinition)) match {
case Some(XSDComplexType(_,XSDSimpleSequenceModelGroup(particles))) =>
particles.forall({
case XSDParticleContent(e:XSDElementDeclaration) =>
e.isElementDeclarationReference
case _ => false })
case Some(XSDComplexType(_,null)) => true
case Some(XSDSimpleType(_)) => true
case None =>
e.getTypeDefinition.getTargetNamespace == "http://www.w3.org/2001/XMLSchema"
case _ => false
})

}





Finally we need a class to test all the patterns:


object XsdDesignPatterns {
def patterns:List[XsdDesignPattern] = List(new RussianDoll,
new SalamiSlice,
new VenetianBlind,
new GardenOfEden)
def identify(schema : XSDSchema) =
patterns.filter((p:XsdDesignPattern) => p identify schema).map((p:XsdDesignPattern) => p.name)
}




The code for this experiment can be found here.