package simpleorm.simplewebapp.eg.simple;
import simpleorm.simplewebapp.core.WException;
import java.util.*;
/**
* A crude mock up of a database to demonstrate SimpleWebApp.
* (The database classes use a real database via SimpleOrm.)
*/
public abstract class WTestDatabase {
/** db can be overriden in hibernate test. */
public static WTestDatabase db = new WMockDatabase().addTestRows();
public void beginTransaction(){}
public void endTransaction(){}
void addRow(String id, String name, String color, String alignment, String happy, Integer count, Date datefield) {
WTestRecord row = addRow(id);
row.name = name;
row.color = color;
row.alignment = alignment;
row.happy = happy;
row.count = count;
row.datefield = datefield;
}
public abstract WTestRecord addRow(String id);
public abstract WTestRecord findRow(String id);
public abstract void removeRow(String id);
public abstract String getDatabaseName();
/** Return a sorted iterator over all rows whose name contains nameWord */
public abstract Iterator<WTestRecord> getIterator(String nameWord, String sorter);
public WTestDatabase addTestRows() {
addRow("one", "The First one", "Green", "Middle", null, 100, null);
addRow("two", "This is the second row in the table", "Red", "Middle", null, 200, new Date("1/2/34"));
addRow("three", "Third one row", "Green", "Middle", null, 300, new Date("2/3/45"));
addRow("four", "A forth row", "Red", "Left", null, 401, new Date("3/4/56"));
addRow("five", "Fifth one", "Blue", "Right", null, 501, new Date("4/5/67"));
//Map fourth = new HashMap();
//fourth.put("four", "Fourth as map");
//fourth, // Alternate form todo But does not work -- more bugs in EL, see manuallisttest.jsp for experiments
return this;
}
public static class WMockDatabase extends WTestDatabase {
Map<String, WTestRecord> dbrows = new LinkedHashMap(10);
public @Override String getDatabaseName() {return "Mock Database";}
public WTestRecord addRow(String id) {
WTestRecord row = new WTestRecord(dbrows.size(), id);
dbrows.put(id, row);
return row;
}
public WTestRecord findRow(String id) {
return dbrows.get(id);
}
public void removeRow(String id) {
dbrows.remove(id);
}
/** Return a sorted iterator over all rows whose name contains nameWord */
public Iterator<WTestRecord> getIterator(String nameWord, String sorter) {
TreeMap<Comparable, WTestRecord> selected = new TreeMap<Comparable, WTestRecord>();
for ( WTestRecord row: dbrows.values() ) {
if ( nameWord == null || "".equals(nameWord) || row.name.contains(nameWord) ) {
Comparable key;
if ( sorter == null || "".equals(sorter) ) key = 1000000 + row.index;
else if ( "id".equals(sorter) ) key = row.idx;
else if ( "name".equals(sorter) ) key = row.name;
else if ( "color".equals(sorter) ) key = row.color;
else if ( "alignment".equals(sorter) ) key = row.alignment;
else if ( "count".equals(sorter) ) key = row.count;
else throw new WException("Bad sorter " + sorter);
selected.put(key + "_" + (1000000 + row.index), row);
}
}
return selected.values().iterator();
}
}
}
|