提交 e6fde6d9 authored 作者: Thomas Mueller's avatar Thomas Mueller

Limit line length to 80 characters

上级 e2f5284c
...@@ -41,7 +41,8 @@ public class DirectInsert { ...@@ -41,7 +41,8 @@ public class DirectInsert {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST"); stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)"); stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))"); PreparedStatement prep = conn.prepareStatement(
"INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))");
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
...@@ -58,14 +59,18 @@ public class DirectInsert { ...@@ -58,14 +59,18 @@ public class DirectInsert {
conn.close(); conn.close();
} }
private static void createAsSelect(String url, boolean optimize) throws SQLException { private static void createAsSelect(String url, boolean optimize)
Connection conn = DriverManager.getConnection(url + ";OPTIMIZE_INSERT_FROM_SELECT=" + optimize); throws SQLException {
Connection conn = DriverManager.getConnection(url +
";OPTIMIZE_INSERT_FROM_SELECT=" + optimize);
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST2"); stat.execute("DROP TABLE IF EXISTS TEST2");
System.out.println("CREATE TABLE ... AS SELECT " + (optimize ? "(optimized)" : "")); System.out.println("CREATE TABLE ... AS SELECT " +
(optimize ? "(optimized)" : ""));
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
stat.execute("CREATE TABLE TEST2 AS SELECT * FROM TEST"); stat.execute("CREATE TABLE TEST2 AS SELECT * FROM TEST");
System.out.printf("%.3f sec.\n", (System.currentTimeMillis() - time) / 1000.0); System.out.printf("%.3f sec.\n",
(System.currentTimeMillis() - time) / 1000.0);
stat.execute("INSERT INTO TEST2 SELECT * FROM TEST2"); stat.execute("INSERT INTO TEST2 SELECT * FROM TEST2");
stat.close(); stat.close();
conn.close(); conn.close();
......
...@@ -66,7 +66,8 @@ public class FileFunctions { ...@@ -66,7 +66,8 @@ public class FileFunctions {
* @param encoding the encoding * @param encoding the encoding
* @return the text * @return the text
*/ */
public static String readTextFileWithEncoding(String fileName, String encoding) throws IOException { public static String readTextFileWithEncoding(String fileName,
String encoding) throws IOException {
byte[] buff = readFile(fileName); byte[] buff = readFile(fileName);
String s = new String(buff, encoding); String s = new String(buff, encoding);
return s; return s;
......
...@@ -30,13 +30,16 @@ public class Function { ...@@ -30,13 +30,16 @@ public class Function {
*/ */
public static void main(String... args) throws Exception { public static void main(String... args) throws Exception {
Class.forName("org.h2.Driver"); Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", ""); Connection conn = DriverManager.getConnection(
"jdbc:h2:mem:", "sa", "");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
// Using a custom Java function // Using a custom Java function
stat.execute("CREATE ALIAS IS_PRIME FOR \"org.h2.samples.Function.isPrime\" "); stat.execute("CREATE ALIAS IS_PRIME " +
"FOR \"org.h2.samples.Function.isPrime\" ");
ResultSet rs; ResultSet rs;
rs = stat.executeQuery("SELECT IS_PRIME(X), X FROM SYSTEM_RANGE(1, 20) ORDER BY X"); rs = stat.executeQuery("SELECT IS_PRIME(X), X " +
"FROM SYSTEM_RANGE(1, 20) ORDER BY X");
while (rs.next()) { while (rs.next()) {
boolean isPrime = rs.getBoolean(1); boolean isPrime = rs.getBoolean(1);
if (isPrime) { if (isPrime) {
...@@ -49,7 +52,8 @@ public class Function { ...@@ -49,7 +52,8 @@ public class Function {
stat.execute("CREATE TABLE TEST(ID INT) AS " + stat.execute("CREATE TABLE TEST(ID INT) AS " +
"SELECT X FROM SYSTEM_RANGE(1, 100)"); "SELECT X FROM SYSTEM_RANGE(1, 100)");
PreparedStatement prep; PreparedStatement prep;
prep = conn.prepareStatement("SELECT * FROM TABLE(X INT=?, O INT=?) J " + prep = conn.prepareStatement(
"SELECT * FROM TABLE(X INT=?, O INT=?) J " +
"INNER JOIN TEST T ON J.X=T.ID ORDER BY J.O"); "INNER JOIN TEST T ON J.X=T.ID ORDER BY J.O");
prep.setObject(1, new Integer[] { 30, 20 }); prep.setObject(1, new Integer[] { 30, 20 });
prep.setObject(2, new Integer[] { 1, 2 }); prep.setObject(2, new Integer[] { 1, 2 });
...@@ -61,7 +65,8 @@ public class Function { ...@@ -61,7 +65,8 @@ public class Function {
rs.close(); rs.close();
// Using a custom function like table // Using a custom function like table
stat.execute("CREATE ALIAS MATRIX FOR \"org.h2.samples.Function.getMatrix\" "); stat.execute("CREATE ALIAS MATRIX " +
"FOR \"org.h2.samples.Function.getMatrix\" ");
prep = conn.prepareStatement("SELECT * FROM MATRIX(?) " + prep = conn.prepareStatement("SELECT * FROM MATRIX(?) " +
"ORDER BY X, Y"); "ORDER BY X, Y");
prep.setInt(1, 2); prep.setInt(1, 2);
......
...@@ -32,10 +32,13 @@ public class FunctionMultiReturn { ...@@ -32,10 +32,13 @@ public class FunctionMultiReturn {
*/ */
public static void main(String... args) throws Exception { public static void main(String... args) throws Exception {
Class.forName("org.h2.Driver"); Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", ""); Connection conn = DriverManager.getConnection(
"jdbc:h2:mem:", "sa", "");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS P2C FOR \"org.h2.samples.FunctionMultiReturn.polar2Cartesian\" "); stat.execute("CREATE ALIAS P2C " +
PreparedStatement prep = conn.prepareStatement("SELECT X, Y FROM P2C(?, ?)"); "FOR \"org.h2.samples.FunctionMultiReturn.polar2Cartesian\" ");
PreparedStatement prep = conn.prepareStatement(
"SELECT X, Y FROM P2C(?, ?)");
prep.setDouble(1, 5.0); prep.setDouble(1, 5.0);
prep.setDouble(2, 0.5); prep.setDouble(2, 0.5);
ResultSet rs = prep.executeQuery(); ResultSet rs = prep.executeQuery();
...@@ -47,18 +50,23 @@ public class FunctionMultiReturn { ...@@ -47,18 +50,23 @@ public class FunctionMultiReturn {
stat.execute("CREATE TABLE TEST(ID IDENTITY, R DOUBLE, A DOUBLE)"); stat.execute("CREATE TABLE TEST(ID IDENTITY, R DOUBLE, A DOUBLE)");
stat.execute("INSERT INTO TEST(R, A) VALUES(5.0, 0.5), (10.0, 0.6)"); stat.execute("INSERT INTO TEST(R, A) VALUES(5.0, 0.5), (10.0, 0.6)");
stat.execute("CREATE ALIAS P2C_SET FOR \"org.h2.samples.FunctionMultiReturn.polar2CartesianSet\" "); stat.execute("CREATE ALIAS P2C_SET " +
rs = conn.createStatement().executeQuery("SELECT * FROM P2C_SET('SELECT * FROM TEST')"); "FOR \"org.h2.samples.FunctionMultiReturn.polar2CartesianSet\" ");
rs = conn.createStatement().executeQuery(
"SELECT * FROM P2C_SET('SELECT * FROM TEST')");
while (rs.next()) { while (rs.next()) {
double r = rs.getDouble("R"); double r = rs.getDouble("R");
double a = rs.getDouble("A"); double a = rs.getDouble("A");
double x = rs.getDouble("X"); double x = rs.getDouble("X");
double y = rs.getDouble("Y"); double y = rs.getDouble("Y");
System.out.println("(r="+r+" a="+a+") : (x=" + x + ", y="+y+")"); System.out.println("(r="+r+" a="+a+") :" +
" (x=" + x + ", y="+y+")");
} }
stat.execute("CREATE ALIAS P2C_A FOR \"org.h2.samples.FunctionMultiReturn.polar2CartesianArray\" "); stat.execute("CREATE ALIAS P2C_A " +
rs = conn.createStatement().executeQuery("SELECT R, A, P2C_A(R, A) FROM TEST"); "FOR \"org.h2.samples.FunctionMultiReturn.polar2CartesianArray\" ");
rs = conn.createStatement().executeQuery(
"SELECT R, A, P2C_A(R, A) FROM TEST");
while (rs.next()) { while (rs.next()) {
double r = rs.getDouble(1); double r = rs.getDouble(1);
double a = rs.getDouble(2); double a = rs.getDouble(2);
...@@ -66,16 +74,20 @@ public class FunctionMultiReturn { ...@@ -66,16 +74,20 @@ public class FunctionMultiReturn {
Object[] xy = (Object[]) o; Object[] xy = (Object[]) o;
double x = ((Double) xy[0]).doubleValue(); double x = ((Double) xy[0]).doubleValue();
double y = ((Double) xy[1]).doubleValue(); double y = ((Double) xy[1]).doubleValue();
System.out.println("(r=" + r + " a=" + a + ") : (x=" + x + ", y=" + y + ")"); System.out.println("(r=" + r + " a=" + a + ") :" +
" (x=" + x + ", y=" + y + ")");
} }
rs = stat.executeQuery("SELECT R, A, ARRAY_GET(E, 1), ARRAY_GET(E, 2) FROM (SELECT R, A, P2C_A(R, A) E FROM TEST)"); rs = stat.executeQuery(
"SELECT R, A, ARRAY_GET(E, 1), ARRAY_GET(E, 2) " +
"FROM (SELECT R, A, P2C_A(R, A) E FROM TEST)");
while (rs.next()) { while (rs.next()) {
double r = rs.getDouble(1); double r = rs.getDouble(1);
double a = rs.getDouble(2); double a = rs.getDouble(2);
double x = rs.getDouble(3); double x = rs.getDouble(3);
double y = rs.getDouble(4); double y = rs.getDouble(4);
System.out.println("(r="+r+" a="+a+") : (x=" + x + ", y="+y+")"); System.out.println("(r="+r+" a="+a+") :" +
" (x=" + x + ", y="+y+")");
} }
rs.close(); rs.close();
...@@ -128,7 +140,8 @@ public class FunctionMultiReturn { ...@@ -128,7 +140,8 @@ public class FunctionMultiReturn {
* @param query the query * @param query the query
* @return a result set with the coordinates * @return a result set with the coordinates
*/ */
public static ResultSet polar2CartesianSet(Connection conn, String query) throws SQLException { public static ResultSet polar2CartesianSet(Connection conn, String query)
throws SQLException {
SimpleResultSet result = new SimpleResultSet(); SimpleResultSet result = new SimpleResultSet();
result.addColumn("R", Types.DOUBLE, 0, 0); result.addColumn("R", Types.DOUBLE, 0, 0);
result.addColumn("A", Types.DOUBLE, 0, 0); result.addColumn("A", Types.DOUBLE, 0, 0);
......
...@@ -30,19 +30,24 @@ public class MixedMode { ...@@ -30,19 +30,24 @@ public class MixedMode {
// start the server, allows to access the database remotely // start the server, allows to access the database remotely
Server server = Server.createTcpServer("-tcpPort", "9081"); Server server = Server.createTcpServer("-tcpPort", "9081");
server.start(); server.start();
System.out.println("You can access the database remotely now, using the URL:"); System.out.println(
System.out.println("jdbc:h2:tcp://localhost:9081/~/test (user: sa, password: sa)"); "You can access the database remotely now, using the URL:");
System.out.println(
"jdbc:h2:tcp://localhost:9081/~/test (user: sa, password: sa)");
// now use the database in your application in embedded mode // now use the database in your application in embedded mode
Class.forName("org.h2.Driver"); Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:~/test", "sa", "sa"); Connection conn = DriverManager.getConnection(
"jdbc:h2:~/test", "sa", "sa");
// some simple 'business usage' // some simple 'business usage'
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("DROP TABLE TIMER IF EXISTS"); stat.execute("DROP TABLE TIMER IF EXISTS");
stat.execute("CREATE TABLE TIMER(ID INT PRIMARY KEY, TIME VARCHAR)"); stat.execute("CREATE TABLE TIMER(ID INT PRIMARY KEY, TIME VARCHAR)");
System.out.println("Execute this a few times: SELECT TIME FROM TIMER"); System.out.println("Execute this a few times: " +
System.out.println("To stop this application (and the server), run: DROP TABLE TIMER"); "SELECT TIME FROM TIMER");
System.out.println("To stop this application " +
"(and the server), run: DROP TABLE TIMER");
try { try {
while (true) { while (true) {
// runs forever, except if you drop the table remotely // runs forever, except if you drop the table remotely
......
...@@ -32,13 +32,16 @@ public class RowAccessRights extends TriggerAdapter { ...@@ -32,13 +32,16 @@ public class RowAccessRights extends TriggerAdapter {
DeleteDbFiles.execute("~", "test", true); DeleteDbFiles.execute("~", "test", true);
Class.forName("org.h2.Driver"); Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:~/test"); Connection conn = DriverManager.getConnection(
"jdbc:h2:~/test");
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("create table test_data(id int, user varchar, data varchar, primary key(id, user))"); stat.execute("create table test_data(" +
"id int, user varchar, data varchar, primary key(id, user))");
stat.execute("create index on test_data(id, user)"); stat.execute("create index on test_data(id, user)");
stat.execute("create view test as select id, data from test_data where user = user()"); stat.execute("create view test as select id, data " +
"from test_data where user = user()");
stat.execute("create trigger t_test instead of " + stat.execute("create trigger t_test instead of " +
"insert, update, delete on test for each row " + "insert, update, delete on test for each row " +
"call \"" + RowAccessRights.class.getName() + "\""); "call \"" + RowAccessRights.class.getName() + "\"");
...@@ -49,13 +52,15 @@ public class RowAccessRights extends TriggerAdapter { ...@@ -49,13 +52,15 @@ public class RowAccessRights extends TriggerAdapter {
ResultSet rs; ResultSet rs;
Connection connA = DriverManager.getConnection("jdbc:h2:~/test", "a", "a"); Connection connA = DriverManager.getConnection(
"jdbc:h2:~/test", "a", "a");
Statement statA = connA.createStatement(); Statement statA = connA.createStatement();
statA.execute("insert into test values(1, 'Hello'), (2, 'World')"); statA.execute("insert into test values(1, 'Hello'), (2, 'World')");
statA.execute("update test set data = 'Hello!' where id = 1"); statA.execute("update test set data = 'Hello!' where id = 1");
statA.execute("delete from test where id = 2"); statA.execute("delete from test where id = 2");
Connection connB = DriverManager.getConnection("jdbc:h2:~/test", "b", "b"); Connection connB = DriverManager.getConnection(
"jdbc:h2:~/test", "b", "b");
Statement statB = connB.createStatement(); Statement statB = connB.createStatement();
statB.execute("insert into test values(1, 'Hallo'), (2, 'Welt')"); statB.execute("insert into test values(1, 'Hallo'), (2, 'Welt')");
statB.execute("update test set data = 'Hallo!' where id = 1"); statB.execute("update test set data = 'Hallo!' where id = 1");
...@@ -68,7 +73,8 @@ public class RowAccessRights extends TriggerAdapter { ...@@ -68,7 +73,8 @@ public class RowAccessRights extends TriggerAdapter {
rs = statB.executeQuery("select * from test"); rs = statB.executeQuery("select * from test");
while (rs.next()) { while (rs.next()) {
System.out.println("b: " + rs.getInt(1) + "/" + rs.getString(2)); System.out.println("b: " +
rs.getInt(1) + "/" + rs.getString(2));
} }
connA.close(); connA.close();
...@@ -76,7 +82,8 @@ public class RowAccessRights extends TriggerAdapter { ...@@ -76,7 +82,8 @@ public class RowAccessRights extends TriggerAdapter {
rs = stat.executeQuery("select * from test_data"); rs = stat.executeQuery("select * from test_data");
while (rs.next()) { while (rs.next()) {
System.out.println(rs.getInt(1) + "/" + rs.getString(2) + "/" + rs.getString(3)); System.out.println(rs.getInt(1) + "/" +
rs.getString(2) + "/" + rs.getString(3));
} }
conn.close(); conn.close();
...@@ -85,13 +92,16 @@ public class RowAccessRights extends TriggerAdapter { ...@@ -85,13 +92,16 @@ public class RowAccessRights extends TriggerAdapter {
@Override @Override
public void init(Connection conn, String schemaName, String triggerName, public void init(Connection conn, String schemaName, String triggerName,
String tableName, boolean before, int type) throws SQLException { String tableName, boolean before, int type) throws SQLException {
prepDelete = conn.prepareStatement("delete from test_data where id = ? and user = ?"); prepDelete = conn.prepareStatement(
prepInsert = conn.prepareStatement("insert into test_data values(?, ?, ?)"); "delete from test_data where id = ? and user = ?");
prepInsert = conn.prepareStatement(
"insert into test_data values(?, ?, ?)");
super.init(conn, schemaName, triggerName, tableName, before, type); super.init(conn, schemaName, triggerName, tableName, before, type);
} }
@Override @Override
public void fire(Connection conn, ResultSet oldRow, ResultSet newRow) throws SQLException { public void fire(Connection conn, ResultSet oldRow, ResultSet newRow)
throws SQLException {
String user = conn.getMetaData().getUserName(); String user = conn.getMetaData().getUserName();
if (oldRow != null && oldRow.next()) { if (oldRow != null && oldRow.next()) {
prepDelete.setInt(1, oldRow.getInt(1)); prepDelete.setInt(1, oldRow.getInt(1));
......
...@@ -54,7 +54,8 @@ public class SQLInjection { ...@@ -54,7 +54,8 @@ public class SQLInjection {
* @param user the user name * @param user the user name
* @param password the password * @param password the password
*/ */
void run(String driver, String url, String user, String password) throws Exception { void run(String driver, String url, String user, String password)
throws Exception {
Class.forName(driver); Class.forName(driver);
conn = DriverManager.getConnection(url, user, password); conn = DriverManager.getConnection(url, user, password);
stat = conn.createStatement(); stat = conn.createStatement();
...@@ -147,7 +148,8 @@ public class SQLInjection { ...@@ -147,7 +148,8 @@ public class SQLInjection {
* @param password the password * @param password the password
* @return a result set with the user record if the password matches * @return a result set with the user record if the password matches
*/ */
public static ResultSet getUser(Connection conn, String userName, String password) throws Exception { public static ResultSet getUser(Connection conn, String userName,
String password) throws Exception {
PreparedStatement prep = conn.prepareStatement( PreparedStatement prep = conn.prepareStatement(
"SELECT * FROM USERS WHERE NAME=? AND PASSWORD=?"); "SELECT * FROM USERS WHERE NAME=? AND PASSWORD=?");
prep.setString(1, userName); prep.setString(1, userName);
...@@ -164,7 +166,8 @@ public class SQLInjection { ...@@ -164,7 +166,8 @@ public class SQLInjection {
* @param password the password * @param password the password
* @return the new password * @return the new password
*/ */
public static String changePassword(Connection conn, String userName, String password) throws Exception { public static String changePassword(Connection conn, String userName,
String password) throws Exception {
PreparedStatement prep = conn.prepareStatement( PreparedStatement prep = conn.prepareStatement(
"UPDATE USERS SET PASSWORD=? WHERE NAME=?"); "UPDATE USERS SET PASSWORD=? WHERE NAME=?");
prep.setString(1, password); prep.setString(1, password);
......
...@@ -51,7 +51,10 @@ public class SecurePassword { ...@@ -51,7 +51,10 @@ public class SecurePassword {
stat.execute( stat.execute(
"drop table account if exists"); "drop table account if exists");
stat.execute( stat.execute(
"create table account(name varchar primary key, salt binary default secure_rand(16), hash binary)"); "create table account(" +
"name varchar primary key, " +
"salt binary default secure_rand(16), " +
"hash binary)");
PreparedStatement prep; PreparedStatement prep;
prep = conn.prepareStatement("insert into account(name) values(?)"); prep = conn.prepareStatement("insert into account(name) values(?)");
prep.setString(1, "Joe"); prep.setString(1, "Joe");
...@@ -59,14 +62,18 @@ public class SecurePassword { ...@@ -59,14 +62,18 @@ public class SecurePassword {
prep.close(); prep.close();
prep = conn.prepareStatement( prep = conn.prepareStatement(
"update account set hash=hash('SHA256', stringtoutf8(salt||?), 10) where name=?"); "update account set " +
"hash=hash('SHA256', stringtoutf8(salt||?), 10) " +
"where name=?");
prep.setString(1, "secret"); prep.setString(1, "secret");
prep.setString(2, "Joe"); prep.setString(2, "Joe");
prep.execute(); prep.execute();
prep.close(); prep.close();
prep = conn.prepareStatement( prep = conn.prepareStatement(
"select * from account where name=? and hash=hash('SHA256', stringtoutf8(salt||?), 10)"); "select * from account " +
"where name=? " +
"and hash=hash('SHA256', stringtoutf8(salt||?), 10)");
prep.setString(1, "Joe"); prep.setString(1, "Joe");
prep.setString(2, "secret"); prep.setString(2, "secret");
ResultSet rs = prep.executeQuery(); ResultSet rs = prep.executeQuery();
......
...@@ -51,7 +51,8 @@ public class ShowProgress implements DatabaseEventListener { ...@@ -51,7 +51,8 @@ public class ShowProgress implements DatabaseEventListener {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("DROP TABLE IF EXISTS TEST"); stat.execute("DROP TABLE IF EXISTS TEST");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)"); stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))"); PreparedStatement prep = conn.prepareStatement(
"INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))");
long time; long time;
time = System.currentTimeMillis(); time = System.currentTimeMillis();
int len = 1000; int len = 1000;
...@@ -78,7 +79,9 @@ public class ShowProgress implements DatabaseEventListener { ...@@ -78,7 +79,9 @@ public class ShowProgress implements DatabaseEventListener {
System.out.println("Open connection..."); System.out.println("Open connection...");
time = System.currentTimeMillis(); time = System.currentTimeMillis();
conn = DriverManager.getConnection("jdbc:h2:test;DATABASE_EVENT_LISTENER='" + getClass().getName() + "'", "sa", ""); conn = DriverManager.getConnection(
"jdbc:h2:test;DATABASE_EVENT_LISTENER='" +
getClass().getName() + "'", "sa", "");
time = System.currentTimeMillis() - time; time = System.currentTimeMillis() - time;
System.out.println("Done after " + time + " ms"); System.out.println("Done after " + time + " ms");
prep.close(); prep.close();
...@@ -133,7 +136,9 @@ public class ShowProgress implements DatabaseEventListener { ...@@ -133,7 +136,9 @@ public class ShowProgress implements DatabaseEventListener {
} catch (InterruptedException e) { } catch (InterruptedException e) {
// ignore // ignore
} }
System.out.println("State: " + stateName + " " + (100 * current / max) + "% (" + current + " of " + max + ") " System.out.println("State: " + stateName + " " +
(100 * current / max) + "% (" +
current + " of " + max + ") "
+ (time - start) + " ms"); + (time - start) + " ms");
} }
......
...@@ -82,13 +82,15 @@ public class TriggerPassData implements Trigger { ...@@ -82,13 +82,15 @@ public class TriggerPassData implements Trigger {
* @param trigger the trigger name * @param trigger the trigger name
* @param data the data * @param data the data
*/ */
public static void setTriggerData(Connection conn, String trigger, String data) throws SQLException { public static void setTriggerData(Connection conn, String trigger,
String data) throws SQLException {
TRIGGERS.get(getPrefix(conn) + trigger).triggerData = data; TRIGGERS.get(getPrefix(conn) + trigger).triggerData = data;
} }
private static String getPrefix(Connection conn) throws SQLException { private static String getPrefix(Connection conn) throws SQLException {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("call ifnull(database_path() || '_', '') || database() || '_'"); ResultSet rs = stat.executeQuery(
"call ifnull(database_path() || '_', '') || database() || '_'");
rs.next(); rs.next();
return rs.getString(1); return rs.getString(1);
} }
......
...@@ -77,7 +77,8 @@ public class TriggerSample { ...@@ -77,7 +77,8 @@ public class TriggerSample {
* @param type the operation type: INSERT, UPDATE, or DELETE * @param type the operation type: INSERT, UPDATE, or DELETE
*/ */
@Override @Override
public void init(Connection conn, String schemaName, String triggerName, String tableName, boolean before, int type) { public void init(Connection conn, String schemaName,
String triggerName, String tableName, boolean before, int type) {
// initialize the trigger object is necessary // initialize the trigger object is necessary
} }
......
...@@ -74,7 +74,8 @@ public class UpdatableView extends TriggerAdapter { ...@@ -74,7 +74,8 @@ public class UpdatableView extends TriggerAdapter {
} }
@Override @Override
public void fire(Connection conn, ResultSet oldRow, ResultSet newRow) throws SQLException { public void fire(Connection conn, ResultSet oldRow, ResultSet newRow)
throws SQLException {
if (oldRow != null && oldRow.next()) { if (oldRow != null && oldRow.next()) {
prepDelete.setInt(1, oldRow.getInt(1)); prepDelete.setInt(1, oldRow.getInt(1));
prepDelete.execute(); prepDelete.execute();
......
...@@ -172,7 +172,8 @@ public abstract class TestBase { ...@@ -172,7 +172,8 @@ public abstract class TestBase {
* @return the connection * @return the connection
*/ */
public Connection getConnection(String name) throws SQLException { public Connection getConnection(String name) throws SQLException {
return getConnectionInternal(getURL(name, true), getUser(), getPassword()); return getConnectionInternal(getURL(name, true), getUser(),
getPassword());
} }
/** /**
...@@ -183,7 +184,8 @@ public abstract class TestBase { ...@@ -183,7 +184,8 @@ public abstract class TestBase {
* @param password the password to use * @param password the password to use
* @return the connection * @return the connection
*/ */
public Connection getConnection(String name, String user, String password) throws SQLException { public Connection getConnection(String name, String user, String password)
throws SQLException {
return getConnectionInternal(getURL(name, false), user, password); return getConnectionInternal(getURL(name, false), user, password);
} }
...@@ -270,7 +272,8 @@ public abstract class TestBase { ...@@ -270,7 +272,8 @@ public abstract class TestBase {
url = "tcp://localhost:9192/" + name; url = "tcp://localhost:9192/" + name;
} }
} else if (config.googleAppEngine) { } else if (config.googleAppEngine) {
url = "gae://" + name + ";FILE_LOCK=NO;AUTO_SERVER=FALSE;DB_CLOSE_ON_EXIT=FALSE"; url = "gae://" + name +
";FILE_LOCK=NO;AUTO_SERVER=FALSE;DB_CLOSE_ON_EXIT=FALSE";
} else { } else {
url = name; url = name;
} }
...@@ -333,7 +336,8 @@ public abstract class TestBase { ...@@ -333,7 +336,8 @@ public abstract class TestBase {
return url; return url;
} }
private static Connection getConnectionInternal(String url, String user, String password) throws SQLException { private static Connection getConnectionInternal(String url, String user,
String password) throws SQLException {
org.h2.Driver.load(); org.h2.Driver.load();
// url += ";DEFAULT_TABLE_TYPE=1"; // url += ";DEFAULT_TABLE_TYPE=1";
// Class.forName("org.hsqldb.jdbcDriver"); // Class.forName("org.hsqldb.jdbcDriver");
...@@ -459,7 +463,8 @@ public abstract class TestBase { ...@@ -459,7 +463,8 @@ public abstract class TestBase {
e = new Exception(s); e = new Exception(s);
} }
System.out.flush(); System.out.flush();
System.err.println("ERROR: " + s + " " + e.toString() + " ------------------------------"); System.err.println("ERROR: " + s + " " + e.toString()
+ " ------------------------------");
e.printStackTrace(); e.printStackTrace();
try { try {
TraceSystem ts = new TraceSystem(null); TraceSystem ts = new TraceSystem(null);
...@@ -654,7 +659,8 @@ public abstract class TestBase { ...@@ -654,7 +659,8 @@ public abstract class TestBase {
* @param len the maximum length, or -1 * @param len the maximum length, or -1
* @throws AssertionError if the values are not equal * @throws AssertionError if the values are not equal
*/ */
protected void assertEqualReaders(Reader expected, Reader actual, int len) throws IOException { protected void assertEqualReaders(Reader expected, Reader actual, int len)
throws IOException {
for (int i = 0; len < 0 || i < len; i++) { for (int i = 0; len < 0 || i < len; i++) {
int ce = expected.read(); int ce = expected.read();
int ca = actual.read(); int ca = actual.read();
...@@ -675,7 +681,8 @@ public abstract class TestBase { ...@@ -675,7 +681,8 @@ public abstract class TestBase {
* @param len the maximum length, or -1 * @param len the maximum length, or -1
* @throws AssertionError if the values are not equal * @throws AssertionError if the values are not equal
*/ */
protected void assertEqualStreams(InputStream expected, InputStream actual, int len) throws IOException { protected void assertEqualStreams(InputStream expected, InputStream actual,
int len) throws IOException {
// this doesn't actually read anything - just tests reading 0 bytes // this doesn't actually read anything - just tests reading 0 bytes
actual.read(new byte[0]); actual.read(new byte[0]);
expected.read(new byte[0]); expected.read(new byte[0]);
...@@ -730,7 +737,8 @@ public abstract class TestBase { ...@@ -730,7 +737,8 @@ public abstract class TestBase {
if (bl > 4000) { if (bl > 4000) {
actual = actual.substring(0, 4000); actual = actual.substring(0, 4000);
} }
fail("Expected: " + expected + " (" + al + ") actual: " + actual + " (" + bl + ") " + message); fail("Expected: " + expected + " (" + al + ") actual: " + actual
+ " (" + bl + ") " + message);
} }
} }
...@@ -753,7 +761,8 @@ public abstract class TestBase { ...@@ -753,7 +761,8 @@ public abstract class TestBase {
* @param rs1 the second result set * @param rs1 the second result set
* @throws AssertionError if the values are not equal * @throws AssertionError if the values are not equal
*/ */
protected void assertEquals(String message, ResultSet rs0, ResultSet rs1) throws SQLException { protected void assertEquals(String message, ResultSet rs0, ResultSet rs1)
throws SQLException {
ResultSetMetaData meta = rs0.getMetaData(); ResultSetMetaData meta = rs0.getMetaData();
int columns = meta.getColumnCount(); int columns = meta.getColumnCount();
assertEquals(columns, rs1.getMetaData().getColumnCount()); assertEquals(columns, rs1.getMetaData().getColumnCount());
...@@ -948,7 +957,8 @@ public abstract class TestBase { ...@@ -948,7 +957,8 @@ public abstract class TestBase {
* @param expected the expected result value * @param expected the expected result value
* @throws AssertionError if a different result value was returned * @throws AssertionError if a different result value was returned
*/ */
protected void assertSingleValue(Statement stat, String sql, int expected) throws SQLException { protected void assertSingleValue(Statement stat, String sql, int expected)
throws SQLException {
ResultSet rs = stat.executeQuery(sql); ResultSet rs = stat.executeQuery(sql);
assertTrue(rs.next()); assertTrue(rs.next());
assertEquals(expected, rs.getInt(1)); assertEquals(expected, rs.getInt(1));
...@@ -963,7 +973,8 @@ public abstract class TestBase { ...@@ -963,7 +973,8 @@ public abstract class TestBase {
* @param sql the SQL statement to execute * @param sql the SQL statement to execute
* @throws AssertionError if a different result value was returned * @throws AssertionError if a different result value was returned
*/ */
protected void assertResult(String expected, Statement stat, String sql) throws SQLException { protected void assertResult(String expected, Statement stat, String sql)
throws SQLException {
ResultSet rs = stat.executeQuery(sql); ResultSet rs = stat.executeQuery(sql);
if (rs.next()) { if (rs.next()) {
String actual = rs.getString(1); String actual = rs.getString(1);
...@@ -980,7 +991,8 @@ public abstract class TestBase { ...@@ -980,7 +991,8 @@ public abstract class TestBase {
* @param stat the statement * @param stat the statement
* @param sql the SQL statement to execute * @param sql the SQL statement to execute
*/ */
protected void assertThrows(String expectedErrorMessage, Statement stat, String sql) { protected void assertThrows(String expectedErrorMessage, Statement stat,
String sql) {
try { try {
stat.executeQuery(sql); stat.executeQuery(sql);
fail("Expected error: " + expectedErrorMessage); fail("Expected error: " + expectedErrorMessage);
...@@ -999,8 +1011,9 @@ public abstract class TestBase { ...@@ -999,8 +1011,9 @@ public abstract class TestBase {
* @param precision the expected precisions * @param precision the expected precisions
* @param scale the expected scales * @param scale the expected scales
*/ */
protected void assertResultSetMeta(ResultSet rs, int columnCount, String[] labels, int[] datatypes, int[] precision, protected void assertResultSetMeta(ResultSet rs, int columnCount,
int[] scale) throws SQLException { String[] labels, int[] datatypes, int[] precision, int[] scale)
throws SQLException {
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
int cc = meta.getColumnCount(); int cc = meta.getColumnCount();
if (cc != columnCount) { if (cc != columnCount) {
...@@ -1069,7 +1082,8 @@ public abstract class TestBase { ...@@ -1069,7 +1082,8 @@ public abstract class TestBase {
* @param data the expected data * @param data the expected data
* @throws AssertionError if there is a mismatch * @throws AssertionError if there is a mismatch
*/ */
protected void assertResultSetOrdered(ResultSet rs, String[][] data) throws SQLException { protected void assertResultSetOrdered(ResultSet rs, String[][] data)
throws SQLException {
assertResultSet(true, rs, data); assertResultSet(true, rs, data);
} }
...@@ -1081,7 +1095,8 @@ public abstract class TestBase { ...@@ -1081,7 +1095,8 @@ public abstract class TestBase {
* @param data the expected data * @param data the expected data
* @throws AssertionError if there is a mismatch * @throws AssertionError if there is a mismatch
*/ */
private void assertResultSet(boolean ordered, ResultSet rs, String[][] data) throws SQLException { private void assertResultSet(boolean ordered, ResultSet rs, String[][] data)
throws SQLException {
int len = rs.getMetaData().getColumnCount(); int len = rs.getMetaData().getColumnCount();
int rows = data.length; int rows = data.length;
if (rows == 0) { if (rows == 0) {
...@@ -1102,7 +1117,8 @@ public abstract class TestBase { ...@@ -1102,7 +1117,8 @@ public abstract class TestBase {
if (ordered) { if (ordered) {
String[] good = data[i]; String[] good = data[i];
if (!testRow(good, row, good.length)) { if (!testRow(good, row, good.length)) {
fail("testResultSet row not equal, got:\n" + formatRow(row) + "\n" + formatRow(good)); fail("testResultSet row not equal, got:\n" + formatRow(row)
+ "\n" + formatRow(good));
} }
} else { } else {
boolean found = false; boolean found = false;
...@@ -1120,7 +1136,8 @@ public abstract class TestBase { ...@@ -1120,7 +1136,8 @@ public abstract class TestBase {
} }
if (rs.next()) { if (rs.next()) {
String[] row = getData(rs, len); String[] row = getData(rs, len);
fail("testResultSet expected rowcount:" + rows + " got:>=" + (rows + 1) + " data:" + formatRow(row)); fail("testResultSet expected rowcount:" + rows + " got:>="
+ (rows + 1) + " data:" + formatRow(row));
} }
} }
...@@ -1253,8 +1270,11 @@ public abstract class TestBase { ...@@ -1253,8 +1270,11 @@ public abstract class TestBase {
* @param stat2 the connection to the second database * @param stat2 the connection to the second database
* @throws AssertionError if the databases don't match * @throws AssertionError if the databases don't match
*/ */
protected void assertEqualDatabases(Statement stat1, Statement stat2) throws SQLException { protected void assertEqualDatabases(Statement stat1, Statement stat2)
ResultSet rs = stat1.executeQuery("select value from information_schema.settings where name='ANALYZE_AUTO'"); throws SQLException {
ResultSet rs = stat1.executeQuery(
"select value from information_schema.settings " +
"where name='ANALYZE_AUTO'");
int analyzeAuto = rs.next() ? rs.getInt(1) : 0; int analyzeAuto = rs.next() ? rs.getInt(1) : 0;
if (analyzeAuto > 0) { if (analyzeAuto > 0) {
stat1.execute("analyze"); stat1.execute("analyze");
...@@ -1356,10 +1376,12 @@ public abstract class TestBase { ...@@ -1356,10 +1376,12 @@ public abstract class TestBase {
* @param obj the object to wrap * @param obj the object to wrap
* @return a proxy for the object * @return a proxy for the object
*/ */
protected <T> T assertThrows(final Class<?> expectedExceptionClass, final T obj) { protected <T> T assertThrows(final Class<?> expectedExceptionClass,
final T obj) {
return assertThrows(new ResultVerifier() { return assertThrows(new ResultVerifier() {
@Override @Override
public boolean verify(Object returnValue, Throwable t, Method m, Object... args) { public boolean verify(Object returnValue, Throwable t, Method m,
Object... args) {
if (t == null) { if (t == null) {
throw new AssertionError("Expected an exception of type " + throw new AssertionError("Expected an exception of type " +
expectedExceptionClass.getSimpleName() + expectedExceptionClass.getSimpleName() +
...@@ -1394,7 +1416,8 @@ public abstract class TestBase { ...@@ -1394,7 +1416,8 @@ public abstract class TestBase {
protected <T> T assertThrows(final int expectedErrorCode, final T obj) { protected <T> T assertThrows(final int expectedErrorCode, final T obj) {
return assertThrows(new ResultVerifier() { return assertThrows(new ResultVerifier() {
@Override @Override
public boolean verify(Object returnValue, Throwable t, Method m, Object... args) { public boolean verify(Object returnValue, Throwable t, Method m,
Object... args) {
int errorCode; int errorCode;
if (t instanceof DbException) { if (t instanceof DbException) {
errorCode = ((DbException) t).getErrorCode(); errorCode = ((DbException) t).getErrorCode();
...@@ -1405,7 +1428,8 @@ public abstract class TestBase { ...@@ -1405,7 +1428,8 @@ public abstract class TestBase {
} }
if (errorCode != expectedErrorCode) { if (errorCode != expectedErrorCode) {
AssertionError ae = new AssertionError( AssertionError ae = new AssertionError(
"Expected an SQLException or DbException with error code " + expectedErrorCode); "Expected an SQLException or DbException with error code "
+ expectedErrorCode);
ae.initCause(t); ae.initCause(t);
throw ae; throw ae;
} }
...@@ -1434,7 +1458,8 @@ public abstract class TestBase { ...@@ -1434,7 +1458,8 @@ public abstract class TestBase {
} }
} }
@Override @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Exception { public Object invoke(Object proxy, Method method, Object[] args)
throws Exception {
try { try {
called = null; called = null;
Object ret = method.invoke(obj, args); Object ret = method.invoke(obj, args);
...@@ -1469,7 +1494,8 @@ public abstract class TestBase { ...@@ -1469,7 +1494,8 @@ public abstract class TestBase {
}; };
if (!ProxyCodeGenerator.isGenerated(c)) { if (!ProxyCodeGenerator.isGenerated(c)) {
Class<?>[] interfaces = c.getInterfaces(); Class<?>[] interfaces = c.getInterfaces();
if (Modifier.isFinal(c.getModifiers()) || (interfaces.length > 0 && getClass() != c)) { if (Modifier.isFinal(c.getModifiers())
|| (interfaces.length > 0 && getClass() != c)) {
// interface class proxies // interface class proxies
if (interfaces.length == 0) { if (interfaces.length == 0) {
throw new RuntimeException("Can not create a proxy for the class " + throw new RuntimeException("Can not create a proxy for the class " +
...@@ -1481,7 +1507,8 @@ public abstract class TestBase { ...@@ -1481,7 +1507,8 @@ public abstract class TestBase {
} }
try { try {
Class<?> pc = ProxyCodeGenerator.getClassProxy(c); Class<?> pc = ProxyCodeGenerator.getClassProxy(c);
Constructor<?> cons = pc.getConstructor(new Class<?>[] { InvocationHandler.class }); Constructor<?> cons = pc
.getConstructor(new Class<?>[] { InvocationHandler.class });
return (T) cons.newInstance(new Object[] { ih }); return (T) cons.newInstance(new Object[] { ih });
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
......
...@@ -43,10 +43,15 @@ public class TestStringUtils extends TestBase { ...@@ -43,10 +43,15 @@ public class TestStringUtils extends TestBase {
} }
private void testHex() { private void testHex() {
assertEquals("face", StringUtils.convertBytesToHex(new byte[] { (byte) 0xfa, (byte) 0xce })); assertEquals("face",
assertEquals(new byte[] { (byte) 0xfa, (byte) 0xce }, StringUtils.convertHexToBytes("face")); StringUtils.convertBytesToHex(new byte[]
assertEquals(new byte[] { (byte) 0xfa, (byte) 0xce }, StringUtils.convertHexToBytes("fAcE")); { (byte) 0xfa, (byte) 0xce }));
assertEquals(new byte[] { (byte) 0xfa, (byte) 0xce }, StringUtils.convertHexToBytes("FaCe")); assertEquals(new byte[] { (byte) 0xfa, (byte) 0xce },
StringUtils.convertHexToBytes("face"));
assertEquals(new byte[] { (byte) 0xfa, (byte) 0xce },
StringUtils.convertHexToBytes("fAcE"));
assertEquals(new byte[] { (byte) 0xfa, (byte) 0xce },
StringUtils.convertHexToBytes("FaCe"));
new AssertThrows(DbException.class) { @Override new AssertThrows(DbException.class) { @Override
public void test() { public void test() {
StringUtils.convertHexToBytes("120"); StringUtils.convertHexToBytes("120");
...@@ -69,40 +74,67 @@ public class TestStringUtils extends TestBase { ...@@ -69,40 +74,67 @@ public class TestStringUtils extends TestBase {
} }
private void testXML() { private void testXML() {
assertEquals("<!-- - - - - - -abc- - - - - - -->\n", StringUtils.xmlComment("------abc------")); assertEquals("<!-- - - - - - -abc- - - - - - -->\n",
assertEquals("<test/>\n", StringUtils.xmlNode("test", null, null)); StringUtils.xmlComment("------abc------"));
assertEquals("<test>Gr&#xfc;bel</test>\n", StringUtils.xmlNode("test", null, StringUtils.xmlText("Gr\u00fcbel"))); assertEquals("<test/>\n",
assertEquals("Rand&amp;Blue", StringUtils.xmlText("Rand&Blue")); StringUtils.xmlNode("test", null, null));
assertEquals("&lt;&lt;[[[]]]&gt;&gt;", StringUtils.xmlCData("<<[[[]]]>>")); assertEquals("<test>Gr&#xfc;bel</test>\n",
Date dt = DateTimeUtils.parseDateTime("2001-02-03 04:05:06 GMT", "yyyy-MM-dd HH:mm:ss z", "en", "GMT"); StringUtils.xmlNode("test", null,
StringUtils.xmlText("Gr\u00fcbel")));
assertEquals("Rand&amp;Blue",
StringUtils.xmlText("Rand&Blue"));
assertEquals("&lt;&lt;[[[]]]&gt;&gt;",
StringUtils.xmlCData("<<[[[]]]>>"));
Date dt = DateTimeUtils.parseDateTime(
"2001-02-03 04:05:06 GMT",
"yyyy-MM-dd HH:mm:ss z", "en", "GMT");
String s = StringUtils.xmlStartDoc() String s = StringUtils.xmlStartDoc()
+ StringUtils.xmlComment("Test Comment") + StringUtils.xmlComment("Test Comment")
+ StringUtils.xmlNode("rss", StringUtils.xmlAttr("version", "2.0"), StringUtils + StringUtils.xmlNode("rss",
.xmlComment("Test Comment\nZeile2") StringUtils.xmlAttr("version", "2.0"),
+ StringUtils.xmlNode("channel", null, StringUtils.xmlNode("title", null, "H2 Database Engine") StringUtils.xmlComment("Test Comment\nZeile2")
+ StringUtils.xmlNode("channel", null,
StringUtils.xmlNode("title", null, "H2 Database Engine")
+ StringUtils.xmlNode("link", null, "http://www.h2database.com")
+ StringUtils.xmlNode("description", null, "H2 Database Engine")
+ StringUtils.xmlNode("language", null, "en-us")
+ StringUtils.xmlNode("pubDate", null,
DateTimeUtils.formatDateTime(dt,
"EEE, d MMM yyyy HH:mm:ss z", "en", "GMT"))
+ StringUtils.xmlNode("lastBuildDate", null,
DateTimeUtils.formatDateTime(dt,
"EEE, d MMM yyyy HH:mm:ss z", "en", "GMT"))
+ StringUtils.xmlNode("item", null,
StringUtils.xmlNode("title", null,
"New Version 0.9.9.9.9")
+ StringUtils.xmlNode("link", null, "http://www.h2database.com") + StringUtils.xmlNode("link", null, "http://www.h2database.com")
+ StringUtils.xmlNode("description", null, "H2 Database Engine") + StringUtils.xmlNode("description", null,
+ StringUtils.xmlNode("language", null, "en-us") StringUtils.xmlCData("\nNew Features\nTest\n")))));
+ StringUtils.xmlNode("pubDate", null, DateTimeUtils.formatDateTime(dt, assertEquals(
"EEE, d MMM yyyy HH:mm:ss z", "en", "GMT")) s,
+ StringUtils.xmlNode("lastBuildDate", null, DateTimeUtils.formatDateTime(dt, "<?xml version=\"1.0\"?>\n"
"EEE, d MMM yyyy HH:mm:ss z", "en", "GMT")) + "<!-- Test Comment -->\n"
+ StringUtils.xmlNode("item", null, StringUtils.xmlNode("title", null, + "<rss version=\"2.0\">\n"
"New Version 0.9.9.9.9") + " <!--\n"
+ StringUtils.xmlNode("link", null, "http://www.h2database.com") + " Test Comment\n"
+ StringUtils.xmlNode("description", null, StringUtils + " Zeile2\n"
.xmlCData("\nNew Features\nTest\n"))))); + " -->\n"
assertEquals(s, "<?xml version=\"1.0\"?>\n" + "<!-- Test Comment -->\n" + "<rss version=\"2.0\">\n" + " <!--\n" + " <channel>\n"
+ " Test Comment\n" + " Zeile2\n" + " -->\n" + " <channel>\n" + " <title>H2 Database Engine</title>\n"
+ " <title>H2 Database Engine</title>\n" + " <link>http://www.h2database.com</link>\n" + " <link>http://www.h2database.com</link>\n"
+ " <description>H2 Database Engine</description>\n" + " <language>en-us</language>\n" + " <description>H2 Database Engine</description>\n"
+ " <pubDate>Sat, 3 Feb 2001 04:05:06 GMT</pubDate>\n" + " <language>en-us</language>\n"
+ " <lastBuildDate>Sat, 3 Feb 2001 04:05:06 GMT</lastBuildDate>\n" + " <item>\n" + " <pubDate>Sat, 3 Feb 2001 04:05:06 GMT</pubDate>\n"
+ " <title>New Version 0.9.9.9.9</title>\n" + " <lastBuildDate>Sat, 3 Feb 2001 04:05:06 GMT</lastBuildDate>\n"
+ " <link>http://www.h2database.com</link>\n" + " <description>\n" + " <item>\n"
+ " <![CDATA[\n" + " New Features\n" + " Test\n" + " <title>New Version 0.9.9.9.9</title>\n"
+ " ]]>\n" + " </description>\n" + " </item>\n" + " </channel>\n" + " <link>http://www.h2database.com</link>\n"
+ "</rss>\n"); + " <description>\n"
+ " <![CDATA[\n"
+ " New Features\n"
+ " Test\n" + " ]]>\n"
+ " </description>\n" + " </item>\n"
+ " </channel>\n" + "</rss>\n");
} }
private void testURL() throws UnsupportedEncodingException { private void testURL() throws UnsupportedEncodingException {
...@@ -172,15 +204,24 @@ public class TestStringUtils extends TestBase { ...@@ -172,15 +204,24 @@ public class TestStringUtils extends TestBase {
} }
private void testReplaceAll() { private void testReplaceAll() {
assertEquals("def", StringUtils.replaceAll("abc def", "abc ", "")); assertEquals("def",
assertEquals("af", StringUtils.replaceAll("abc def", "bc de", "")); StringUtils.replaceAll("abc def", "abc ", ""));
assertEquals("abc def", StringUtils.replaceAll("abc def", "bc ", "bc ")); assertEquals("af",
assertEquals("abc ", StringUtils.replaceAll("abc def", "def", "")); StringUtils.replaceAll("abc def", "bc de", ""));
assertEquals(" ", StringUtils.replaceAll("abc abc", "abc", "")); assertEquals("abc def",
assertEquals("xyz xyz", StringUtils.replaceAll("abc abc", "abc", "xyz")); StringUtils.replaceAll("abc def", "bc ", "bc "));
assertEquals("abc def", StringUtils.replaceAll("abc def", "xyz", "abc")); assertEquals("abc ",
assertEquals("", StringUtils.replaceAll("abcabcabc", "abc", "")); StringUtils.replaceAll("abc def", "def", ""));
assertEquals("abcabcabc", StringUtils.replaceAll("abcabcabc", "aBc", "")); assertEquals(" ",
StringUtils.replaceAll("abc abc", "abc", ""));
assertEquals("xyz xyz",
StringUtils.replaceAll("abc abc", "abc", "xyz"));
assertEquals("abc def",
StringUtils.replaceAll("abc def", "xyz", "abc"));
assertEquals("",
StringUtils.replaceAll("abcabcabc", "abc", ""));
assertEquals("abcabcabc",
StringUtils.replaceAll("abcabcabc", "aBc", ""));
} }
} }
...@@ -17,12 +17,14 @@ import android.database.Cursor; ...@@ -17,12 +17,14 @@ import android.database.Cursor;
public class Test extends Activity { public class Test extends Activity {
public static void main(String... args) throws Exception { public static void main(String... args) throws Exception {
H2Database db = H2Utils.openOrCreateDatabase("helloWorld.db", MODE_PRIVATE, null); H2Database db = H2Utils.openOrCreateDatabase(
"helloWorld.db", MODE_PRIVATE, null);
log("opened ps=" + db.getPageSize()); log("opened ps=" + db.getPageSize());
try { try {
// db.execSQL("DROP TABLE IF EXISTS test"); // db.execSQL("DROP TABLE IF EXISTS test");
// log("dropped"); // log("dropped");
db.execSQL("CREATE TABLE if not exists test(ID INTEGER PRIMARY KEY, NAME VARCHAR)"); db.execSQL(
"CREATE TABLE if not exists test(ID INTEGER PRIMARY KEY, NAME VARCHAR)");
log("created"); log("created");
for (int j = 0; j < 10; j++) { for (int j = 0; j < 10; j++) {
Cursor c = db.rawQuery("select * from test", new String[0]); Cursor c = db.rawQuery("select * from test", new String[0]);
...@@ -39,13 +41,15 @@ public class Test extends Activity { ...@@ -39,13 +41,15 @@ public class Test extends Activity {
log("delete"); log("delete");
db.beginTransaction(); db.beginTransaction();
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
db.execSQL("INSERT INTO TEST VALUES(?, 'Hello')", new Object[] { i }); db.execSQL(
"INSERT INTO TEST VALUES(?, 'Hello')", new Object[] { i });
} }
db.setTransactionSuccessful(); db.setTransactionSuccessful();
db.endTransaction(); db.endTransaction();
log("inserted"); log("inserted");
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
Cursor c = db.rawQuery("select * from test where id=?", new String[] { "" + i }); Cursor c = db.rawQuery(
"select * from test where id=?", new String[] { "" + i });
int count = c.getCount(); int count = c.getCount();
if (count > 0) { if (count > 0) {
c.move(1); c.move(1);
......
...@@ -24,7 +24,8 @@ public class H2Cursor extends AbstractWindowedCursor { ...@@ -24,7 +24,8 @@ public class H2Cursor extends AbstractWindowedCursor {
private H2Database database; private H2Database database;
private ResultInterface result; private ResultInterface result;
H2Cursor(H2Database db, H2CursorDriver driver, String editTable, H2Query query) { H2Cursor(H2Database db, H2CursorDriver driver, String editTable,
H2Query query) {
this.database = db; this.database = db;
// TODO // TODO
} }
......
...@@ -16,7 +16,6 @@ import org.h2.engine.Database; ...@@ -16,7 +16,6 @@ import org.h2.engine.Database;
import org.h2.engine.Session; import org.h2.engine.Session;
import org.h2.expression.Parameter; import org.h2.expression.Parameter;
import org.h2.result.ResultInterface; import org.h2.result.ResultInterface;
import org.h2.store.PageStore;
import org.h2.value.Value; import org.h2.value.Value;
import org.h2.value.ValueInt; import org.h2.value.ValueInt;
import org.h2.value.ValueLong; import org.h2.value.ValueLong;
...@@ -111,7 +110,8 @@ public class H2Database { ...@@ -111,7 +110,8 @@ public class H2Database {
* @param flags 0, or a combination of OPEN_READONLY and CREATE_IF_NECESSARY * @param flags 0, or a combination of OPEN_READONLY and CREATE_IF_NECESSARY
* @return a connection to this database * @return a connection to this database
*/ */
public static H2Database openDatabase(String path, H2Database.CursorFactory factory, int flags) { public static H2Database openDatabase(String path,
H2Database.CursorFactory factory, int flags) {
ConnectionInfo ci = new ConnectionInfo(path); ConnectionInfo ci = new ConnectionInfo(path);
if ((flags & OPEN_READWRITE) != 0) { if ((flags & OPEN_READWRITE) != 0) {
// TODO readonly connections // TODO readonly connections
...@@ -133,7 +133,8 @@ public class H2Database { ...@@ -133,7 +133,8 @@ public class H2Database {
* @param factory the cursor factory * @param factory the cursor factory
* @return a connection to this database * @return a connection to this database
*/ */
public static H2Database openOrCreateDatabase(File file, H2Database.CursorFactory factory) { public static H2Database openOrCreateDatabase(File file,
H2Database.CursorFactory factory) {
return openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY); return openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY);
} }
...@@ -145,7 +146,8 @@ public class H2Database { ...@@ -145,7 +146,8 @@ public class H2Database {
* @param factory the cursor factory * @param factory the cursor factory
* @return a connection to this database * @return a connection to this database
*/ */
public static H2Database openOrCreateDatabase(String path, H2Database.CursorFactory factory) { public static H2Database openOrCreateDatabase(String path,
H2Database.CursorFactory factory) {
return openDatabase(path, factory, CREATE_IF_NECESSARY); return openDatabase(path, factory, CREATE_IF_NECESSARY);
} }
...@@ -161,7 +163,8 @@ public class H2Database { ...@@ -161,7 +163,8 @@ public class H2Database {
* *
* @param transactionListener the transaction listener to use * @param transactionListener the transaction listener to use
*/ */
public void beginTransactionWithListener(H2TransactionListener transactionListener) { public void beginTransactionWithListener(
H2TransactionListener transactionListener) {
// TODO H2TransactionListener // TODO H2TransactionListener
session.setAutoCommit(false); session.setAutoCommit(false);
} }
...@@ -306,7 +309,8 @@ public class H2Database { ...@@ -306,7 +309,8 @@ public class H2Database {
* @param values the values * @param values the values
* @return TODO * @return TODO
*/ */
public long insertOrThrow(String table, String nullColumnHack, ContentValues values) { public long insertOrThrow(String table, String nullColumnHack,
ContentValues values) {
return 0; return 0;
} }
...@@ -377,7 +381,8 @@ public class H2Database { ...@@ -377,7 +381,8 @@ public class H2Database {
* @param foreignKey the foreign key * @param foreignKey the foreign key
* @param updateTable TODO * @param updateTable TODO
*/ */
public void markTableSyncable(String table, String foreignKey, String updateTable) { public void markTableSyncable(String table, String foreignKey,
String updateTable) {
// TODO // TODO
} }
...@@ -405,8 +410,9 @@ public class H2Database { ...@@ -405,8 +410,9 @@ public class H2Database {
* @param limit the limit or null * @param limit the limit or null
* @return the cursor * @return the cursor
*/ */
public Cursor query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, public Cursor query(boolean distinct, String table, String[] columns,
String groupBy, String having, String orderBy, String limit) { String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit) {
return null; return null;
} }
...@@ -422,8 +428,9 @@ public class H2Database { ...@@ -422,8 +428,9 @@ public class H2Database {
* @param orderBy the order by list or null * @param orderBy the order by list or null
* @return the cursor * @return the cursor
*/ */
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, public Cursor query(String table, String[] columns, String selection,
String having, String orderBy) { String[] selectionArgs, String groupBy, String having,
String orderBy) {
return null; return null;
} }
...@@ -440,8 +447,9 @@ public class H2Database { ...@@ -440,8 +447,9 @@ public class H2Database {
* @param limit the limit or null * @param limit the limit or null
* @return the cursor * @return the cursor
*/ */
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, public Cursor query(String table, String[] columns, String selection,
String having, String orderBy, String limit) { String[] selectionArgs, String groupBy, String having,
String orderBy, String limit) {
return null; return null;
} }
...@@ -460,8 +468,10 @@ public class H2Database { ...@@ -460,8 +468,10 @@ public class H2Database {
* @param limit the limit or null * @param limit the limit or null
* @return the cursor * @return the cursor
*/ */
public Cursor queryWithFactory(H2Database.CursorFactory cursorFactory, boolean distinct, String table, String[] columns, public Cursor queryWithFactory(H2Database.CursorFactory cursorFactory,
String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { boolean distinct, String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy, String limit) {
return null; return null;
} }
...@@ -487,8 +497,8 @@ public class H2Database { ...@@ -487,8 +497,8 @@ public class H2Database {
* @param editTable TODO * @param editTable TODO
* @return the cursor * @return the cursor
*/ */
public Cursor rawQueryWithFactory(H2Database.CursorFactory cursorFactory, String sql, String[] selectionArgs, public Cursor rawQueryWithFactory(H2Database.CursorFactory cursorFactory,
String editTable) { String sql, String[] selectionArgs, String editTable) {
return null; return null;
} }
...@@ -509,7 +519,8 @@ public class H2Database { ...@@ -509,7 +519,8 @@ public class H2Database {
* @param initialValues the values * @param initialValues the values
* @return TODO * @return TODO
*/ */
public long replace(String table, String nullColumnHack, ContentValues initialValues) { public long replace(String table, String nullColumnHack,
ContentValues initialValues) {
return 0; return 0;
} }
...@@ -521,7 +532,8 @@ public class H2Database { ...@@ -521,7 +532,8 @@ public class H2Database {
* @param initialValues the values * @param initialValues the values
* @return TODO * @return TODO
*/ */
public long replaceOrThrow(String table, String nullColumnHack, ContentValues initialValues) { public long replaceOrThrow(String table, String nullColumnHack,
ContentValues initialValues) {
return 0; return 0;
} }
...@@ -588,7 +600,8 @@ public class H2Database { ...@@ -588,7 +600,8 @@ public class H2Database {
* @param whereArgs the parameter values * @param whereArgs the parameter values
* @return the number of rows updated * @return the number of rows updated
*/ */
public int update(String table, ContentValues values, String whereClause, String[] whereArgs) { public int update(String table, ContentValues values, String whereClause,
String[] whereArgs) {
return 0; return 0;
} }
...@@ -602,8 +615,8 @@ public class H2Database { ...@@ -602,8 +615,8 @@ public class H2Database {
* @param conflictAlgorithm the conflict resolution option * @param conflictAlgorithm the conflict resolution option
* @return the number of rows updated * @return the number of rows updated
*/ */
public int updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, public int updateWithOnConflict(String table, ContentValues values,
int conflictAlgorithm) { String whereClause, String[] whereArgs, int conflictAlgorithm) {
return 0; return 0;
} }
...@@ -650,7 +663,8 @@ public class H2Database { ...@@ -650,7 +663,8 @@ public class H2Database {
* @param query TODO * @param query TODO
* @return the cursor * @return the cursor
*/ */
Cursor newCursor(H2Database db, H2CursorDriver masterQuery, String editTable, H2Query query); Cursor newCursor(H2Database db, H2CursorDriver masterQuery,
String editTable, H2Query query);
} }
private Prepared prepare(String sql, Object[] args) { private Prepared prepare(String sql, Object[] args) {
......
...@@ -22,7 +22,8 @@ public abstract class H2OpenHelper { ...@@ -22,7 +22,8 @@ public abstract class H2OpenHelper {
* @param factory the cursor factory to use * @param factory the cursor factory to use
* @param version the expected database version * @param version the expected database version
*/ */
H2OpenHelper(Context context, String name, H2Database.CursorFactory factory, int version) { H2OpenHelper(Context context, String name,
H2Database.CursorFactory factory, int version) {
// TODO // TODO
} }
......
...@@ -49,8 +49,9 @@ public class H2QueryBuilder { ...@@ -49,8 +49,9 @@ public class H2QueryBuilder {
* @param limit the limit or null * @param limit the limit or null
* @return the query * @return the query
*/ */
static String buildQueryString(boolean distinct, String tables, String[] columns, String where, String groupBy, static String buildQueryString(boolean distinct, String tables,
String having, String orderBy, String limit) { String[] columns, String where, String groupBy, String having,
String orderBy, String limit) {
StringBuilder s = new StringBuilder(); StringBuilder s = new StringBuilder();
s.append("select "); s.append("select ");
if (distinct) { if (distinct) {
...@@ -106,7 +107,8 @@ public class H2QueryBuilder { ...@@ -106,7 +107,8 @@ public class H2QueryBuilder {
* @param limit the limit or null * @param limit the limit or null
* @return the query * @return the query
*/ */
String buildQuery(String[] projectionIn, String selection, String[] selectionArgs, String groupBy, String having, String buildQuery(String[] projectionIn, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy, String limit) { String orderBy, String limit) {
return null; return null;
} }
...@@ -138,9 +140,11 @@ public class H2QueryBuilder { ...@@ -138,9 +140,11 @@ public class H2QueryBuilder {
* @param having the having condition or null * @param having the having condition or null
* @return the query * @return the query
*/ */
String buildUnionSubQuery(String typeDiscriminatorColumn, String[] unionColumns, Set<String> columnsPresentInTable, String buildUnionSubQuery(String typeDiscriminatorColumn,
int computedColumnsOffset, String typeDiscriminatorValue, String selection, String[] selectionArgs, String[] unionColumns, Set<String> columnsPresentInTable,
String groupBy, String having) { int computedColumnsOffset, String typeDiscriminatorValue,
String selection, String[] selectionArgs, String groupBy,
String having) {
return null; return null;
} }
...@@ -166,8 +170,9 @@ public class H2QueryBuilder { ...@@ -166,8 +170,9 @@ public class H2QueryBuilder {
* @param orderBy the order by list or null * @param orderBy the order by list or null
* @return the cursor * @return the cursor
*/ */
Cursor query(H2Database db, String[] projectionIn, String selection, String[] selectionArgs, String groupBy, Cursor query(H2Database db, String[] projectionIn, String selection,
String having, String orderBy) { String[] selectionArgs, String groupBy, String having,
String orderBy) {
return null; return null;
} }
...@@ -184,8 +189,9 @@ public class H2QueryBuilder { ...@@ -184,8 +189,9 @@ public class H2QueryBuilder {
* @param limit the limit or null * @param limit the limit or null
* @return the cursor * @return the cursor
*/ */
Cursor query(H2Database db, String[] projectionIn, String selection, String[] selectionArgs, String groupBy, Cursor query(H2Database db, String[] projectionIn, String selection,
String having, String orderBy, String limit) { String[] selectionArgs, String groupBy, String having,
String orderBy, String limit) {
return null; return null;
} }
......
...@@ -19,7 +19,8 @@ public class H2Utils { ...@@ -19,7 +19,8 @@ public class H2Utils {
* @param factory the cursor factory to use * @param factory the cursor factory to use
* @return the database connection * @return the database connection
*/ */
public static H2Database openOrCreateDatabase(String name, int mode, H2Database.CursorFactory factory) { public static H2Database openOrCreateDatabase(String name, int mode,
H2Database.CursorFactory factory) {
return H2Database.openOrCreateDatabase(name, factory); return H2Database.openOrCreateDatabase(name, factory);
} }
......
...@@ -39,29 +39,37 @@ public class Build extends BuildBase { ...@@ -39,29 +39,37 @@ public class Build extends BuildBase {
* Run the benchmarks. * Run the benchmarks.
*/ */
public void benchmark() { public void benchmark() {
downloadUsingMaven("ext/hsqldb-2.0.0.jar", "hsqldb", "hsqldb", "2.0.0", downloadUsingMaven("ext/hsqldb-2.0.0.jar",
"hsqldb", "hsqldb", "2.0.0",
"c9d525ce1a464185e6b01c7de872127a06092673"); "c9d525ce1a464185e6b01c7de872127a06092673");
downloadUsingMaven("ext/derby-10.6.1.0.jar", "org/apache/derby", "derby", "10.6.1.0", downloadUsingMaven("ext/derby-10.6.1.0.jar",
"org/apache/derby", "derby", "10.6.1.0",
"01137cd636b0e3c22f0d273478adb58aa30e984a"); "01137cd636b0e3c22f0d273478adb58aa30e984a");
downloadUsingMaven("ext/derbyclient-10.6.1.0.jar", "org/apache/derby", "derbyclient", "10.6.1.0", downloadUsingMaven("ext/derbyclient-10.6.1.0.jar",
"org/apache/derby", "derbyclient", "10.6.1.0",
"e7c6fbaca2ef4dbcad27fa7d8a9cd1ac0d1e4b00"); "e7c6fbaca2ef4dbcad27fa7d8a9cd1ac0d1e4b00");
downloadUsingMaven("ext/derbynet-10.6.1.0.jar", "org/apache/derby", "derbynet", "10.6.1.0", downloadUsingMaven("ext/derbynet-10.6.1.0.jar",
"org/apache/derby", "derbynet", "10.6.1.0",
"d5d9d7b783eeaef016be85c34d5c65d1e7cec764"); "d5d9d7b783eeaef016be85c34d5c65d1e7cec764");
downloadUsingMaven("ext/postgresql-8.3-603.jdbc3.jar", "postgresql", "postgresql", "8.3-603.jdbc3", downloadUsingMaven("ext/postgresql-8.3-603.jdbc3.jar",
"postgresql", "postgresql", "8.3-603.jdbc3",
"33d531c3c53055ddcbea3d88bfa093466ffef924"); "33d531c3c53055ddcbea3d88bfa093466ffef924");
downloadUsingMaven("ext/mysql-connector-java-5.1.6.jar", "mysql", "mysql-connector-java", "5.1.6", downloadUsingMaven("ext/mysql-connector-java-5.1.6.jar",
"mysql", "mysql-connector-java", "5.1.6",
"380ef5226de2c85ff3b38cbfefeea881c5fce09d"); "380ef5226de2c85ff3b38cbfefeea881c5fce09d");
compile(); compile();
String cp = "temp" + File.pathSeparator + "bin/h2" + getJarSuffix() + File.pathSeparator + String cp = "temp" +
"ext/hsqldb.jar" + File.pathSeparator + File.pathSeparator + "bin/h2" + getJarSuffix() +
"ext/hsqldb-2.0.0.jar" + File.pathSeparator + File.pathSeparator + "ext/hsqldb.jar" +
"ext/derby-10.6.1.0.jar" + File.pathSeparator + File.pathSeparator + "ext/hsqldb-2.0.0.jar" +
"ext/derbyclient-10.6.1.0.jar" + File.pathSeparator + File.pathSeparator + "ext/derby-10.6.1.0.jar" +
"ext/derbynet-10.6.1.0.jar" + File.pathSeparator + File.pathSeparator + "ext/derbyclient-10.6.1.0.jar" +
"ext/postgresql-8.3-603.jdbc3.jar" + File.pathSeparator + File.pathSeparator + "ext/derbynet-10.6.1.0.jar" +
"ext/mysql-connector-java-5.1.6.jar"; File.pathSeparator + "ext/postgresql-8.3-603.jdbc3.jar" +
StringList args = args("-Xmx128m", "-cp", cp, "org.h2.test.bench.TestPerformance"); File.pathSeparator + "ext/mysql-connector-java-5.1.6.jar";
StringList args = args("-Xmx128m",
"-cp", cp, "org.h2.test.bench.TestPerformance");
exec("java", args.plus("-init", "-db", "1")); exec("java", args.plus("-init", "-db", "1"));
exec("java", args.plus("-db", "2")); exec("java", args.plus("-db", "2"));
exec("java", args.plus("-db", "3", "-out", "pe.html")); exec("java", args.plus("-db", "3", "-out", "pe.html"));
...@@ -93,7 +101,8 @@ public class Build extends BuildBase { ...@@ -93,7 +101,8 @@ public class Build extends BuildBase {
private void compileTools() { private void compileTools() {
FileList files = files("src/tools").keep("src/tools/org/h2/build/*"); FileList files = files("src/tools").keep("src/tools/org/h2/build/*");
StringList args = args("-d", "temp", "-sourcepath", "src/tools" + StringList args = args("-d", "temp", "-sourcepath", "src/tools" +
File.pathSeparator + "src/test" + File.pathSeparator + "src/main"); File.pathSeparator + "src/test" +
File.pathSeparator + "src/main");
mkdir("temp"); mkdir("temp");
javac(args, files); javac(args, files);
} }
...@@ -117,7 +126,8 @@ public class Build extends BuildBase { ...@@ -117,7 +126,8 @@ public class Build extends BuildBase {
File.pathSeparator + "ext/jts-1.13.jar" + File.pathSeparator + "ext/jts-1.13.jar" +
File.pathSeparator + "ext/slf4j-api-1.6.0.jar" + File.pathSeparator + "ext/slf4j-api-1.6.0.jar" +
File.pathSeparator + "ext/slf4j-nop-1.6.0.jar" + File.pathSeparator + "ext/slf4j-nop-1.6.0.jar" +
File.pathSeparator + System.getProperty("java.home") + "/../lib/tools.jar"; File.pathSeparator + System.getProperty("java.home") +
"/../lib/tools.jar";
// -XX:-UseSplitVerifier is for Java 7 compatibility // -XX:-UseSplitVerifier is for Java 7 compatibility
exec("java", args( exec("java", args(
"-Xmx128m", "-Xmx128m",
...@@ -126,7 +136,8 @@ public class Build extends BuildBase { ...@@ -126,7 +136,8 @@ public class Build extends BuildBase {
"-cp", "temp", "-cp", "temp",
"-sp", "src/main", "-sp", "src/main",
"-r", "html,txt", "-r", "html,txt",
"-ix", "-org.h2.test.*,-org.h2.dev.*,-org.h2.jaqu.*,-org.h2.mode.*,-org.h2.server.pg.*", "-ix", "-org.h2.test.*,-org.h2.dev.*," +
"-org.h2.jaqu.*,-org.h2.mode.*,-org.h2.server.pg.*",
"org.h2.test.TestAll")); "org.h2.test.TestAll"));
} }
...@@ -162,15 +173,18 @@ public class Build extends BuildBase { ...@@ -162,15 +173,18 @@ public class Build extends BuildBase {
exclude("src/main/org/h2/mvstore/db/*"); exclude("src/main/org/h2/mvstore/db/*");
StringList args = args(); StringList args = args();
if (debugInfo) { if (debugInfo) {
args = args.plus("-Xlint:unchecked", "-d", "temp", "-sourcepath", "src/main", "-classpath", classpath); args = args.plus("-Xlint:unchecked", "-d", "temp", "-sourcepath",
"src/main", "-classpath", classpath);
} else { } else {
args = args.plus("-Xlint:unchecked", "-g:none", "-d", "temp", "-sourcepath", "src/main", "-classpath", classpath); args = args.plus("-Xlint:unchecked", "-g:none", "-d", "temp",
"-sourcepath", "src/main", "-classpath", classpath);
} }
System.out.println(files); System.out.println(files);
javac(args, files); javac(args, files);
} }
private void compile(boolean debugInfo, boolean clientOnly, boolean basicResourcesOnly) { private void compile(boolean debugInfo, boolean clientOnly,
boolean basicResourcesOnly) {
switchSource(debugInfo); switchSource(debugInfo);
clean(); clean();
mkdir("temp"); mkdir("temp");
...@@ -224,7 +238,8 @@ public class Build extends BuildBase { ...@@ -224,7 +238,8 @@ public class Build extends BuildBase {
resources(clientOnly, basicResourcesOnly); resources(clientOnly, basicResourcesOnly);
} }
private static void filter(String source, String target, String old, String replacement) { private static void filter(String source, String target, String old,
String replacement) {
String text = new String(readFile(new File(source))); String text = new String(readFile(new File(source)));
text = replaceAll(text, old, replacement); text = replaceAll(text, old, replacement);
writeFile(new File(target), text.getBytes()); writeFile(new File(target), text.getBytes());
...@@ -262,17 +277,23 @@ public class Build extends BuildBase { ...@@ -262,17 +277,23 @@ public class Build extends BuildBase {
} }
private void downloadOrVerify(boolean offline) { private void downloadOrVerify(boolean offline) {
downloadOrVerify("ext/servlet-api-2.4.jar", "javax/servlet", "servlet-api", "2.4", downloadOrVerify("ext/servlet-api-2.4.jar",
"javax/servlet", "servlet-api", "2.4",
"3fc542fe8bb8164e8d3e840fe7403bc0518053c0", offline); "3fc542fe8bb8164e8d3e840fe7403bc0518053c0", offline);
downloadOrVerify("ext/lucene-core-3.0.2.jar", "org/apache/lucene", "lucene-core", "3.0.2", downloadOrVerify("ext/lucene-core-3.0.2.jar",
"org/apache/lucene", "lucene-core", "3.0.2",
"c2b48995ab855c1b9ea13867a0f976c994e0105d", offline); "c2b48995ab855c1b9ea13867a0f976c994e0105d", offline);
downloadOrVerify("ext/slf4j-api-1.6.0.jar", "org/slf4j", "slf4j-api", "1.6.0", downloadOrVerify("ext/slf4j-api-1.6.0.jar",
"org/slf4j", "slf4j-api", "1.6.0",
"b353147a7d51fcfcd818d8aa6784839783db0915", offline); "b353147a7d51fcfcd818d8aa6784839783db0915", offline);
downloadOrVerify("ext/org.osgi.core-4.2.0.jar", "org/osgi", "org.osgi.core", "4.2.0", downloadOrVerify("ext/org.osgi.core-4.2.0.jar",
"org/osgi", "org.osgi.core", "4.2.0",
"66ab449ff3aa5c4adfc82c89025cc983b422eb95", offline); "66ab449ff3aa5c4adfc82c89025cc983b422eb95", offline);
downloadOrVerify("ext/org.osgi.enterprise-4.2.0.jar", "org/osgi", "org.osgi.enterprise", "4.2.0", downloadOrVerify("ext/org.osgi.enterprise-4.2.0.jar",
"org/osgi", "org.osgi.enterprise", "4.2.0",
"8634dcb0fc62196e820ed0f1062993c377f74972", offline); "8634dcb0fc62196e820ed0f1062993c377f74972", offline);
downloadOrVerify("ext/jts-1.13.jar", "com/vividsolutions", "jts", "1.13", downloadOrVerify("ext/jts-1.13.jar",
"com/vividsolutions", "jts", "1.13",
"3ccfb9b60f04d71add996a666ceb8902904fd805", offline); "3ccfb9b60f04d71add996a666ceb8902904fd805", offline);
} }
...@@ -296,14 +317,17 @@ public class Build extends BuildBase { ...@@ -296,14 +317,17 @@ public class Build extends BuildBase {
"http://h2database.com/h2mig_pagestore_addon.jar", "http://h2database.com/h2mig_pagestore_addon.jar",
"6dfafe1b86959c3ba4f7cf03e99535e8b9719965"); "6dfafe1b86959c3ba4f7cf03e99535e8b9719965");
// for TestOldVersion // for TestOldVersion
downloadUsingMaven("ext/h2-1.2.127.jar", "com/h2database", "h2", "1.2.127", downloadUsingMaven("ext/h2-1.2.127.jar",
"com/h2database", "h2", "1.2.127",
"056e784c7cf009483366ab9cd8d21d02fe47031a"); "056e784c7cf009483366ab9cd8d21d02fe47031a");
// for TestPgServer // for TestPgServer
downloadUsingMaven("ext/postgresql-8.3-603.jdbc3.jar", "postgresql", "postgresql", "8.3-603.jdbc3", downloadUsingMaven("ext/postgresql-8.3-603.jdbc3.jar",
"postgresql", "postgresql", "8.3-603.jdbc3",
"33d531c3c53055ddcbea3d88bfa093466ffef924"); "33d531c3c53055ddcbea3d88bfa093466ffef924");
// for TestTraceSystem // for TestTraceSystem
downloadUsingMaven("ext/slf4j-nop-1.6.0.jar", "org/slf4j", "slf4j-nop", "1.6.0", downloadUsingMaven("ext/slf4j-nop-1.6.0.jar",
"org/slf4j", "slf4j-nop", "1.6.0",
"4da67bb4a6eea5dc273f99c50ad2333eadb46f86"); "4da67bb4a6eea5dc273f99c50ad2333eadb46f86");
} }
...@@ -354,7 +378,8 @@ public class Build extends BuildBase { ...@@ -354,7 +378,8 @@ public class Build extends BuildBase {
updateChecksum("../h2web/html/download.html", sha1Zip, sha1Exe); updateChecksum("../h2web/html/download.html", sha1Zip, sha1Exe);
} }
private static void updateChecksum(String fileName, String sha1Zip, String sha1Exe) { private static void updateChecksum(String fileName, String sha1Zip,
String sha1Exe) {
String checksums = new String(readFile(new File(fileName))); String checksums = new String(readFile(new File(fileName)));
checksums = replaceAll(checksums, "<!-- sha1Zip -->", checksums = replaceAll(checksums, "<!-- sha1Zip -->",
"(SHA1 checksum: " + sha1Zip + ")"); "(SHA1 checksum: " + sha1Zip + ")");
...@@ -523,8 +548,9 @@ public class Build extends BuildBase { ...@@ -523,8 +548,9 @@ public class Build extends BuildBase {
public void javadocImpl() { public void javadocImpl() {
compileTools(); compileTools();
mkdir("docs/javadocImpl2"); mkdir("docs/javadocImpl2");
javadoc("-sourcepath", "src/main" + File.pathSeparator + javadoc("-sourcepath", "src/main" +
"src/test" + File.pathSeparator + "src/tools" , File.pathSeparator + "src/test" +
File.pathSeparator + "src/tools" ,
"-noindex", "-noindex",
"-tag", "h2.resource", "-tag", "h2.resource",
"-d", "docs/javadocImpl2", "-d", "docs/javadocImpl2",
...@@ -540,9 +566,12 @@ public class Build extends BuildBase { ...@@ -540,9 +566,12 @@ public class Build extends BuildBase {
"-exclude", "org.h2.test.jaqu:org.h2.jaqu"); "-exclude", "org.h2.test.jaqu:org.h2.jaqu");
System.setProperty("h2.interfacesOnly", "false"); System.setProperty("h2.interfacesOnly", "false");
System.setProperty("h2.javadocDestDir", "docs/javadocImpl"); System.setProperty("h2.javadocDestDir", "docs/javadocImpl");
javadoc("-sourcepath", "src/main" + File.pathSeparator + "src/test" + File.pathSeparator + "src/tools", javadoc("-sourcepath", "src/main" +
"-classpath", System.getProperty("java.home") + "/../lib/tools.jar" + File.pathSeparator + "src/test" +
File.pathSeparator + "ext/slf4j-api-1.6.0.jar" + File.pathSeparator + "src/tools",
"-classpath",
System.getProperty("java.home") + "/../lib/tools.jar" +
File.pathSeparator + "ext/slf4j-api-1.6.0.jar" +
File.pathSeparator + "ext/servlet-api-2.4.jar" + File.pathSeparator + "ext/servlet-api-2.4.jar" +
File.pathSeparator + "ext/lucene-core-3.0.2.jar" + File.pathSeparator + "ext/lucene-core-3.0.2.jar" +
File.pathSeparator + "ext/org.osgi.core-4.2.0.jar" + File.pathSeparator + "ext/org.osgi.core-4.2.0.jar" +
...@@ -557,7 +586,8 @@ public class Build extends BuildBase { ...@@ -557,7 +586,8 @@ public class Build extends BuildBase {
} }
private static void manifest(String title, String mainClassName) { private static void manifest(String title, String mainClassName) {
String manifest = new String(readFile(new File("src/main/META-INF/MANIFEST.MF"))); String manifest = new String(readFile(new File(
"src/main/META-INF/MANIFEST.MF")));
manifest = replaceAll(manifest, "${title}", title); manifest = replaceAll(manifest, "${title}", title);
manifest = replaceAll(manifest, "${version}", getVersion()); manifest = replaceAll(manifest, "${version}", getVersion());
manifest = replaceAll(manifest, "${buildJdk}", getJavaSpecVersion()); manifest = replaceAll(manifest, "${buildJdk}", getJavaSpecVersion());
...@@ -580,7 +610,8 @@ public class Build extends BuildBase { ...@@ -580,7 +610,8 @@ public class Build extends BuildBase {
copy("docs", files, "src/main"); copy("docs", files, "src/main");
files = files("docs").keep("docs/org/*").keep("*.java"); files = files("docs").keep("docs/org/*").keep("*.java");
files.addAll(files("docs").keep("docs/META-INF/*")); files.addAll(files("docs").keep("docs/META-INF/*"));
String manifest = new String(readFile(new File("src/installer/source-manifest.mf"))); String manifest = new String(readFile(new File(
"src/installer/source-manifest.mf")));
manifest = replaceAll(manifest, "${version}", getVersion()); manifest = replaceAll(manifest, "${version}", getVersion());
writeFile(new File("docs/META-INF/MANIFEST.MF"), manifest.getBytes()); writeFile(new File("docs/META-INF/MANIFEST.MF"), manifest.getBytes());
jar("docs/h2-" + getVersion() + "-sources.jar", files, "docs"); jar("docs/h2-" + getVersion() + "-sources.jar", files, "docs");
...@@ -714,7 +745,8 @@ public class Build extends BuildBase { ...@@ -714,7 +745,8 @@ public class Build extends BuildBase {
*/ */
public void testSysProperties() { public void testSysProperties() {
System.out.println("environment settings:"); System.out.println("environment settings:");
for (Entry<Object, Object> e : new TreeMap<Object, Object>(System.getProperties()).entrySet()) { for (Entry<Object, Object> e : new TreeMap<Object, Object>(
System.getProperties()).entrySet()) {
System.out.println(e); System.out.println(e);
} }
} }
...@@ -732,7 +764,8 @@ public class Build extends BuildBase { ...@@ -732,7 +764,8 @@ public class Build extends BuildBase {
} }
InetAddress localhost = InetAddress.getLocalHost(); InetAddress localhost = InetAddress.getLocalHost();
System.out.println("getLocalHost:" + localhost); System.out.println("getLocalHost:" + localhost);
for (InetAddress address : InetAddress.getAllByName(localhost.getHostAddress())) { for (InetAddress address : InetAddress.getAllByName(localhost
.getHostAddress())) {
System.out.println(" " + address); System.out.println(" " + address);
} }
InetAddress address = InetAddress.getByName(localhost.getHostAddress()); InetAddress address = InetAddress.getByName(localhost.getHostAddress());
...@@ -790,8 +823,10 @@ public class Build extends BuildBase { ...@@ -790,8 +823,10 @@ public class Build extends BuildBase {
t.start(); t.start();
t.join(5000); t.join(5000);
if (!socket.isConnected()) { if (!socket.isConnected()) {
final InetSocketAddress localhostAddress = new InetSocketAddress("localhost", port); final InetSocketAddress localhostAddress = new InetSocketAddress(
System.out.println("not connected, trying localhost:" + socketAddress); "localhost", port);
System.out.println("not connected, trying localhost:"
+ socketAddress);
socket.connect(localhostAddress, 2000); socket.connect(localhostAddress, 2000);
} }
System.out.println("time: " + (System.currentTimeMillis() - start)); System.out.println("time: " + (System.currentTimeMillis() - start));
......
...@@ -130,7 +130,9 @@ public class BuildBase { ...@@ -130,7 +130,9 @@ public class BuildBase {
pattern = pattern.substring(1); pattern = pattern.substring(1);
} }
if (pattern.indexOf('*') >= 0) { if (pattern.indexOf('*') >= 0) {
throw new RuntimeException("Unsupported pattern, may only start or end with *:" + pattern); throw new RuntimeException(
"Unsupported pattern, may only start or end with *:"
+ pattern);
} }
// normalize / and \ // normalize / and \
pattern = BuildBase.replaceAll(pattern, "/", File.separator); pattern = BuildBase.replaceAll(pattern, "/", File.separator);
...@@ -211,7 +213,8 @@ public class BuildBase { ...@@ -211,7 +213,8 @@ public class BuildBase {
private void runShell() { private void runShell() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String last = "", line; String last = "", line;
System.out.println("Shell mode. Type the target, then [Enter]. Just [Enter] repeats the last target."); System.out.println("Shell mode. Type the target, then [Enter]. " +
"Just [Enter] repeats the last target.");
while (true) { while (true) {
System.out.print("build> "); System.out.print("build> ");
try { try {
...@@ -283,7 +286,8 @@ public class BuildBase { ...@@ -283,7 +286,8 @@ public class BuildBase {
sysOut.println("Targets:"); sysOut.println("Targets:");
for (Method m : methods) { for (Method m : methods) {
int mod = m.getModifiers(); int mod = m.getModifiers();
if (!Modifier.isStatic(mod) && Modifier.isPublic(mod) && m.getParameterTypes().length == 0) { if (!Modifier.isStatic(mod) && Modifier.isPublic(mod)
&& m.getParameterTypes().length == 0) {
sysOut.println(m.getName()); sysOut.println(m.getName());
} }
} }
...@@ -374,7 +378,8 @@ public class BuildBase { ...@@ -374,7 +378,8 @@ public class BuildBase {
Field field = clazz.getField(fieldName); Field field = clazz.getField(fieldName);
return field.get(null).toString(); return field.get(null).toString();
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Can not read field " + className + "." + fieldName, e); throw new RuntimeException("Can not read field " + className + "."
+ fieldName, e);
} }
} }
...@@ -391,7 +396,8 @@ public class BuildBase { ...@@ -391,7 +396,8 @@ public class BuildBase {
Method method = clazz.getMethod(methodName); Method method = clazz.getMethod(methodName);
return method.invoke(null).toString(); return method.invoke(null).toString();
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Can not read value " + className + "." + methodName + "()", e); throw new RuntimeException("Can not read value " + className + "."
+ methodName + "()", e);
} }
} }
...@@ -533,13 +539,15 @@ public class BuildBase { ...@@ -533,13 +539,15 @@ public class BuildBase {
* @param version the Maven version id * @param version the Maven version id
* @param sha1Checksum the SHA-1 checksum or null * @param sha1Checksum the SHA-1 checksum or null
*/ */
protected void downloadUsingMaven(String target, String group, String artifact, String version, String sha1Checksum) { protected void downloadUsingMaven(String target, String group,
String artifact, String version, String sha1Checksum) {
String repoDir = "http://repo1.maven.org/maven2"; String repoDir = "http://repo1.maven.org/maven2";
File targetFile = new File(target); File targetFile = new File(target);
if (targetFile.exists()) { if (targetFile.exists()) {
return; return;
} }
String repoFile = group + "/" + artifact + "/" + version + "/" + artifact + "-" + version + ".jar"; String repoFile = group + "/" + artifact + "/" + version + "/"
+ artifact + "-" + version + ".jar";
mkdirs(targetFile.getAbsoluteFile().getParentFile()); mkdirs(targetFile.getAbsoluteFile().getParentFile());
String localMavenDir = getLocalMavenDir(); String localMavenDir = getLocalMavenDir();
if (new File(localMavenDir).exists()) { if (new File(localMavenDir).exists()) {
...@@ -758,7 +766,8 @@ public class BuildBase { ...@@ -758,7 +766,8 @@ public class BuildBase {
* @param storeOnly if the files should not be compressed * @param storeOnly if the files should not be compressed
* @param sortBySuffix if the file should be sorted by the file suffix * @param sortBySuffix if the file should be sorted by the file suffix
*/ */
protected void zip(String destFile, FileList files, String basePath, boolean storeOnly, boolean sortBySuffix) { protected void zip(String destFile, FileList files, String basePath,
boolean storeOnly, boolean sortBySuffix) {
long kb = zipOrJar(destFile, files, basePath, storeOnly, sortBySuffix, false); long kb = zipOrJar(destFile, files, basePath, storeOnly, sortBySuffix, false);
println("Zip " + destFile + " (" + kb + " KB)"); println("Zip " + destFile + " (" + kb + " KB)");
} }
...@@ -785,7 +794,9 @@ public class BuildBase { ...@@ -785,7 +794,9 @@ public class BuildBase {
basePath = new File(basePath).getPath(); basePath = new File(basePath).getPath();
try { try {
if (new File(destFile).isDirectory()) { if (new File(destFile).isDirectory()) {
throw new IOException("Can't create the file as a directory with this name already exists: " + destFile); throw new IOException(
"Can't create the file as a directory with this name already exists: "
+ destFile);
} }
OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile)); OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile));
ZipOutputStream zipOut; ZipOutputStream zipOut;
...@@ -897,7 +908,8 @@ public class BuildBase { ...@@ -897,7 +908,8 @@ public class BuildBase {
File f = new File(dir); File f = new File(dir);
if (f.exists()) { if (f.exists()) {
if (f.isFile()) { if (f.isFile()) {
throw new RuntimeException("Can not create directory " + dir + " because a file with this name exists"); throw new RuntimeException("Can not create directory " + dir
+ " because a file with this name exists");
} }
} else { } else {
mkdirs(f); mkdirs(f);
......
...@@ -18,7 +18,7 @@ import java.io.RandomAccessFile; ...@@ -18,7 +18,7 @@ import java.io.RandomAccessFile;
public class CheckJavadoc { public class CheckJavadoc {
private static final int MAX_COMMENT_LINE_SIZE = 80; private static final int MAX_COMMENT_LINE_SIZE = 80;
private static final int MAX_SOURCE_LINE_SIZE = 120; private static final int MAX_SOURCE_LINE_SIZE = 80;
private int errorCount; private int errorCount;
/** /**
...@@ -55,7 +55,9 @@ public class CheckJavadoc { ...@@ -55,7 +55,9 @@ public class CheckJavadoc {
} }
} }
if (foundJava && !foundPackageHtml) { if (foundJava && !foundPackageHtml) {
System.out.println("No package.html file, but a Java file found at: " + file.getAbsolutePath()); System.out.println(
"No package.html file, but a Java file found at: "
+ file.getAbsolutePath());
errorCount++; errorCount++;
} }
} else { } else {
...@@ -112,6 +114,7 @@ public class CheckJavadoc { ...@@ -112,6 +114,7 @@ public class CheckJavadoc {
} else if (!inComment && line.length() > MAX_SOURCE_LINE_SIZE) { } else if (!inComment && line.length() > MAX_SOURCE_LINE_SIZE) {
System.out.println("Long line: " + file.getAbsolutePath() System.out.println("Long line: " + file.getAbsolutePath()
+ " (" + file.getName() + ":" + lineNumber + ")"); + " (" + file.getName() + ":" + lineNumber + ")");
errorCount++;
} }
lineNumber++; lineNumber++;
pos = next + 1; pos = next + 1;
......
...@@ -19,14 +19,18 @@ import java.util.Arrays; ...@@ -19,14 +19,18 @@ import java.util.Arrays;
public class CheckTextFiles { public class CheckTextFiles {
// must contain "+" otherwise this here counts as well // must contain "+" otherwise this here counts as well
private static final String COPYRIGHT = "Copyright 2004-2013 " + "H2 Group."; private static final String COPYRIGHT = "Copyright 2004-2013 " +
private static final String LICENSE = "Multiple-Licensed " + "under the H2 License"; "H2 Group.";
private static final String LICENSE = "Multiple-Licensed " +
"under the H2 License";
private static final String[] SUFFIX_CHECK = { "html", "jsp", "js", "css", "bat", "nsi", private static final String[] SUFFIX_CHECK = { "html", "jsp", "js", "css",
"java", "txt", "properties", "sql", "xml", "csv", "Driver", "prefs" }; "bat", "nsi", "java", "txt", "properties", "sql", "xml", "csv",
private static final String[] SUFFIX_IGNORE = { "gif", "png", "odg", "ico", "sxd", "Driver", "prefs" };
"layout", "res", "win", "jar", "task", "svg", "MF", "mf", "sh", "DS_Store", "prop" }; private static final String[] SUFFIX_IGNORE = { "gif", "png", "odg", "ico",
private static final String[] SUFFIX_CRLF = { "bat" }; "sxd", "layout", "res", "win", "jar", "task", "svg", "MF", "mf",
"sh", "DS_Store", "prop" };
private static final String[] SUFFIX_CRLF = { "bat" };
private static final boolean ALLOW_TAB = false; private static final boolean ALLOW_TAB = false;
private static final boolean ALLOW_CR = true; private static final boolean ALLOW_CR = true;
...@@ -86,7 +90,9 @@ public class CheckTextFiles { ...@@ -86,7 +90,9 @@ public class CheckTextFiles {
// check = false; // check = false;
// ignore = true; // ignore = true;
// } // }
if (name.endsWith(".utf8.txt") || (name.startsWith("_docs_") && name.endsWith(".properties"))) { if (name.endsWith(".utf8.txt") ||
(name.startsWith("_docs_") &&
name.endsWith(".properties"))) {
check = false; check = false;
ignore = true; ignore = true;
} }
...@@ -103,7 +109,8 @@ public class CheckTextFiles { ...@@ -103,7 +109,8 @@ public class CheckTextFiles {
} }
} }
if (ignore == check) { if (ignore == check) {
throw new RuntimeException("Unknown suffix: " + suffix + " for file: " + file.getAbsolutePath()); throw new RuntimeException("Unknown suffix: " + suffix
+ " for file: " + file.getAbsolutePath());
} }
useCRLF = false; useCRLF = false;
for (String s : SUFFIX_CRLF) { for (String s : SUFFIX_CRLF) {
...@@ -128,7 +135,8 @@ public class CheckTextFiles { ...@@ -128,7 +135,8 @@ public class CheckTextFiles {
* @param fix automatically fix newline characters and trailing spaces * @param fix automatically fix newline characters and trailing spaces
* @param checkLicense check the license and copyright * @param checkLicense check the license and copyright
*/ */
public void checkOrFixFile(File file, boolean fix, boolean checkLicense) throws Exception { public void checkOrFixFile(File file, boolean fix, boolean checkLicense)
throws Exception {
RandomAccessFile in = new RandomAccessFile(file, "r"); RandomAccessFile in = new RandomAccessFile(file, "r");
byte[] data = new byte[(int) file.length()]; byte[] data = new byte[(int) file.length()];
ByteArrayOutputStream out = fix ? new ByteArrayOutputStream() : null; ByteArrayOutputStream out = fix ? new ByteArrayOutputStream() : null;
...@@ -161,7 +169,8 @@ public class CheckTextFiles { ...@@ -161,7 +169,8 @@ public class CheckTextFiles {
char ch = (char) (data[i] & 0xff); char ch = (char) (data[i] & 0xff);
boolean isWhitespace = Character.isWhitespace(ch); boolean isWhitespace = Character.isWhitespace(ch);
if (ch > 127) { if (ch > 127) {
fail(file, "contains character " + (int) ch + " at " + new String(data, i - 10, 20), line); fail(file, "contains character " + (int) ch + " at "
+ new String(data, i - 10, 20), line);
return; return;
} else if (ch < 32) { } else if (ch < 32) {
if (ch == '\n') { if (ch == '\n') {
...@@ -277,7 +286,8 @@ public class CheckTextFiles { ...@@ -277,7 +286,8 @@ public class CheckTextFiles {
name = name.substring(idx); name = name.substring(idx);
} }
} }
System.out.println("FAIL at " + name + " " + error + " " + file.getAbsolutePath()); System.out.println("FAIL at " + name + " " + error + " "
+ file.getAbsolutePath());
hasError = true; hasError = true;
if (failOnError) { if (failOnError) {
throw new RuntimeException("FAIL"); throw new RuntimeException("FAIL");
......
...@@ -143,7 +143,8 @@ public class SwitchSource { ...@@ -143,7 +143,8 @@ public class SwitchSource {
f.renameTo(fileBack); f.renameTo(fileBack);
File fileCopy = new File(name); File fileCopy = new File(name);
if (!fileNew.renameTo(fileCopy)) { if (!fileNew.renameTo(fileCopy)) {
throw new IOException("Could not rename " + fileNew.getAbsolutePath() + " to " + name); throw new IOException("Could not rename "
+ fileNew.getAbsolutePath() + " to " + name);
} }
if (!fileBack.delete()) { if (!fileBack.delete()) {
throw new IOException("Could not delete " + fileBack.getAbsolutePath()); throw new IOException("Could not delete " + fileBack.getAbsolutePath());
......
...@@ -39,7 +39,8 @@ public class BnfRailroad implements BnfVisitor { ...@@ -39,7 +39,8 @@ public class BnfRailroad implements BnfVisitor {
StringBuilder buff = new StringBuilder(); StringBuilder buff = new StringBuilder();
for (String s : syntaxList) { for (String s : syntaxList) {
bnf.visit(this, s); bnf.visit(this, s);
html = StringUtils.replaceAll(html, "</code></td><td class=\"d\"><code class=\"c\">", " "); html = StringUtils.replaceAll(html, "</code></td>" +
"<td class=\"d\"><code class=\"c\">", " ");
if (buff.length() > 0) { if (buff.length() > 0) {
buff.append("<br />"); buff.append("<br />");
} }
...@@ -137,7 +138,8 @@ public class BnfRailroad implements BnfVisitor { ...@@ -137,7 +138,8 @@ public class BnfRailroad implements BnfVisitor {
for (Rule r : list) { for (Rule r : list) {
String a = i == 0 ? "t" : i == list.size() - 1 ? "l" : "k"; String a = i == 0 ? "t" : i == list.size() - 1 ? "l" : "k";
i++; i++;
buff.append("<tr class=\"railroad\"><td class=\"" + a + "s\"></td><td class=\"d\">"); buff.append("<tr class=\"railroad\"><td class=\"" +
a + "s\"></td><td class=\"d\">");
r.accept(this); r.accept(this);
buff.append(html); buff.append(html);
buff.append("</td><td class=\"" + a + "e\"></td></tr>"); buff.append("</td><td class=\"" + a + "e\"></td></tr>");
...@@ -161,8 +163,10 @@ public class BnfRailroad implements BnfVisitor { ...@@ -161,8 +163,10 @@ public class BnfRailroad implements BnfVisitor {
public void visitRuleOptional(Rule rule) { public void visitRuleOptional(Rule rule) {
StringBuilder buff = new StringBuilder(); StringBuilder buff = new StringBuilder();
buff.append("<table class=\"railroad\">"); buff.append("<table class=\"railroad\">");
buff.append("<tr class=\"railroad\"><td class=\"ts\"></td><td class=\"d\">&nbsp;</td><td class=\"te\"></td></tr>"); buff.append("<tr class=\"railroad\"><td class=\"ts\"></td>" +
buff.append("<tr class=\"railroad\"><td class=\"ls\"></td><td class=\"d\">"); "<td class=\"d\">&nbsp;</td><td class=\"te\"></td></tr>");
buff.append("<tr class=\"railroad\">" +
"<td class=\"ls\"></td><td class=\"d\">");
rule.accept(this); rule.accept(this);
buff.append(html); buff.append(html);
buff.append("</td><td class=\"le\"></td></tr></table>"); buff.append("</td><td class=\"le\"></td></tr></table>");
......
...@@ -43,7 +43,8 @@ public class FileConverter { ...@@ -43,7 +43,8 @@ public class FileConverter {
} }
} }
String languageCode = Locale.KOREA.getLanguage(); String languageCode = Locale.KOREA.getLanguage();
String language = new Locale(languageCode).getDisplayLanguage(new Locale(languageCode)); String language = new Locale(languageCode)
.getDisplayLanguage(new Locale(languageCode));
System.out.println(language); System.out.println(language);
System.out.println(StringUtils.javaEncode(language)); System.out.println(StringUtils.javaEncode(language));
convert(); convert();
......
...@@ -36,7 +36,8 @@ public class GenerateDoc { ...@@ -36,7 +36,8 @@ public class GenerateDoc {
private String inDir = "src/docsrc/html"; private String inDir = "src/docsrc/html";
private String outDir = "docs/html"; private String outDir = "docs/html";
private Connection conn; private Connection conn;
private final HashMap<String, Object> session = new HashMap<String, Object>(); private final HashMap<String, Object> session =
new HashMap<String, Object>();
private Bnf bnf; private Bnf bnf;
/** /**
...@@ -68,22 +69,38 @@ public class GenerateDoc { ...@@ -68,22 +69,38 @@ public class GenerateDoc {
session.put("stableVersion", Constants.getVersionStable()); session.put("stableVersion", Constants.getVersionStable());
session.put("stableVersionDate", Constants.BUILD_DATE_STABLE); session.put("stableVersionDate", Constants.BUILD_DATE_STABLE);
// String help = "SELECT * FROM INFORMATION_SCHEMA.HELP WHERE SECTION"; // String help = "SELECT * FROM INFORMATION_SCHEMA.HELP WHERE SECTION";
String help = "SELECT ROWNUM ID, * FROM CSVREAD('" + IN_HELP + "', NULL, 'lineComment=#') WHERE SECTION "; String help = "SELECT ROWNUM ID, * FROM CSVREAD('" +
map("commands", help + "LIKE 'Commands%' ORDER BY ID", true); IN_HELP + "', NULL, 'lineComment=#') WHERE SECTION ";
map("commandsDML", help + "= 'Commands (DML)' ORDER BY ID", false); map("commands",
map("commandsDDL", help + "= 'Commands (DDL)' ORDER BY ID", false); help + "LIKE 'Commands%' ORDER BY ID", true);
map("commandsOther", help + "= 'Commands (Other)' ORDER BY ID", false); map("commandsDML",
map("otherGrammar", help + "= 'Other Grammar' ORDER BY ID", true); help + "= 'Commands (DML)' ORDER BY ID", false);
map("functionsAggregate", help + "= 'Functions (Aggregate)' ORDER BY ID", false); map("commandsDDL",
map("functionsNumeric", help + "= 'Functions (Numeric)' ORDER BY ID", false); help + "= 'Commands (DDL)' ORDER BY ID", false);
map("functionsString", help + "= 'Functions (String)' ORDER BY ID", false); map("commandsOther",
map("functionsTimeDate", help + "= 'Functions (Time and Date)' ORDER BY ID", false); help + "= 'Commands (Other)' ORDER BY ID", false);
map("functionsSystem", help + "= 'Functions (System)' ORDER BY ID", false); map("otherGrammar",
map("functionsAll", help + "LIKE 'Functions%' ORDER BY SECTION, ID", true); help + "= 'Other Grammar' ORDER BY ID", true);
map("dataTypes", help + "LIKE 'Data Types%' ORDER BY SECTION, ID", true); map("functionsAggregate",
map("informationSchema", "SELECT TABLE_NAME TOPIC, GROUP_CONCAT(COLUMN_NAME " help + "= 'Functions (Aggregate)' ORDER BY ID", false);
+ "ORDER BY ORDINAL_POSITION SEPARATOR ', ') SYNTAX FROM INFORMATION_SCHEMA.COLUMNS " map("functionsNumeric",
+ "WHERE TABLE_SCHEMA='INFORMATION_SCHEMA' GROUP BY TABLE_NAME ORDER BY TABLE_NAME", false); help + "= 'Functions (Numeric)' ORDER BY ID", false);
map("functionsString",
help + "= 'Functions (String)' ORDER BY ID", false);
map("functionsTimeDate",
help + "= 'Functions (Time and Date)' ORDER BY ID", false);
map("functionsSystem",
help + "= 'Functions (System)' ORDER BY ID", false);
map("functionsAll",
help + "LIKE 'Functions%' ORDER BY SECTION, ID", true);
map("dataTypes",
help + "LIKE 'Data Types%' ORDER BY SECTION, ID", true);
map("informationSchema", "SELECT TABLE_NAME TOPIC, " +
"GROUP_CONCAT(COLUMN_NAME " +
"ORDER BY ORDINAL_POSITION SEPARATOR ', ') SYNTAX " +
"FROM INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_SCHEMA='INFORMATION_SCHEMA' " +
"GROUP BY TABLE_NAME ORDER BY TABLE_NAME", false);
processAll(""); processAll("");
conn.close(); conn.close();
} }
...@@ -118,13 +135,15 @@ public class GenerateDoc { ...@@ -118,13 +135,15 @@ public class GenerateDoc {
out.close(); out.close();
} }
private void map(String key, String sql, boolean railroads) throws Exception { private void map(String key, String sql, boolean railroads)
throws Exception {
ResultSet rs = null; ResultSet rs = null;
Statement stat = null; Statement stat = null;
try { try {
stat = conn.createStatement(); stat = conn.createStatement();
rs = stat.executeQuery(sql); rs = stat.executeQuery(sql);
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); ArrayList<HashMap<String, String>> list =
new ArrayList<HashMap<String, String>>();
while (rs.next()) { while (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>(); HashMap<String, String> map = new HashMap<String, String>();
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
...@@ -149,8 +168,10 @@ public class GenerateDoc { ...@@ -149,8 +168,10 @@ public class GenerateDoc {
String text = map.get("text"); String text = map.get("text");
if (text != null) { if (text != null) {
// text is enclosed in <p> .. </p> so this works. // text is enclosed in <p> .. </p> so this works.
text = StringUtils.replaceAll(text, "<br /><br />", "</p><p>"); text = StringUtils.replaceAll(text,
text = StringUtils.replaceAll(text, "<br />", " "); "<br /><br />", "</p><p>");
text = StringUtils.replaceAll(text,
"<br />", " ");
text = addCode(text); text = addCode(text);
map.put("text", text); map.put("text", text);
} }
...@@ -167,7 +188,8 @@ public class GenerateDoc { ...@@ -167,7 +188,8 @@ public class GenerateDoc {
int div = 3; int div = 3;
int part = (list.size() + div - 1) / div; int part = (list.size() + div - 1) / div;
for (int i = 0, start = 0; i < div; i++, start += part) { for (int i = 0, start = 0; i < div; i++, start += part) {
List<HashMap<String, String>> listThird = list.subList(start, Math.min(start + part, list.size())); List<HashMap<String, String>> listThird = list.subList(start,
Math.min(start + part, list.size()));
session.put(key + "-" + i, listThird); session.put(key + "-" + i, listThird);
} }
} finally { } finally {
......
...@@ -52,7 +52,8 @@ public class GenerateHelp { ...@@ -52,7 +52,8 @@ public class GenerateHelp {
rs2.addRow(row); rs2.addRow(row);
} }
BufferedWriter writer = new BufferedWriter(new FileWriter(out)); BufferedWriter writer = new BufferedWriter(new FileWriter(out));
writer.write("# Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,\n" + writer.write("# Copyright 2004-2013 H2 Group. " +
"Multiple-Licensed under the H2 License,\n" +
"# Version 1.0, and under the Eclipse Public License, Version 1.0\n" + "# Version 1.0, and under the Eclipse Public License, Version 1.0\n" +
"# (http://h2database.com/html/license.html).\n" + "# (http://h2database.com/html/license.html).\n" +
"# Initial Developer: H2 Group)\n"); "# Initial Developer: H2 Group)\n");
......
...@@ -30,9 +30,10 @@ public class MergeDocs { ...@@ -30,9 +30,10 @@ public class MergeDocs {
*/ */
public static void main(String... args) throws Exception { public static void main(String... args) throws Exception {
// the order of pages is important here // the order of pages is important here
String[] pages = { "quickstart.html", "installation.html", "tutorial.html", "features.html", String[] pages = { "quickstart.html", "installation.html",
"performance.html", "advanced.html", "grammar.html", "functions.html", "datatypes.html", "build.html", "tutorial.html", "features.html", "performance.html",
"history.html", "faq.html" }; "advanced.html", "grammar.html", "functions.html",
"datatypes.html", "build.html", "history.html", "faq.html" };
StringBuilder buff = new StringBuilder(); StringBuilder buff = new StringBuilder();
for (String fileName : pages) { for (String fileName : pages) {
String text = getContent(fileName); String text = getContent(fileName);
...@@ -46,9 +47,11 @@ public class MergeDocs { ...@@ -46,9 +47,11 @@ public class MergeDocs {
String finalText = buff.toString(); String finalText = buff.toString();
File output = new File(BASE_DIR, "onePage.html"); File output = new File(BASE_DIR, "onePage.html");
PrintWriter writer = new PrintWriter(new FileWriter(output)); PrintWriter writer = new PrintWriter(new FileWriter(output));
writer.println("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /><title>"); writer.println("<html><head><meta http-equiv=\"Content-Type\" " +
"content=\"text/html;charset=utf-8\" /><title>");
writer.println("H2 Documentation"); writer.println("H2 Documentation");
writer.println("</title><link rel=\"stylesheet\" type=\"text/css\" href=\"stylesheetPdf.css\" /></head><body>"); writer.println("</title><link rel=\"stylesheet\" type=\"text/css\" " +
"href=\"stylesheetPdf.css\" /></head><body>");
writer.println("<h1>H2 Database Engine</h1>"); writer.println("<h1>H2 Database Engine</h1>");
writer.println("<p>Version " + Constants.getFullVersion() + "</p>"); writer.println("<p>Version " + Constants.getFullVersion() + "</p>");
writer.println(finalText); writer.println(finalText);
...@@ -57,10 +60,18 @@ public class MergeDocs { ...@@ -57,10 +60,18 @@ public class MergeDocs {
} }
private static String disableRailroads(String text) { private static String disableRailroads(String text) {
text = StringUtils.replaceAll(text, "<!-- railroad-start -->", "<!-- railroad-start "); text = StringUtils.replaceAll(text,
text = StringUtils.replaceAll(text, "<!-- railroad-end -->", " railroad-end -->"); "<!-- railroad-start -->",
text = StringUtils.replaceAll(text, "<!-- syntax-start", "<!-- syntax-start -->"); "<!-- railroad-start ");
text = StringUtils.replaceAll(text, "syntax-end -->", "<!-- syntax-end -->"); text = StringUtils.replaceAll(text,
"<!-- railroad-end -->",
" railroad-end -->");
text = StringUtils.replaceAll(text,
"<!-- syntax-start",
"<!-- syntax-start -->");
text = StringUtils.replaceAll(text,
"syntax-end -->",
"<!-- syntax-end -->");
return text; return text;
} }
...@@ -69,7 +80,8 @@ public class MergeDocs { ...@@ -69,7 +80,8 @@ public class MergeDocs {
// String end = "</body>"; // String end = "</body>";
String start = "<!-- } -->"; String start = "<!-- } -->";
String end = "<!-- [close] { --></div></td></tr></table><!-- } --><!-- analytics --></body></html>"; String end = "<!-- [close] { --></div></td></tr></table>" +
"<!-- } --><!-- analytics --></body></html>";
int idx = text.indexOf(end); int idx = text.indexOf(end);
if (idx < 0) { if (idx < 0) {
......
...@@ -48,7 +48,8 @@ public class RailroadImages { ...@@ -48,7 +48,8 @@ public class RailroadImages {
BufferedImage img; BufferedImage img;
Graphics2D g; Graphics2D g;
img = new BufferedImage(SIZE * 64, SIZE * LINE_REPEAT, BufferedImage.TYPE_INT_ARGB); img = new BufferedImage(SIZE * 64, SIZE * LINE_REPEAT,
BufferedImage.TYPE_INT_ARGB);
g = img.createGraphics(); g = img.createGraphics();
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
setStroke(g, i); setStroke(g, i);
...@@ -107,7 +108,8 @@ public class RailroadImages { ...@@ -107,7 +108,8 @@ public class RailroadImages {
int h = img.getHeight(); int h = img.getHeight();
BufferedImage smaller = new BufferedImage(w / DIV, h / DIV, img.getType()); BufferedImage smaller = new BufferedImage(w / DIV, h / DIV, img.getType());
Graphics2D g = smaller.createGraphics(); Graphics2D g = smaller.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, w / DIV, h / DIV, 0, 0, w, h, null); g.drawImage(img, 0, 0, w / DIV, h / DIV, 0, 0, w, h, null);
g.dispose(); g.dispose();
try { try {
......
...@@ -25,13 +25,17 @@ import org.h2.util.Utils; ...@@ -25,13 +25,17 @@ import org.h2.util.Utils;
*/ */
public class SpellChecker { public class SpellChecker {
private static final String[] SUFFIX = { "html", "java", "sql", "txt", "xml", "jsp", "css", "bat", private static final String[] SUFFIX = { "html", "java", "sql", "txt",
"csv", "xml", "js", "Driver", "properties", "task", "MF", "mf", "sh", "" }; "xml", "jsp", "css", "bat", "csv", "xml", "js", "Driver",
private static final String[] IGNORE = { "dev", "nsi", "gif", "png", "odg", "ico", "sxd", "zip", "properties", "task", "MF", "mf", "sh", "" };
"bz2", "rc", "layout", "res", "dll", "jar", "svg", "prefs", "prop", "iml" }; private static final String[] IGNORE = { "dev", "nsi", "gif", "png", "odg",
private static final String DELIMITERS = " \n.();-\"=,*/{}_<>+\r:'@[]&\\!#|?$^%~`\t"; "ico", "sxd", "zip", "bz2", "rc", "layout", "res", "dll", "jar",
"svg", "prefs", "prop", "iml" };
private static final String DELIMITERS =
" \n.();-\"=,*/{}_<>+\r:'@[]&\\!#|?$^%~`\t";
private static final String PREFIX_IGNORE = "abc"; private static final String PREFIX_IGNORE = "abc";
private static final String[] IGNORE_FILES = {"mainWeb.html", "pg_catalog.sql"}; private static final String[] IGNORE_FILES = { "mainWeb.html",
"pg_catalog.sql" };
// These are public so we can set them during development testing // These are public so we can set them during development testing
...@@ -45,9 +49,12 @@ public class SpellChecker { ...@@ -45,9 +49,12 @@ public class SpellChecker {
*/ */
public boolean printDictionary; public boolean printDictionary;
private final HashSet<String> dictionary = new HashSet<String>(); private final HashSet<String> dictionary =
private final HashSet<String> used = new HashSet<String>(); new HashSet<String>();
private final HashMap<String, Integer> unknown = new HashMap<String, Integer>(); private final HashSet<String> used =
new HashSet<String>();
private final HashMap<String, Integer> unknown =
new HashMap<String, Integer>();
private boolean addToDictionary; private boolean addToDictionary;
private int errorCount; private int errorCount;
private int contextCount; private int contextCount;
...@@ -140,7 +147,8 @@ public class SpellChecker { ...@@ -140,7 +147,8 @@ public class SpellChecker {
} }
} }
if (!ok) { if (!ok) {
throw new IOException("Unsupported suffix: " + suffix + " for file: " + fileName); throw new IOException("Unsupported suffix: " +
suffix + " for file: " + fileName);
} }
String text = new String(BuildBase.readFile(file)); String text = new String(BuildBase.readFile(file));
if (fileName.endsWith("dictionary.txt")) { if (fileName.endsWith("dictionary.txt")) {
...@@ -198,7 +206,8 @@ public class SpellChecker { ...@@ -198,7 +206,8 @@ public class SpellChecker {
pos += "http://".length(); pos += "http://".length();
while (true) { while (true) {
char c = text.charAt(pos); char c = text.charAt(pos);
if (!Character.isJavaIdentifierPart(c) && ".#/?&=%+_-:".indexOf(c) < 0) { if (!Character.isJavaIdentifierPart(c) &&
".#/?&=%+_-:".indexOf(c) < 0) {
break; break;
} }
pos++; pos++;
...@@ -219,11 +228,13 @@ public class SpellChecker { ...@@ -219,11 +228,13 @@ public class SpellChecker {
for (int i = 1; i < token.length(); i++) { for (int i = 1; i < token.length(); i++) {
char charLeft = token.charAt(i - 1); char charLeft = token.charAt(i - 1);
char charRight = token.charAt(i); char charRight = token.charAt(i);
if (Character.isLowerCase(charLeft) && Character.isUpperCase(charRight)) { if (Character.isLowerCase(charLeft)
&& Character.isUpperCase(charRight)) {
scanToken(notFound, token.substring(0, i)); scanToken(notFound, token.substring(0, i));
token = token.substring(i); token = token.substring(i);
i = 1; i = 1;
} else if (Character.isUpperCase(charLeft) && Character.isLowerCase(charRight)) { } else if (Character.isUpperCase(charLeft)
&& Character.isLowerCase(charRight)) {
scanToken(notFound, token.substring(0, i - 1)); scanToken(notFound, token.substring(0, i - 1));
token = token.substring(i - 1); token = token.substring(i - 1);
i = 1; i = 1;
......
...@@ -53,7 +53,8 @@ public class UploadBuild { ...@@ -53,7 +53,8 @@ public class UploadBuild {
boolean coverage = new File("coverage/index.html").exists(); boolean coverage = new File("coverage/index.html").exists();
boolean coverageFailed; boolean coverageFailed;
if (coverage) { if (coverage) {
byte[] data = IOUtils.readBytesAndClose(new FileInputStream("coverage/index.html"), -1); byte[] data = IOUtils.readBytesAndClose(
new FileInputStream("coverage/index.html"), -1);
String index = new String(data, "ISO-8859-1"); String index = new String(data, "ISO-8859-1");
coverageFailed = index.indexOf("CLASS=\"h\"") >= 0; coverageFailed = index.indexOf("CLASS=\"h\"") >= 0;
while (true) { while (true) {
...@@ -87,7 +88,8 @@ public class UploadBuild { ...@@ -87,7 +88,8 @@ public class UploadBuild {
String testOutput; String testOutput;
boolean error; boolean error;
if (new File("docs/html/testOutput.html").exists()) { if (new File("docs/html/testOutput.html").exists()) {
testOutput = IOUtils.readStringAndClose(new FileReader("docs/html/testOutput.html"), -1); testOutput = IOUtils.readStringAndClose(
new FileReader("docs/html/testOutput.html"), -1);
error = testOutput.indexOf(OutputCatcher.START_ERROR) >= 0; error = testOutput.indexOf(OutputCatcher.START_ERROR) >= 0;
} else if (new File("log.txt").exists()) { } else if (new File("log.txt").exists()) {
testOutput = IOUtils.readStringAndClose(new FileReader("log.txt"), -1); testOutput = IOUtils.readStringAndClose(new FileReader("log.txt"), -1);
...@@ -103,7 +105,8 @@ public class UploadBuild { ...@@ -103,7 +105,8 @@ public class UploadBuild {
if (ftp.exists("/httpdocs/automated", "history.sql")) { if (ftp.exists("/httpdocs/automated", "history.sql")) {
buildSql = new String(ftp.retrieve("/httpdocs/automated/history.sql")); buildSql = new String(ftp.retrieve("/httpdocs/automated/history.sql"));
} else { } else {
buildSql = "create table item(id identity, title varchar, issued timestamp, desc varchar);\n"; buildSql = "create table item(id identity, title varchar, " +
"issued timestamp, desc varchar);\n";
} }
String ts = new java.sql.Timestamp(System.currentTimeMillis()).toString(); String ts = new java.sql.Timestamp(System.currentTimeMillis()).toString();
String now = ts.substring(0, 16); String now = ts.substring(0, 16);
...@@ -111,16 +114,22 @@ public class UploadBuild { ...@@ -111,16 +114,22 @@ public class UploadBuild {
if (idx >= 0) { if (idx >= 0) {
int end = testOutput.indexOf("<br />", idx); int end = testOutput.indexOf("<br />", idx);
if (end >= 0) { if (end >= 0) {
String result = testOutput.substring(idx + "Statements per second: ".length(), end); String result = testOutput.substring(idx +
"Statements per second: ".length(), end);
now += " " + result + " op/s"; now += " " + result + " op/s";
} }
} }
String sql = "insert into item(title, issued, desc) values('Build " + now + String sql = "insert into item(title, issued, desc) values('Build " +
now +
(error ? " FAILED" : "") + (error ? " FAILED" : "") +
(coverageFailed ? " COVERAGE" : "") + (coverageFailed ? " COVERAGE" : "") +
"', '" + ts + "', '<a href=\"http://www.h2database.com/html/testOutput.html\">Output</a>" + "', '" + ts +
" - <a href=\"http://www.h2database.com/coverage/overview.html\">Coverage</a>" + "', '<a href=\"http://www.h2database.com/" +
" - <a href=\"http://www.h2database.com/automated/h2-latest.jar\">Jar</a>');\n"; "html/testOutput.html\">Output</a>" +
" - <a href=\"http://www.h2database.com/" +
"coverage/overview.html\">Coverage</a>" +
" - <a href=\"http://www.h2database.com/" +
"automated/h2-latest.jar\">Jar</a>');\n";
buildSql += sql; buildSql += sql;
Connection conn; Connection conn;
try { try {
...@@ -131,7 +140,8 @@ public class UploadBuild { ...@@ -131,7 +140,8 @@ public class UploadBuild {
conn = DriverManager.getConnection("jdbc:h2v1_1:mem:"); conn = DriverManager.getConnection("jdbc:h2v1_1:mem:");
} }
conn.createStatement().execute(buildSql); conn.createStatement().execute(buildSql);
String newsfeed = IOUtils.readStringAndClose(new FileReader("src/tools/org/h2/build/doc/buildNewsfeed.sql"), -1); String newsfeed = IOUtils.readStringAndClose(
new FileReader("src/tools/org/h2/build/doc/buildNewsfeed.sql"), -1);
ScriptReader r = new ScriptReader(new StringReader(newsfeed)); ScriptReader r = new ScriptReader(new StringReader(newsfeed));
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
ResultSet rs = null; ResultSet rs = null;
...@@ -147,22 +157,29 @@ public class UploadBuild { ...@@ -147,22 +157,29 @@ public class UploadBuild {
rs.next(); rs.next();
String content = rs.getString("content"); String content = rs.getString("content");
conn.close(); conn.close();
ftp.store("/httpdocs/automated/history.sql", new ByteArrayInputStream(buildSql.getBytes())); ftp.store("/httpdocs/automated/history.sql",
ftp.store("/httpdocs/automated/news.xml", new ByteArrayInputStream(content.getBytes())); new ByteArrayInputStream(buildSql.getBytes()));
ftp.store("/httpdocs/html/testOutput.html", new ByteArrayInputStream(testOutput.getBytes())); ftp.store("/httpdocs/automated/news.xml",
new ByteArrayInputStream(content.getBytes()));
ftp.store("/httpdocs/html/testOutput.html",
new ByteArrayInputStream(testOutput.getBytes()));
String jarFileName = "bin/h2-" + Constants.getVersion() + ".jar"; String jarFileName = "bin/h2-" + Constants.getVersion() + ".jar";
if (FileUtils.exists(jarFileName)) { if (FileUtils.exists(jarFileName)) {
ftp.store("/httpdocs/automated/h2-latest.jar", new FileInputStream(jarFileName)); ftp.store("/httpdocs/automated/h2-latest.jar",
new FileInputStream(jarFileName));
} }
if (coverage) { if (coverage) {
ftp.store("/httpdocs/coverage/overview.html", new FileInputStream("coverage/overview.html")); ftp.store("/httpdocs/coverage/overview.html",
ftp.store("/httpdocs/coverage/coverage.zip", new FileInputStream("coverage.zip")); new FileInputStream("coverage/overview.html"));
ftp.store("/httpdocs/coverage/coverage.zip",
new FileInputStream("coverage.zip"));
FileUtils.delete("coverage.zip"); FileUtils.delete("coverage.zip");
} }
ftp.close(); ftp.close();
} }
private static void zip(String destFile, String directory, boolean storeOnly) throws IOException { private static void zip(String destFile, String directory, boolean storeOnly)
throws IOException {
OutputStream out = new FileOutputStream(destFile); OutputStream out = new FileOutputStream(destFile);
ZipOutputStream zipOut = new ZipOutputStream(out); ZipOutputStream zipOut = new ZipOutputStream(out);
if (storeOnly) { if (storeOnly) {
...@@ -174,7 +191,8 @@ public class UploadBuild { ...@@ -174,7 +191,8 @@ public class UploadBuild {
zipOut.close(); zipOut.close();
} }
private static void addFiles(File base, File file, ZipOutputStream out) throws IOException { private static void addFiles(File base, File file, ZipOutputStream out)
throws IOException {
if (file.isDirectory()) { if (file.isDirectory()) {
for (File f : file.listFiles()) { for (File f : file.listFiles()) {
addFiles(base, f, out); addFiles(base, f, out);
......
...@@ -26,7 +26,8 @@ public class WebSite { ...@@ -26,7 +26,8 @@ public class WebSite {
private static final String ANALYTICS_TAG = "<!-- analytics -->"; private static final String ANALYTICS_TAG = "<!-- analytics -->";
private static final String ANALYTICS_SCRIPT = private static final String ANALYTICS_SCRIPT =
"<script src=\"http://www.google-analytics.com/ga.js\" type=\"text/javascript\"></script>\n" + "<script src=\"http://www.google-analytics.com/ga.js\" " +
"type=\"text/javascript\"></script>\n" +
"<script type=\"text/javascript\">" + "<script type=\"text/javascript\">" +
"var pageTracker=_gat._getTracker(\"UA-2351060-1\");" + "var pageTracker=_gat._getTracker(\"UA-2351060-1\");" +
"pageTracker._initData();pageTracker._trackPageview();" + "pageTracker._initData();pageTracker._trackPageview();" +
...@@ -116,7 +117,8 @@ public class WebSite { ...@@ -116,7 +117,8 @@ public class WebSite {
dir.delete(); dir.delete();
} }
private void copy(File source, File target, boolean replaceFragments, boolean web) throws IOException { private void copy(File source, File target, boolean replaceFragments,
boolean web) throws IOException {
if (source.isDirectory()) { if (source.isDirectory()) {
target.mkdirs(); target.mkdirs();
for (File f : source.listFiles()) { for (File f : source.listFiles()) {
......
...@@ -113,7 +113,8 @@ public class XMLChecker { ...@@ -113,7 +113,8 @@ public class XMLChecker {
if (html) { if (html) {
for (String n : noClose) { for (String n : noClose) {
if (name.equals(n)) { if (name.equals(n)) {
throw new Exception("Unnecessary closing element " + name + " at " + parser.getRemaining()); throw new Exception("Unnecessary closing element "
+ name + " at " + parser.getRemaining());
} }
} }
} }
...@@ -137,7 +138,8 @@ public class XMLChecker { ...@@ -137,7 +138,8 @@ public class XMLChecker {
// ignore // ignore
} else { } else {
int eventType = parser.getEventType(); int eventType = parser.getEventType();
throw new Exception("Unexpected event " + eventType + " at " + parser.getRemaining()); throw new Exception("Unexpected event " + eventType + " at "
+ parser.getRemaining());
} }
} }
if (stack.size() != 0) { if (stack.size() != 0) {
......
...@@ -119,7 +119,8 @@ public class XMLParser { ...@@ -119,7 +119,8 @@ public class XMLParser {
} }
private void error(String expected) { private void error(String expected) {
throw new RuntimeException("Expected: " + expected + " got: " + xml.substring(pos, Math.min(pos + 1000, xml.length()))); throw new RuntimeException("Expected: " + expected + " got: "
+ xml.substring(pos, Math.min(pos + 1000, xml.length())));
} }
private void read(String chars) { private void read(String chars) {
...@@ -343,7 +344,8 @@ public class XMLParser { ...@@ -343,7 +344,8 @@ public class XMLParser {
if (localNameStart == start) { if (localNameStart == start) {
addAttributeName("", xml.substring(localNameStart, end)); addAttributeName("", xml.substring(localNameStart, end));
} else { } else {
addAttributeName(xml.substring(start, localNameStart - 1), xml.substring(localNameStart, end)); addAttributeName(xml.substring(start, localNameStart - 1),
xml.substring(localNameStart, end));
} }
if (noValue) { if (noValue) {
noValue = false; noValue = false;
...@@ -512,7 +514,8 @@ public class XMLParser { ...@@ -512,7 +514,8 @@ public class XMLParser {
* @return the full name * @return the full name
*/ */
public String getName() { public String getName() {
return prefix == null || prefix.length() == 0 ? localName : prefix + ":" + localName; return prefix == null || prefix.length() == 0 ? localName : prefix
+ ":" + localName;
} }
/** /**
......
...@@ -36,8 +36,10 @@ import com.sun.javadoc.Type; ...@@ -36,8 +36,10 @@ import com.sun.javadoc.Type;
*/ */
public class Doclet { public class Doclet {
private static final boolean INTERFACES_ONLY = Boolean.getBoolean("h2.interfacesOnly"); private static final boolean INTERFACES_ONLY = Boolean
private String destDir = System.getProperty("h2.javadocDestDir", "docs/javadoc"); .getBoolean("h2.interfacesOnly");
private String destDir = System.getProperty("h2.javadocDestDir",
"docs/javadoc");
private int errorCount; private int errorCount;
private final HashSet<String> errors = new HashSet<String>(); private final HashSet<String> errors = new HashSet<String>();
...@@ -85,26 +87,39 @@ public class Doclet { ...@@ -85,26 +87,39 @@ public class Doclet {
String className = getClass(clazz); String className = getClass(clazz);
FileWriter out = new FileWriter(fileName); FileWriter out = new FileWriter(fileName);
PrintWriter writer = new PrintWriter(new BufferedWriter(out)); PrintWriter writer = new PrintWriter(new BufferedWriter(out));
writer.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " + writer.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" " +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
String language = "en"; String language = "en";
writer.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" " + writer.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" " +
"lang=\"" + language + "\" xml:lang=\"" + language + "\">"); "lang=\"" + language + "\" xml:lang=\"" + language + "\">");
writer.println("<head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /><title>"); writer.println("<head>" +
"<meta http-equiv=\"Content-Type\" " +
"content=\"text/html;charset=utf-8\" /><title>");
writer.println(className); writer.println(className);
writer.println("</title><link rel=\"stylesheet\" type=\"text/css\" href=\"../../../stylesheet.css\" />"); writer.println("</title>" +
writer.println("<script type=\"text/javascript\" src=\"../../../animate.js\"></script>"); "<link rel=\"stylesheet\" type=\"text/css\" " +
"href=\"../../../stylesheet.css\" />");
writer.println("<script type=\"text/javascript\" " +
"src=\"../../../animate.js\"></script>");
writer.println("</head><body onload=\"openLink();\">"); writer.println("</head><body onload=\"openLink();\">");
writer.println("<table class=\"content\"><tr class=\"content\"><td class=\"content\"><div class=\"contentDiv\">"); writer.println("<table class=\"content\">" +
"<tr class=\"content\">" +
"<td class=\"content\">" +
"<div class=\"contentDiv\">");
writer.println("<h1>" + className + "</h1>"); writer.println("<h1>" + className + "</h1>");
writer.println(formatText(clazz.commentText()) + "<br /><br />"); writer.println(formatText(clazz.commentText()) + "<br /><br />");
// methods // methods
ConstructorDoc[] constructors = clazz.constructors(); ConstructorDoc[] constructors = clazz.constructors();
MethodDoc[] methods = clazz.methods(); MethodDoc[] methods = clazz.methods();
ExecutableMemberDoc[] constructorsMethods = new ExecutableMemberDoc[constructors.length + methods.length]; ExecutableMemberDoc[] constructorsMethods =
System.arraycopy(constructors, 0, constructorsMethods, 0, constructors.length); new ExecutableMemberDoc[constructors.length
System.arraycopy(methods, 0, constructorsMethods, constructors.length, methods.length); + methods.length];
System.arraycopy(constructors, 0, constructorsMethods, 0,
constructors.length);
System.arraycopy(methods, 0, constructorsMethods, constructors.length,
methods.length);
Arrays.sort(constructorsMethods, new Comparator<ExecutableMemberDoc>() { Arrays.sort(constructorsMethods, new Comparator<ExecutableMemberDoc>() {
@Override @Override
public int compare(ExecutableMemberDoc a, ExecutableMemberDoc b) { public int compare(ExecutableMemberDoc a, ExecutableMemberDoc b) {
...@@ -136,12 +151,17 @@ public class Doclet { ...@@ -136,12 +151,17 @@ public class Doclet {
continue; continue;
} }
if (!hasMethods) { if (!hasMethods) {
writer.println("<table class=\"block\"><tr onclick=\"return allDetails()\"><th colspan=\"2\">Methods</th></tr>"); writer.println("<table class=\"block\">" +
"<tr onclick=\"return allDetails()\">" +
"<th colspan=\"2\">Methods</th></tr>");
hasMethods = true; hasMethods = true;
} }
String type = getTypeName(method.isStatic(), false, getReturnType(method)); String type = getTypeName(method.isStatic(), false,
writer.println("<tr id=\"__"+id+"\" onclick=\"return on("+ id +")\">"); getReturnType(method));
writer.println("<td class=\"return\">" + type + "</td><td class=\"method\">"); writer.println("<tr id=\"__" + id + "\" onclick=\"return on(" +
id + ")\">");
writer.println("<td class=\"return\">" + type +
"</td><td class=\"method\">");
Parameter[] params = method.parameters(); Parameter[] params = method.parameters();
StringBuilder buff = new StringBuilder(); StringBuilder buff = new StringBuilder();
StringBuilder buffSignature = new StringBuilder(name); StringBuilder buffSignature = new StringBuilder(name);
...@@ -168,14 +188,19 @@ public class Doclet { ...@@ -168,14 +188,19 @@ public class Doclet {
signatures.add(null); signatures.add(null);
} }
signatures.add(i, signature); signatures.add(i, signature);
writer.println("<a id=\"" + signature + "\" href=\"#" + signature + "\">" + name + "</a>" + buff.toString()); writer.println("<a id=\"" + signature +
"\" href=\"#" + signature + "\">" +
name + "</a>" + buff.toString());
String firstSentence = getFirstSentence(method.firstSentenceTags()); String firstSentence = getFirstSentence(method.firstSentenceTags());
if (firstSentence != null) { if (firstSentence != null) {
writer.println("<div class=\"methodText\">" + formatText(firstSentence) + "</div>"); writer.println("<div class=\"methodText\">" +
formatText(firstSentence) + "</div>");
} }
writer.println("</td></tr>"); writer.println("</td></tr>");
writer.println("<tr onclick=\"return off("+ id +")\" class=\"detail\" id=\"_"+id+"\">"); writer.println("<tr onclick=\"return off("+
writer.println("<td class=\"return\">" + type + "</td><td>"); id +")\" class=\"detail\" id=\"_"+id+"\">");
writer.println("<td class=\"return\">" +
type + "</td><td>");
writeMethodDetails(writer, clazz, method, signature); writeMethodDetails(writer, clazz, method, signature);
writer.println("</td></tr>"); writer.println("</td></tr>");
id++; id++;
...@@ -203,7 +228,8 @@ public class Doclet { ...@@ -203,7 +228,8 @@ public class Doclet {
String name = field.name(); String name = field.name();
String text = field.commentText(); String text = field.commentText();
if (text == null || text.trim().length() == 0) { if (text == null || text.trim().length() == 0) {
addError("Undocumented field (" + getLink(clazz, field.position().line()) + ") " + name); addError("Undocumented field (" +
getLink(clazz, field.position().line()) + ") " + name);
} }
if (text != null && text.startsWith("INTERNAL")) { if (text != null && text.startsWith("INTERNAL")) {
continue; continue;
...@@ -212,7 +238,8 @@ public class Doclet { ...@@ -212,7 +238,8 @@ public class Doclet {
writer.println("<br /><table><tr><th colspan=\"2\">Fields</th></tr>"); writer.println("<br /><table><tr><th colspan=\"2\">Fields</th></tr>");
} }
String type = getTypeName(true, false, field.type()); String type = getTypeName(true, false, field.type());
writer.println("<tr><td class=\"return\">" + type + "</td><td class=\"method\">"); writer.println("<tr><td class=\"return\">" + type +
"</td><td class=\"method\">");
String constant = field.constantValueExpression(); String constant = field.constantValueExpression();
// add a link (a name) if there is a <code> tag // add a link (a name) if there is a <code> tag
...@@ -254,7 +281,8 @@ public class Doclet { ...@@ -254,7 +281,8 @@ public class Doclet {
out.close(); out.close();
} }
private void writeFieldDetails(PrintWriter writer, ClassDoc clazz, FieldDoc field) { private void writeFieldDetails(PrintWriter writer, ClassDoc clazz,
FieldDoc field) {
if (skipField(clazz, field)) { if (skipField(clazz, field)) {
return; return;
} }
...@@ -265,7 +293,8 @@ public class Doclet { ...@@ -265,7 +293,8 @@ public class Doclet {
String name = field.name(); String name = field.name();
String constant = field.constantValueExpression(); String constant = field.constantValueExpression();
String link = getFieldLink(text, constant, clazz, name); String link = getFieldLink(text, constant, clazz, name);
writer.println("<h4 id=\"" + link + "\"><span class=\"methodName\">" + name); writer.println("<h4 id=\"" + link + "\"><span class=\"methodName\">" +
name);
if (constant == null) { if (constant == null) {
writer.println(); writer.println();
} else { } else {
...@@ -276,7 +305,8 @@ public class Doclet { ...@@ -276,7 +305,8 @@ public class Doclet {
writer.println("<hr />"); writer.println("<hr />");
} }
private void writeMethodDetails(PrintWriter writer, ClassDoc clazz, ExecutableMemberDoc method, String signature) { private void writeMethodDetails(PrintWriter writer, ClassDoc clazz,
ExecutableMemberDoc method, String signature) {
String name = method.name(); String name = method.name();
if (skipMethod(method)) { if (skipMethod(method)) {
return; return;
...@@ -305,9 +335,12 @@ public class Doclet { ...@@ -305,9 +335,12 @@ public class Doclet {
if (isDeprecated(method)) { if (isDeprecated(method)) {
name = "<span class=\"deprecated\">" + name + "</span>"; name = "<span class=\"deprecated\">" + name + "</span>";
} }
writer.println("<a id=\"" + signature + "\" href=\"#" + signature + "\">" + name + "</a>" + buff.toString()); writer.println("<a id=\"" + signature + "\" href=\"#" + signature + "\">" +
boolean hasComment = method.commentText() != null && method.commentText().trim().length() != 0; name + "</a>" + buff.toString());
writer.println("<div class=\"methodText\">" + formatText(method.commentText()) + "</div>"); boolean hasComment = method.commentText() != null &&
method.commentText().trim().length() != 0;
writer.println("<div class=\"methodText\">" +
formatText(method.commentText()) + "</div>");
ParamTag[] paramTags = method.paramTags(); ParamTag[] paramTags = method.paramTags();
ThrowsTag[] throwsTags = method.throwsTags(); ThrowsTag[] throwsTags = method.throwsTags();
boolean hasThrowsTag = throwsTags != null && throwsTags.length > 0; boolean hasThrowsTag = throwsTags != null && throwsTags.length > 0;
...@@ -316,7 +349,8 @@ public class Doclet { ...@@ -316,7 +349,8 @@ public class Doclet {
// [Not supported] and such are not problematic // [Not supported] and such are not problematic
addError("Undocumented parameter(s) (" + addError("Undocumented parameter(s) (" +
getLink(clazz, method.position().line()) + ") " + getLink(clazz, method.position().line()) + ") " +
name + " documented: " + paramTags.length + " params: "+ params.length); name + " documented: " + paramTags.length +
" params: "+ params.length);
} }
} }
for (int j = 0; j < paramTags.length; j++) { for (int j = 0; j < paramTags.length; j++) {
...@@ -324,7 +358,8 @@ public class Doclet { ...@@ -324,7 +358,8 @@ public class Doclet {
String comment = paramTags[j].parameterComment(); String comment = paramTags[j].parameterComment();
if (comment.trim().length() == 0) { if (comment.trim().length() == 0) {
addError("Undocumented parameter (" + addError("Undocumented parameter (" +
getLink(clazz, method.position().line()) + ") " + name + " " + paramName); getLink(clazz, method.position().line()) + ") " +
name + " " + paramName);
} }
String p = paramName + " - " + comment; String p = paramName + " - " + comment;
if (j == 0) { if (j == 0) {
...@@ -343,11 +378,13 @@ public class Doclet { ...@@ -343,11 +378,13 @@ public class Doclet {
} }
writer.println("<div class=\"item\">" + returnComment + "</div>"); writer.println("<div class=\"item\">" + returnComment + "</div>");
} else if (returnType != null && !returnType.toString().equals("void")) { } else if (returnType != null && !returnType.toString().equals("void")) {
if (hasComment && !method.commentText().startsWith("[") && !hasThrowsTag) { if (hasComment && !method.commentText().startsWith("[") &&
!hasThrowsTag) {
// [Not supported] and such are not problematic // [Not supported] and such are not problematic
// also not problematic are methods that always throw an exception // also not problematic are methods that always throw an exception
addError("Undocumented return value (" + addError("Undocumented return value ("
getLink(clazz, method.position().line()) + ") " + name + " " + getReturnType(method)); + getLink(clazz, method.position().line()) + ") "
+ name + " " + getReturnType(method));
} }
} }
if (hasThrowsTag) { if (hasThrowsTag) {
...@@ -372,14 +409,16 @@ public class Doclet { ...@@ -372,14 +409,16 @@ public class Doclet {
return c + ".java:" + line; return c + ".java:" + line;
} }
private String getFieldLink(String text, String constant, ClassDoc clazz, String name) { private String getFieldLink(String text, String constant, ClassDoc clazz,
String name) {
String link = constant != null ? constant : name.toLowerCase(); String link = constant != null ? constant : name.toLowerCase();
int linkStart = text.indexOf("<code>"); int linkStart = text.indexOf("<code>");
if (linkStart >= 0) { if (linkStart >= 0) {
int linkEnd = text.indexOf("</code>", linkStart); int linkEnd = text.indexOf("</code>", linkStart);
link = text.substring(linkStart + "<code>".length(), linkEnd); link = text.substring(linkStart + "<code>".length(), linkEnd);
if (constant != null && !constant.equals(link)) { if (constant != null && !constant.equals(link)) {
System.out.println("Wrong code tag? " + clazz.name() + "." + name + System.out.println("Wrong code tag? " + clazz.name() + "." +
name +
" code: " + link + " constant: " + constant); " code: " + link + " constant: " + constant);
errorCount++; errorCount++;
} }
...@@ -409,8 +448,10 @@ public class Doclet { ...@@ -409,8 +448,10 @@ public class Doclet {
private boolean skipMethod(ExecutableMemberDoc method) { private boolean skipMethod(ExecutableMemberDoc method) {
ClassDoc clazz = method.containingClass(); ClassDoc clazz = method.containingClass();
boolean isAbstract = method instanceof MethodDoc && ((MethodDoc) method).isAbstract(); boolean isAbstract = method instanceof MethodDoc
boolean isInterface = clazz.isInterface() || (clazz.isAbstract() && isAbstract); && ((MethodDoc) method).isAbstract();
boolean isInterface = clazz.isInterface()
|| (clazz.isAbstract() && isAbstract);
if (INTERFACES_ONLY && !isInterface) { if (INTERFACES_ONLY && !isInterface) {
return true; return true;
} }
...@@ -418,10 +459,12 @@ public class Doclet { ...@@ -418,10 +459,12 @@ public class Doclet {
if (method.isPrivate() || name.equals("finalize")) { if (method.isPrivate() || name.equals("finalize")) {
return true; return true;
} }
if (method.isConstructor() && method.getRawCommentText().trim().length() == 0) { if (method.isConstructor()
&& method.getRawCommentText().trim().length() == 0) {
return true; return true;
} }
if (method.getRawCommentText().trim().startsWith("@deprecated INTERNAL")) { if (method.getRawCommentText().trim()
.startsWith("@deprecated INTERNAL")) {
return true; return true;
} }
String firstSentence = getFirstSentence(method.firstSentenceTags()); String firstSentence = getFirstSentence(method.firstSentenceTags());
...@@ -429,19 +472,22 @@ public class Doclet { ...@@ -429,19 +472,22 @@ public class Doclet {
if (firstSentence != null && firstSentence.startsWith("INTERNAL")) { if (firstSentence != null && firstSentence.startsWith("INTERNAL")) {
return true; return true;
} }
if ((firstSentence == null || firstSentence.trim().length() == 0) && raw.indexOf("{@inheritDoc}") < 0) { if ((firstSentence == null || firstSentence.trim().length() == 0)
&& raw.indexOf("{@inheritDoc}") < 0) {
if (!doesOverride(method)) { if (!doesOverride(method)) {
boolean setterOrGetter = name.startsWith("set") && method.parameters().length == 1; boolean setterOrGetter = name.startsWith("set")
setterOrGetter |= name.startsWith("get") && method.parameters().length == 0; && method.parameters().length == 1;
setterOrGetter |= name.startsWith("get")
&& method.parameters().length == 0;
Type returnType = getReturnType(method); Type returnType = getReturnType(method);
setterOrGetter |= name.startsWith("is") && setterOrGetter |= name.startsWith("is")
method.parameters().length == 0 && && method.parameters().length == 0
returnType != null && && returnType != null
returnType.toString().equals("boolean"); && returnType.toString().equals("boolean");
if (!setterOrGetter) { if (!setterOrGetter) {
addError("Undocumented method " + addError("Undocumented method " + " ("
" (" + getLink(clazz, method.position().line()) +") " + + getLink(clazz, method.position().line()) + ") "
clazz + "." + name + " " + raw); + clazz + "." + name + " " + raw);
return true; return true;
} }
} }
...@@ -473,10 +519,12 @@ public class Doclet { ...@@ -473,10 +519,12 @@ public class Doclet {
return foundMethod(clazz, false, method.name(), parameterCount); return foundMethod(clazz, false, method.name(), parameterCount);
} }
private boolean foundMethod(ClassDoc clazz, boolean include, String methodName, int parameterCount) { private boolean foundMethod(ClassDoc clazz, boolean include,
String methodName, int parameterCount) {
if (include) { if (include) {
for (MethodDoc m : clazz.methods()) { for (MethodDoc m : clazz.methods()) {
if (m.name().equals(methodName) && m.parameters().length == parameterCount) { if (m.name().equals(methodName)
&& m.parameters().length == parameterCount) {
return true; return true;
} }
} }
...@@ -487,7 +535,8 @@ public class Doclet { ...@@ -487,7 +535,8 @@ public class Doclet {
} }
} }
clazz = clazz.superclass(); clazz = clazz.superclass();
return clazz != null && foundMethod(clazz, true, methodName, parameterCount); return clazz != null
&& foundMethod(clazz, true, methodName, parameterCount);
} }
private static String getFirstSentence(Tag[] tags) { private static String getFirstSentence(Tag[] tags) {
...@@ -499,7 +548,8 @@ public class Doclet { ...@@ -499,7 +548,8 @@ public class Doclet {
return firstSentence; return firstSentence;
} }
private static String getTypeName(boolean isStatic, boolean isVarArgs, Type type) { private static String getTypeName(boolean isStatic, boolean isVarArgs,
Type type) {
if (type == null) { if (type == null) {
return ""; return "";
} }
......
...@@ -23,7 +23,8 @@ import com.sun.javadoc.Tag; ...@@ -23,7 +23,8 @@ import com.sun.javadoc.Tag;
*/ */
public class ResourceDoclet { public class ResourceDoclet {
private String destFile = System.getProperty("h2.javadocResourceFile", "src/main/org/h2/res/javadoc.properties"); private String destFile = System.getProperty("h2.javadocResourceFile",
"src/main/org/h2/res/javadoc.properties");
private final SortedProperties resources = new SortedProperties(); private final SortedProperties resources = new SortedProperties();
......
...@@ -34,7 +34,8 @@ import org.h2.util.StringUtils; ...@@ -34,7 +34,8 @@ import org.h2.util.StringUtils;
*/ */
public class PrepareTranslation { public class PrepareTranslation {
private static final String MAIN_LANGUAGE = "en"; private static final String MAIN_LANGUAGE = "en";
private static final String[] EXCLUDE = { "datatypes.html", "functions.html", "grammar.html" }; private static final String[] EXCLUDE = { "datatypes.html",
"functions.html", "grammar.html" };
/** /**
* This method is called when executing this application from the command * This method is called when executing this application from the command
...@@ -48,9 +49,11 @@ public class PrepareTranslation { ...@@ -48,9 +49,11 @@ public class PrepareTranslation {
prepare(baseDir, "src/main/org/h2/server/web/res", true); prepare(baseDir, "src/main/org/h2/server/web/res", true);
// convert the txt files to properties files // convert the txt files to properties files
PropertiesToUTF8.textUTF8ToProperties("src/docsrc/text/_docs_de.utf8.txt", PropertiesToUTF8.textUTF8ToProperties(
"src/docsrc/text/_docs_de.utf8.txt",
"src/docsrc/text/_docs_de.properties"); "src/docsrc/text/_docs_de.properties");
PropertiesToUTF8.textUTF8ToProperties("src/docsrc/text/_docs_ja.utf8.txt", PropertiesToUTF8.textUTF8ToProperties(
"src/docsrc/text/_docs_ja.utf8.txt",
"src/docsrc/text/_docs_ja.properties"); "src/docsrc/text/_docs_ja.properties");
// create the .jsp files and extract the text in the main language // create the .jsp files and extract the text in the main language
...@@ -66,11 +69,14 @@ public class PrepareTranslation { ...@@ -66,11 +69,14 @@ public class PrepareTranslation {
// convert the properties files back to utf8 text files, including the // convert the properties files back to utf8 text files, including the
// main language (to be used as a template) // main language (to be used as a template)
PropertiesToUTF8.propertiesToTextUTF8("src/docsrc/text/_docs_en.properties", PropertiesToUTF8.propertiesToTextUTF8(
"src/docsrc/text/_docs_en.properties",
"src/docsrc/text/_docs_en.utf8.txt"); "src/docsrc/text/_docs_en.utf8.txt");
PropertiesToUTF8.propertiesToTextUTF8("src/docsrc/text/_docs_de.properties", PropertiesToUTF8.propertiesToTextUTF8(
"src/docsrc/text/_docs_de.properties",
"src/docsrc/text/_docs_de.utf8.txt"); "src/docsrc/text/_docs_de.utf8.txt");
PropertiesToUTF8.propertiesToTextUTF8("src/docsrc/text/_docs_ja.properties", PropertiesToUTF8.propertiesToTextUTF8(
"src/docsrc/text/_docs_ja.properties",
"src/docsrc/text/_docs_ja.utf8.txt"); "src/docsrc/text/_docs_ja.utf8.txt");
// delete temporary files // delete temporary files
...@@ -81,11 +87,13 @@ public class PrepareTranslation { ...@@ -81,11 +87,13 @@ public class PrepareTranslation {
} }
} }
private static void buildHtml(String templateDir, String targetDir, String language) throws IOException { private static void buildHtml(String templateDir, String targetDir,
String language) throws IOException {
File[] list = new File(templateDir).listFiles(); File[] list = new File(templateDir).listFiles();
new File(targetDir).mkdirs(); new File(targetDir).mkdirs();
// load the main 'translation' // load the main 'translation'
String propName = templateDir + "/_docs_" + MAIN_LANGUAGE + ".properties"; String propName = templateDir + "/_docs_" + MAIN_LANGUAGE
+ ".properties";
Properties prop = load(propName, false); Properties prop = load(propName, false);
propName = templateDir + "/_docs_" + language + ".properties"; propName = templateDir + "/_docs_" + language + ".properties";
if (!(new File(propName)).exists()) { if (!(new File(propName)).exists()) {
...@@ -119,22 +127,26 @@ public class PrepareTranslation { ...@@ -119,22 +127,26 @@ public class PrepareTranslation {
} }
// remove '.jsp' // remove '.jsp'
name = name.substring(0, name.length() - 4); name = name.substring(0, name.length() - 4);
String template = IOUtils.readStringAndClose(new FileReader(templateDir + "/" + name + ".jsp"), -1); String template = IOUtils.readStringAndClose(new FileReader(
templateDir + "/" + name + ".jsp"), -1);
HashMap<String, Object> map = New.hashMap(); HashMap<String, Object> map = New.hashMap();
for (Object k : prop.keySet()) { for (Object k : prop.keySet()) {
map.put(k.toString(), prop.get(k)); map.put(k.toString(), prop.get(k));
} }
String html = PageParser.parse(template, map); String html = PageParser.parse(template, map);
html = StringUtils.replaceAll(html, "lang=\"" + MAIN_LANGUAGE + "\"", "lang=\"" + language + "\""); html = StringUtils.replaceAll(html, "lang=\"" + MAIN_LANGUAGE
+ "\"", "lang=\"" + language + "\"");
for (String n : fileNames) { for (String n : fileNames) {
if ("frame".equals(n)) { if ("frame".equals(n)) {
// don't translate 'frame.html' to 'frame_ja.html', // don't translate 'frame.html' to 'frame_ja.html',
// otherwise we can't switch back to English // otherwise we can't switch back to English
continue; continue;
} }
html = StringUtils.replaceAll(html, n + ".html\"", n + "_" + language + ".html\""); html = StringUtils.replaceAll(html, n + ".html\"", n + "_"
+ language + ".html\"");
} }
html = StringUtils.replaceAll(html, "_" + MAIN_LANGUAGE + ".html\"", ".html\""); html = StringUtils.replaceAll(html,
"_" + MAIN_LANGUAGE + ".html\"", ".html\"");
String target; String target;
if (language.equals(MAIN_LANGUAGE)) { if (language.equals(MAIN_LANGUAGE)) {
target = targetDir + "/" + name + ".html"; target = targetDir + "/" + name + ".html";
...@@ -157,7 +169,8 @@ public class PrepareTranslation { ...@@ -157,7 +169,8 @@ public class PrepareTranslation {
return false; return false;
} }
private static void extractFromHtml(String dir, String target) throws Exception { private static void extractFromHtml(String dir, String target)
throws Exception {
for (File f : new File(dir).listFiles()) { for (File f : new File(dir).listFiles()) {
String name = f.getName(); String name = f.getName();
if (!name.endsWith(".html")) { if (!name.endsWith(".html")) {
...@@ -216,8 +229,10 @@ public class PrepareTranslation { ...@@ -216,8 +229,10 @@ public class PrepareTranslation {
return ""; return "";
} }
private static String extract(String documentName, File f, String target) throws Exception { private static String extract(String documentName, File f, String target)
String xml = IOUtils.readStringAndClose(new InputStreamReader(new FileInputStream(f), "UTF-8"), -1); throws Exception {
String xml = IOUtils.readStringAndClose(new InputStreamReader(
new FileInputStream(f), "UTF-8"), -1);
// the template contains ${} instead of text // the template contains ${} instead of text
StringBuilder template = new StringBuilder(xml.length()); StringBuilder template = new StringBuilder(xml.length());
int id = 0; int id = 0;
...@@ -242,30 +257,39 @@ public class PrepareTranslation { ...@@ -242,30 +257,39 @@ public class PrepareTranslation {
} else { } else {
template.append(s); template.append(s);
} }
} else if ("p".equals(tag) || "li".equals(tag) || "a".equals(tag) || "td".equals(tag) } else if ("p".equals(tag) || "li".equals(tag)
|| "th".equals(tag) || "h1".equals(tag) || "h2".equals(tag) || "h3".equals(tag) || "a".equals(tag) || "td".equals(tag)
|| "h4".equals(tag) || "body".equals(tag) || "b".equals(tag) || "code".equals(tag) || "th".equals(tag) || "h1".equals(tag)
|| "form".equals(tag) || "span".equals(tag) || "em".equals(tag) || "div".equals(tag) || "h2".equals(tag) || "h3".equals(tag)
|| "h4".equals(tag) || "body".equals(tag)
|| "b".equals(tag) || "code".equals(tag)
|| "form".equals(tag) || "span".equals(tag)
|| "em".equals(tag) || "div".equals(tag)
|| "label".equals(tag)) { || "label".equals(tag)) {
if (buff.length() == 0) { if (buff.length() == 0) {
nextKey = documentName + "_" + (1000 + id++) + "_" + tag; nextKey = documentName + "_" + (1000 + id++) + "_"
+ tag;
template.append(getSpace(s, true)); template.append(getSpace(s, true));
} else if (templateIsCopy) { } else if (templateIsCopy) {
buff.append(getSpace(s, true)); buff.append(getSpace(s, true));
} }
buff.append(s); buff.append(s);
} else if ("pre".equals(tag) || "title".equals(tag) || "script".equals(tag) || "style".equals(tag)) { } else if ("pre".equals(tag) || "title".equals(tag)
|| "script".equals(tag) || "style".equals(tag)) {
// ignore, don't translate // ignore, don't translate
template.append(s); template.append(s);
} else { } else {
System.out.println(f.getName() + " invalid wrapper tag for text: " + tag + " text: " + s); System.out.println(f.getName()
+ " invalid wrapper tag for text: " + tag
+ " text: " + s);
System.out.println(parser.getRemaining()); System.out.println(parser.getRemaining());
throw new Exception(); throw new Exception();
} }
} else if (event == XMLParser.START_ELEMENT) { } else if (event == XMLParser.START_ELEMENT) {
stack.add(tag); stack.add(tag);
String name = parser.getName(); String name = parser.getName();
if ("code".equals(name) || "a".equals(name) || "b".equals(name) || "span".equals(name)) { if ("code".equals(name) || "a".equals(name) || "b".equals(name)
|| "span".equals(name)) {
// keep tags if wrapped, but not if this is the wrapper // keep tags if wrapped, but not if this is the wrapper
if (buff.length() > 0) { if (buff.length() > 0) {
buff.append(parser.getToken()); buff.append(parser.getToken());
...@@ -274,8 +298,10 @@ public class PrepareTranslation { ...@@ -274,8 +298,10 @@ public class PrepareTranslation {
ignoreEnd = true; ignoreEnd = true;
template.append(parser.getToken()); template.append(parser.getToken());
} }
} else if ("p".equals(tag) || "li".equals(tag) || "td".equals(tag) || "th".equals(tag) } else if ("p".equals(tag) || "li".equals(tag)
|| "h1".equals(tag) || "h2".equals(tag) || "h3".equals(tag) || "h4".equals(tag) || "td".equals(tag) || "th".equals(tag)
|| "h1".equals(tag) || "h2".equals(tag)
|| "h3".equals(tag) || "h4".equals(tag)
|| "body".equals(tag) || "form".equals(tag)) { || "body".equals(tag) || "form".equals(tag)) {
if (buff.length() > 0) { if (buff.length() > 0) {
if (templateIsCopy) { if (templateIsCopy) {
...@@ -292,8 +318,8 @@ public class PrepareTranslation { ...@@ -292,8 +318,8 @@ public class PrepareTranslation {
tag = name; tag = name;
} else if (event == XMLParser.END_ELEMENT) { } else if (event == XMLParser.END_ELEMENT) {
String name = parser.getName(); String name = parser.getName();
if ("code".equals(name) || "a".equals(name) || "b".equals(name) || "span".equals(name) if ("code".equals(name) || "a".equals(name) || "b".equals(name)
|| "em".equals(name)) { || "span".equals(name) || "em".equals(name)) {
if (ignoreEnd) { if (ignoreEnd) {
if (buff.length() > 0) { if (buff.length() > 0) {
if (templateIsCopy) { if (templateIsCopy) {
...@@ -327,7 +353,8 @@ public class PrepareTranslation { ...@@ -327,7 +353,8 @@ public class PrepareTranslation {
template.append(parser.getToken()); template.append(parser.getToken());
} else { } else {
int eventType = parser.getEventType(); int eventType = parser.getEventType();
throw new Exception("Unexpected event " + eventType + " at " + parser.getRemaining()); throw new Exception("Unexpected event " + eventType + " at "
+ parser.getRemaining());
} }
// if(!xml.startsWith(template.toString())) { // if(!xml.startsWith(template.toString())) {
// System.out.println(nextKey); // System.out.println(nextKey);
...@@ -387,7 +414,8 @@ public class PrepareTranslation { ...@@ -387,7 +414,8 @@ public class PrepareTranslation {
prop.setProperty(document, s); prop.setProperty(document, s);
} }
private static void prepare(String baseDir, String path, boolean utf8) throws IOException { private static void prepare(String baseDir, String path, boolean utf8)
throws IOException {
String suffix = utf8 ? ".prop" : ".properties"; String suffix = utf8 ? ".prop" : ".properties";
File dir = new File(path); File dir = new File(path);
File main = null; File main = null;
...@@ -406,21 +434,25 @@ public class PrepareTranslation { ...@@ -406,21 +434,25 @@ public class PrepareTranslation {
store(p, main.getAbsolutePath(), utf8); store(p, main.getAbsolutePath(), utf8);
for (File trans : translations) { for (File trans : translations) {
String language = trans.getName(); String language = trans.getName();
language = language.substring(language.lastIndexOf('_') + 1, language.lastIndexOf('.')); language = language.substring(language.lastIndexOf('_') + 1,
language.lastIndexOf('.'));
prepare(p, base, trans, utf8); prepare(p, base, trans, utf8);
} }
store(p, baseDir + "/" + main.getName(), utf8); store(p, baseDir + "/" + main.getName(), utf8);
} }
private static SortedProperties load(String fileName, boolean utf8) throws IOException { private static SortedProperties load(String fileName, boolean utf8)
throws IOException {
if (utf8) { if (utf8) {
String s = new String(IOUtils.readBytesAndClose(new FileInputStream(fileName), -1), "UTF-8"); String s = new String(IOUtils.readBytesAndClose(
new FileInputStream(fileName), -1), "UTF-8");
return SortedProperties.fromLines(s); return SortedProperties.fromLines(s);
} }
return SortedProperties.loadProperties(fileName); return SortedProperties.loadProperties(fileName);
} }
private static void store(SortedProperties p, String fileName, boolean utf8) throws IOException { private static void store(SortedProperties p, String fileName, boolean utf8)
throws IOException {
if (utf8) { if (utf8) {
String s = p.toLines(); String s = p.toLines();
FileOutputStream f = new FileOutputStream(fileName); FileOutputStream f = new FileOutputStream(fileName);
...@@ -431,7 +463,8 @@ public class PrepareTranslation { ...@@ -431,7 +463,8 @@ public class PrepareTranslation {
} }
} }
private static void prepare(Properties main, Properties base, File trans, boolean utf8) throws IOException { private static void prepare(Properties main, Properties base, File trans,
boolean utf8) throws IOException {
SortedProperties p = load(trans.getAbsolutePath(), utf8); SortedProperties p = load(trans.getAbsolutePath(), utf8);
Properties oldTranslations = new Properties(); Properties oldTranslations = new Properties();
for (Object k : base.keySet()) { for (Object k : base.keySet()) {
...@@ -471,8 +504,10 @@ public class PrepareTranslation { ...@@ -471,8 +504,10 @@ public class PrepareTranslation {
} else if (last != null && !last.equals(now)) { } else if (last != null && !last.equals(now)) {
t = oldTranslations.getProperty(now); t = oldTranslations.getProperty(now);
if (t == null) { if (t == null) {
// main data changed since the last run: review translation // main data changed since the last run: review
System.out.println(trans.getName() + ": key " + key + " changed, please review; last=" + last // translation
System.out.println(trans.getName() + ": key " + key
+ " changed, please review; last=" + last
+ " now=" + now); + " now=" + now);
String old = p.getProperty(key); String old = p.getProperty(key);
t = "#" + now + " #" + old; t = "#" + now + " #" + old;
...@@ -486,7 +521,11 @@ public class PrepareTranslation { ...@@ -486,7 +521,11 @@ public class PrepareTranslation {
for (String key : toTranslate) { for (String key : toTranslate) {
String now = main.getProperty(key); String now = main.getProperty(key);
String t; String t;
System.out.println(trans.getName() + ": key " + key + " not found in translation file; added dummy # 'translation'"); System.out
.println(trans.getName()
+ ": key "
+ key
+ " not found in translation file; added dummy # 'translation'");
t = "#" + now; t = "#" + now;
p.put(key, t); p.put(key, t);
} }
......
...@@ -49,7 +49,8 @@ public class PropertiesToUTF8 { ...@@ -49,7 +49,8 @@ public class PropertiesToUTF8 {
* @param source the name of the properties file * @param source the name of the properties file
* @param target the target file name * @param target the target file name
*/ */
static void propertiesToTextUTF8(String source, String target) throws Exception { static void propertiesToTextUTF8(String source, String target)
throws Exception {
if (!new File(source).exists()) { if (!new File(source).exists()) {
return; return;
} }
...@@ -73,11 +74,13 @@ public class PropertiesToUTF8 { ...@@ -73,11 +74,13 @@ public class PropertiesToUTF8 {
* @param source the source file name * @param source the source file name
* @param target the target file name * @param target the target file name
*/ */
static void textUTF8ToProperties(String source, String target) throws Exception { static void textUTF8ToProperties(String source, String target)
throws Exception {
if (!new File(source).exists()) { if (!new File(source).exists()) {
return; return;
} }
LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(source), "UTF-8")); LineNumberReader reader = new LineNumberReader(new InputStreamReader(
new FileInputStream(source), "UTF-8"));
try { try {
SortedProperties prop = new SortedProperties(); SortedProperties prop = new SortedProperties();
StringBuilder buff = new StringBuilder(); StringBuilder buff = new StringBuilder();
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论