Monday, October 23, 2006

DSL for file processing - GetInLine

I've been playing with an embedded Domain-specific language for file processing. It grew out of a requirement from my current project, but I've already found a use for it in a couple of personal tasks.

Tha language is growing and changing fast, but here's a code snippet that may give you a feel for what it can do already:



public void testIncludingFiltersOutRecordsThatDoNotMatchACondition() throws Exception {
new Source().
fromFile("docs/sample-data/flights3.txt").
upToTheEnd().
counting(allRecords).
withoutBlankLines().
counting(nonBlankRecords).
allowing(Processing.rule().
accepting(1).
including(terminalRecordPattern).
populatingList(
terminals,
terminalFactory,
regexParser),
Processing.rule().
including(detailRecordPattern).
populatingList(
flights,
flightFactory,
commaDelimitedParser))
.read();

assertEquals(1, terminals.size());
assertEquals(4, flights.size());
assertEquals(6, allRecords.getCount());
assertEquals(5, nonBlankRecords.getCount());
checkEntry(0, "BA123", "Glasgow", "09:45");
checkEntry(2, "BM435", "Bradford", "10:40");
}


which will read this file and create objects from it:


Terminal 1

BA123,Glasgow,09:45
IB236,Barcelona,10:20
BM435,Bradford,10:40
KL326,Amsterdam (Schipol),11:00

No comments: