提交 00b26a11 authored 作者: Thomas Mueller's avatar Thomas Mueller

Limit line length to 80 characters

上级 74525f99
......@@ -37,7 +37,8 @@ public class CommandRemote implements CommandInterface {
private boolean readonly;
private final int created;
public CommandRemote(SessionRemote session, ArrayList<Transfer> transferList, String sql, int fetchSize) {
public CommandRemote(SessionRemote session,
ArrayList<Transfer> transferList, String sql, int fetchSize) {
this.transferList = transferList;
trace = session.getTrace();
this.sql = sql;
......@@ -57,10 +58,13 @@ public class CommandRemote implements CommandInterface {
Transfer transfer = transferList.get(i);
if (createParams) {
s.traceOperation("SESSION_PREPARE_READ_PARAMS", id);
transfer.writeInt(SessionRemote.SESSION_PREPARE_READ_PARAMS).writeInt(id).writeString(sql);
transfer.
writeInt(SessionRemote.SESSION_PREPARE_READ_PARAMS).
writeInt(id).writeString(sql);
} else {
s.traceOperation("SESSION_PREPARE", id);
transfer.writeInt(SessionRemote.SESSION_PREPARE).writeInt(id).writeString(sql);
transfer.writeInt(SessionRemote.SESSION_PREPARE).
writeInt(id).writeString(sql);
}
s.done(transfer);
isQuery = transfer.readBoolean();
......@@ -115,10 +119,12 @@ public class CommandRemote implements CommandInterface {
Transfer transfer = transferList.get(i);
try {
session.traceOperation("COMMAND_GET_META_DATA", id);
transfer.writeInt(SessionRemote.COMMAND_GET_META_DATA).writeInt(id).writeInt(objectId);
transfer.writeInt(SessionRemote.COMMAND_GET_META_DATA).
writeInt(id).writeInt(objectId);
session.done(transfer);
int columnCount = transfer.readInt();
result = new ResultRemote(session, transfer, objectId, columnCount, Integer.MAX_VALUE);
result = new ResultRemote(session, transfer, objectId,
columnCount, Integer.MAX_VALUE);
break;
} catch (IOException e) {
session.removeServer(e, i--, ++count);
......@@ -140,8 +146,8 @@ public class CommandRemote implements CommandInterface {
Transfer transfer = transferList.get(i);
try {
session.traceOperation("COMMAND_EXECUTE_QUERY", id);
transfer.writeInt(SessionRemote.COMMAND_EXECUTE_QUERY).writeInt(id).writeInt(objectId).writeInt(
maxRows);
transfer.writeInt(SessionRemote.COMMAND_EXECUTE_QUERY).
writeInt(id).writeInt(objectId).writeInt(maxRows);
int fetch;
if (session.isClustered() || scrollable) {
fetch = Integer.MAX_VALUE;
......
......@@ -105,7 +105,8 @@ public class Database implements DataHandler {
private final HashMap<String, UserAggregate> aggregates = New.hashMap();
private final HashMap<String, Comment> comments = New.hashMap();
private final Set<Session> userSessions = Collections.synchronizedSet(new HashSet<Session>());
private final Set<Session> userSessions =
Collections.synchronizedSet(new HashSet<Session>());
private Session exclusiveSession;
private final BitField objectIds = new BitField();
private final Object lobSyncObject = new Object();
......@@ -154,7 +155,8 @@ public class Database implements DataHandler {
private DatabaseCloser closeOnExit;
private Mode mode = Mode.getInstance(Mode.REGULAR);
private boolean multiThreaded;
private int maxOperationMemory = Constants.DEFAULT_MAX_OPERATION_MEMORY;
private int maxOperationMemory =
Constants.DEFAULT_MAX_OPERATION_MEMORY;
private SmallLRUCache<String, String[]> lobFileListCache;
private final boolean autoServerMode;
private final int autoServerPort;
......@@ -228,19 +230,28 @@ public class Database implements DataHandler {
if (modeName != null) {
this.mode = Mode.getInstance(modeName);
}
this.multiVersion = ci.getProperty("MVCC", false);
this.logMode = ci.getProperty("LOG", PageStore.LOG_MODE_SYNC);
this.javaObjectSerializerName = ci.getProperty("JAVA_OBJECT_SERIALIZER", null);
boolean closeAtVmShutdown = dbSettings.dbCloseOnExit;
int traceLevelFile = ci.getIntProperty(SetTypes.TRACE_LEVEL_FILE, TraceSystem.DEFAULT_TRACE_LEVEL_FILE);
int traceLevelSystemOut = ci.getIntProperty(SetTypes.TRACE_LEVEL_SYSTEM_OUT,
this.multiVersion =
ci.getProperty("MVCC", false);
this.logMode =
ci.getProperty("LOG", PageStore.LOG_MODE_SYNC);
this.javaObjectSerializerName =
ci.getProperty("JAVA_OBJECT_SERIALIZER", null);
boolean closeAtVmShutdown =
dbSettings.dbCloseOnExit;
int traceLevelFile =
ci.getIntProperty(SetTypes.TRACE_LEVEL_FILE,
TraceSystem.DEFAULT_TRACE_LEVEL_FILE);
int traceLevelSystemOut =
ci.getIntProperty(SetTypes.TRACE_LEVEL_SYSTEM_OUT,
TraceSystem.DEFAULT_TRACE_LEVEL_SYSTEM_OUT);
this.cacheType = StringUtils.toUpperEnglish(ci.removeProperty("CACHE_TYPE", Constants.CACHE_TYPE_DEFAULT));
this.cacheType = StringUtils.toUpperEnglish(
ci.removeProperty("CACHE_TYPE", Constants.CACHE_TYPE_DEFAULT));
openDatabase(traceLevelFile, traceLevelSystemOut, closeAtVmShutdown);
}
private void openDatabase(int traceLevelFile, int traceLevelSystemOut, boolean closeAtVmShutdown) {
private void openDatabase(int traceLevelFile, int traceLevelSystemOut,
boolean closeAtVmShutdown) {
try {
open(traceLevelFile, traceLevelSystemOut);
if (closeAtVmShutdown) {
......@@ -547,8 +558,10 @@ public class Database implements DataHandler {
boolean existsPage = FileUtils.exists(pageFileName);
boolean existsMv = FileUtils.exists(mvFileName);
if (existsData && (!existsPage && !existsMv)) {
throw DbException.get(ErrorCode.FILE_VERSION_ERROR_1,
"Old database: " + dataFileName + " - please convert the database to a SQL script and re-create it.");
throw DbException.get(
ErrorCode.FILE_VERSION_ERROR_1, "Old database: " +
dataFileName +
" - please convert the database to a SQL script and re-create it.");
}
if (existsPage && !FileUtils.canWrite(pageFileName)) {
readOnly = true;
......@@ -576,7 +589,8 @@ public class Database implements DataHandler {
fileLockMethod == FileLock.LOCK_SERIALIZED ||
fileLockMethod == FileLock.LOCK_FS ||
!persistent) {
throw DbException.getUnsupportedException("autoServerMode && (readOnly || fileLockMethod == NO" +
throw DbException.getUnsupportedException(
"autoServerMode && (readOnly || fileLockMethod == NO" +
" || fileLockMethod == SERIALIZED || inMemory)");
}
}
......@@ -634,7 +648,8 @@ public class Database implements DataHandler {
}
} else {
if (autoServerMode) {
throw DbException.getUnsupportedException("autoServerMode && inMemory");
throw DbException.getUnsupportedException(
"autoServerMode && inMemory");
}
traceSystem = new TraceSystem(null);
trace = traceSystem.getTrace(Trace.DATABASE);
......@@ -671,7 +686,8 @@ public class Database implements DataHandler {
data.session = systemSession;
meta = mainSchema.createTable(data);
IndexColumn[] pkCols = IndexColumn.wrap(new Column[] { columnId });
metaIdIndex = meta.addIndex(systemSession, "SYS_ID", 0, pkCols, IndexType.createPrimaryKey(
metaIdIndex = meta.addIndex(systemSession, "SYS_ID",
0, pkCols, IndexType.createPrimaryKey(
false, false), true, null);
objectIds.set(0);
starting = true;
......
......@@ -30,7 +30,8 @@ public class Engine implements SessionFactory {
private static final Engine INSTANCE = new Engine();
private static final HashMap<String, Database> DATABASES = New.hashMap();
private volatile long wrongPasswordDelay = SysProperties.DELAY_WRONG_PASSWORD_MIN;
private volatile long wrongPasswordDelay =
SysProperties.DELAY_WRONG_PASSWORD_MIN;
private boolean jmx;
public static Engine getInstance() {
......@@ -58,7 +59,8 @@ public class Engine implements SessionFactory {
if (database.getAllUsers().size() == 0) {
// users is the last thing we add, so if no user is around,
// the database is new (or not initialized correctly)
user = new User(database, database.allocateObjectId(), ci.getUserName(), false);
user = new User(database, database.allocateObjectId(),
ci.getUserName(), false);
user.setAdmin(true);
user.setUserPasswordHash(ci.getUserPasswordHash());
database.setMasterUser(user);
......@@ -100,7 +102,8 @@ public class Engine implements SessionFactory {
Session session = database.createSession(user);
if (ci.getProperty("JMX", false)) {
try {
Utils.callStaticMethod("org.h2.jmx.DatabaseInfo.registerMBean", ci, database);
Utils.callStaticMethod(
"org.h2.jmx.DatabaseInfo.registerMBean", ci, database);
} catch (Exception e) {
database.removeSession(session);
throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, e, "JMX");
......@@ -152,7 +155,8 @@ public class Engine implements SessionFactory {
private synchronized Session openSession(ConnectionInfo ci) {
boolean ifExists = ci.removeProperty("IFEXISTS", false);
boolean ignoreUnknownSetting = ci.removeProperty("IGNORE_UNKNOWN_SETTINGS", false);
boolean ignoreUnknownSetting = ci.removeProperty(
"IGNORE_UNKNOWN_SETTINGS", false);
String cipher = ci.removeProperty("CIPHER", null);
String init = ci.removeProperty("INIT", null);
Session session;
......@@ -183,8 +187,9 @@ public class Engine implements SessionFactory {
}
String value = ci.getProperty(setting);
try {
CommandInterface command = session.prepareCommand("SET " + Parser.quoteIdentifier(setting) + " "
+ value, Integer.MAX_VALUE);
CommandInterface command = session.prepareCommand(
"SET " + Parser.quoteIdentifier(setting) + " " + value,
Integer.MAX_VALUE);
command.executeUpdate();
} catch (DbException e) {
if (!ignoreUnknownSetting) {
......@@ -195,7 +200,8 @@ public class Engine implements SessionFactory {
}
if (init != null) {
try {
CommandInterface command = session.prepareCommand(init, Integer.MAX_VALUE);
CommandInterface command = session.prepareCommand(init,
Integer.MAX_VALUE);
command.executeUpdate();
} catch (DbException e) {
if (!ignoreUnknownSetting) {
......@@ -221,9 +227,12 @@ public class Engine implements SessionFactory {
if (!Constants.CLUSTERING_ENABLED.equals(clusterSession)) {
if (!StringUtils.equals(clusterSession, clusterDb)) {
if (clusterDb.equals(Constants.CLUSTERING_DISABLED)) {
throw DbException.get(ErrorCode.CLUSTER_ERROR_DATABASE_RUNS_ALONE);
throw DbException.get(
ErrorCode.CLUSTER_ERROR_DATABASE_RUNS_ALONE);
}
throw DbException.get(ErrorCode.CLUSTER_ERROR_DATABASE_RUNS_CLUSTERED_1, clusterDb);
throw DbException.get(
ErrorCode.CLUSTER_ERROR_DATABASE_RUNS_CLUSTERED_1,
clusterDb);
}
}
}
......
......@@ -167,7 +167,8 @@ public class IntArray {
public void removeRange(int fromIndex, int toIndex) {
if (SysProperties.CHECK) {
if (fromIndex > toIndex || toIndex > size) {
throw new ArrayIndexOutOfBoundsException("from=" + fromIndex + " to=" + toIndex + " size=" + size);
throw new ArrayIndexOutOfBoundsException("from=" + fromIndex +
" to=" + toIndex + " size=" + size);
}
}
System.arraycopy(data, toIndex, data, fromIndex, size - toIndex);
......
......@@ -107,7 +107,8 @@ public class JdbcUtils {
* @param password the password
* @return the database connection
*/
public static Connection getConnection(String driver, String url, String user, String password) throws SQLException {
public static Connection getConnection(String driver, String url,
String user, String password) throws SQLException {
Properties prop = new Properties();
if (user != null) {
prop.setProperty("user", user);
......
......@@ -41,7 +41,8 @@ public class NetUtils {
* @param ssl if SSL should be used
* @return the socket
*/
public static Socket createLoopbackSocket(int port, boolean ssl) throws IOException {
public static Socket createLoopbackSocket(int port, boolean ssl)
throws IOException {
InetAddress address = getBindAddress();
if (address == null) {
address = InetAddress.getLocalHost();
......@@ -84,7 +85,8 @@ public class NetUtils {
* @param ssl if SSL should be used
* @return the socket
*/
public static Socket createSocket(String server, int defaultPort, boolean ssl) throws IOException {
public static Socket createSocket(String server, int defaultPort,
boolean ssl) throws IOException {
int port = defaultPort;
// IPv6: RFC 2732 format is '[a:b:c:d:e:f:g:h]' or
// '[a:b:c:d:e:f:g:h]:port'
......@@ -108,7 +110,8 @@ public class NetUtils {
* @param ssl if SSL should be used
* @return the socket
*/
public static Socket createSocket(InetAddress address, int port, boolean ssl) throws IOException {
public static Socket createSocket(InetAddress address, int port, boolean ssl)
throws IOException {
long start = System.currentTimeMillis();
for (int i = 0;; i++) {
try {
......@@ -120,7 +123,8 @@ public class NetUtils {
SysProperties.SOCKET_CONNECT_TIMEOUT);
return socket;
} catch (IOException e) {
if (System.currentTimeMillis() - start >= SysProperties.SOCKET_CONNECT_TIMEOUT) {
if (System.currentTimeMillis() - start >=
SysProperties.SOCKET_CONNECT_TIMEOUT) {
// either it was a connect timeout,
// or list of different exceptions
throw e;
......@@ -200,7 +204,8 @@ public class NetUtils {
* @param socket the socket
* @return true if it is
*/
public static boolean isLocalAddress(Socket socket) throws UnknownHostException {
public static boolean isLocalAddress(Socket socket)
throws UnknownHostException {
InetAddress test = socket.getInetAddress();
if (test.isLoopbackAddress()) {
return true;
......
......@@ -67,7 +67,8 @@ public class Utils {
/**
* In order to manage more than one class loader
*/
private static ArrayList<ClassFactory> userClassFactories = new ArrayList<ClassFactory>();
private static ArrayList<ClassFactory> userClassFactories =
new ArrayList<ClassFactory>();
private static String[] allowedClassNamePrefixes;
......@@ -114,7 +115,10 @@ public class Utils {
}
private static int readInt(byte[] buff, int pos) {
return (buff[pos++] << 24) + ((buff[pos++] & 0xff) << 16) + ((buff[pos++] & 0xff) << 8) + (buff[pos] & 0xff);
return (buff[pos++] << 24) +
((buff[pos++] & 0xff) << 16) +
((buff[pos++] & 0xff) << 8) +
(buff[pos] & 0xff);
}
/**
......@@ -397,7 +401,8 @@ public class Utils {
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
is = new ObjectInputStream(in) {
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
try {
return Class.forName(desc.getName(), true, loader);
} catch (ClassNotFoundException e) {
......@@ -529,7 +534,8 @@ public class Utils {
*/
private static <X> void partitionTopN(X[] array, int offset, int limit,
Comparator<? super X> comp) {
partialQuickSort(array, 0, array.length - 1, comp, offset, offset + limit - 1);
partialQuickSort(array, 0, array.length - 1, comp, offset, offset +
limit - 1);
}
private static <X> void partialQuickSort(X[] array, int low, int high,
......@@ -577,7 +583,8 @@ public class Utils {
* @param c2 the second class
* @return true if they have
*/
public static boolean haveCommonComparableSuperclass(Class<?> c1, Class<?> c2) {
public static boolean haveCommonComparableSuperclass(
Class<?> c1, Class<?> c2) {
if (c1 == c2 || c1.isAssignableFrom(c2) || c2.isAssignableFrom(c1)) {
return true;
}
......@@ -633,7 +640,8 @@ public class Utils {
}
}
if (!allowed) {
throw DbException.get(ErrorCode.ACCESS_DENIED_TO_CLASS_1, className);
throw DbException.get(
ErrorCode.ACCESS_DENIED_TO_CLASS_1, className);
}
}
// Use provided class factory first.
......@@ -645,7 +653,8 @@ public class Utils {
return userClass;
}
} catch (Exception e) {
throw DbException.get(ErrorCode.CLASS_NOT_FOUND_1, e, className);
throw DbException.get(
ErrorCode.CLASS_NOT_FOUND_1, e, className);
}
}
}
......@@ -654,15 +663,20 @@ public class Utils {
return Class.forName(className);
} catch (ClassNotFoundException e) {
try {
return Class.forName(className, true, Thread.currentThread().getContextClassLoader());
return Class.forName(
className, true,
Thread.currentThread().getContextClassLoader());
} catch (Exception e2) {
throw DbException.get(ErrorCode.CLASS_NOT_FOUND_1, e, className);
throw DbException.get(
ErrorCode.CLASS_NOT_FOUND_1, e, className);
}
} catch (NoClassDefFoundError e) {
throw DbException.get(ErrorCode.CLASS_NOT_FOUND_1, e, className);
throw DbException.get(
ErrorCode.CLASS_NOT_FOUND_1, e, className);
} catch (Error e) {
// UnsupportedClassVersionError
throw DbException.get(ErrorCode.GENERAL_ERROR_1, e, className);
throw DbException.get(
ErrorCode.GENERAL_ERROR_1, e, className);
}
}
......@@ -728,7 +742,8 @@ public class Utils {
* @param params the method parameters
* @return the return value from this call
*/
public static Object callStaticMethod(String classAndMethod, Object... params) throws Exception {
public static Object callStaticMethod(String classAndMethod,
Object... params) throws Exception {
int lastDot = classAndMethod.lastIndexOf('.');
String className = classAndMethod.substring(0, lastDot);
String methodName = classAndMethod.substring(lastDot + 1);
......@@ -760,7 +775,8 @@ public class Utils {
int bestMatch = 0;
boolean isStatic = instance == null;
for (Method m : clazz.getMethods()) {
if (Modifier.isStatic(m.getModifiers()) == isStatic && m.getName().equals(methodName)) {
if (Modifier.isStatic(m.getModifiers()) == isStatic &&
m.getName().equals(methodName)) {
int p = match(m.getParameterTypes(), params);
if (p > bestMatch) {
bestMatch = p;
......@@ -783,7 +799,8 @@ public class Utils {
* @param params the constructor parameters
* @return the newly created object
*/
public static Object newInstance(String className, Object... params) throws Exception {
public static Object newInstance(String className, Object... params)
throws Exception {
Constructor<?> best = null;
int bestMatch = 0;
for (Constructor<?> c : Class.forName(className).getConstructors()) {
......@@ -840,7 +857,8 @@ public class Utils {
* @param fieldName the field name
* @return the field value
*/
public static Object getField(Object instance, String fieldName) throws Exception {
public static Object getField(Object instance, String fieldName)
throws Exception {
return instance.getClass().getField(fieldName).get(instance);
}
......
......@@ -48,10 +48,16 @@ public class BenchA implements Bench {
db.dropTable("ACCOUNTS");
db.dropTable("HISTORY");
String[] create = { "CREATE TABLE BRANCHES(BID INT NOT NULL PRIMARY KEY, BBALANCE DECIMAL(15,2), FILLER VARCHAR(88))",
"CREATE TABLE TELLERS(TID INT NOT NULL PRIMARY KEY, BID INT, TBALANCE DECIMAL(15,2), FILLER VARCHAR(84))",
"CREATE TABLE ACCOUNTS(AID INT NOT NULL PRIMARY KEY, BID INT, ABALANCE DECIMAL(15,2), FILLER VARCHAR(84))",
"CREATE TABLE HISTORY(TID INT, BID INT, AID INT, DELTA DECIMAL(15,2), HTIME DATETIME, FILLER VARCHAR(40))" };
String[] create = {
"CREATE TABLE BRANCHES(BID INT NOT NULL PRIMARY KEY, " +
"BBALANCE DECIMAL(15,2), FILLER VARCHAR(88))",
"CREATE TABLE TELLERS(TID INT NOT NULL PRIMARY KEY, " +
"BID INT, TBALANCE DECIMAL(15,2), FILLER VARCHAR(84))",
"CREATE TABLE ACCOUNTS(AID INT NOT NULL PRIMARY KEY, " +
"BID INT, ABALANCE DECIMAL(15,2), FILLER VARCHAR(84))",
"CREATE TABLE HISTORY(TID INT, " +
"BID INT, AID INT, DELTA DECIMAL(15,2), HTIME DATETIME, " +
"FILLER VARCHAR(40))" };
for (String sql : create) {
db.update(sql);
......@@ -60,7 +66,9 @@ public class BenchA implements Bench {
PreparedStatement prep;
db.setAutoCommit(false);
int commitEvery = 1000;
prep = db.prepare("INSERT INTO BRANCHES(BID,BBALANCE,FILLER) VALUES(?,10000.00,'" + FILLER + "')");
prep = db.prepare(
"INSERT INTO BRANCHES(BID, BBALANCE, FILLER) " +
"VALUES(?, 10000.00, '" + FILLER + "')");
for (int i = 0; i < branches * scale; i++) {
prep.setInt(1, i);
db.update(prep, "insertBranches");
......@@ -69,7 +77,9 @@ public class BenchA implements Bench {
}
}
db.commit();
prep = db.prepare("INSERT INTO TELLERS(TID,BID,TBALANCE,FILLER) VALUES(?,?,10000.00,'" + FILLER + "')");
prep = db.prepare(
"INSERT INTO TELLERS(TID, BID, TBALANCE, FILLER) " +
"VALUES(?, ?, 10000.00, '" + FILLER + "')");
for (int i = 0; i < tellers * scale; i++) {
prep.setInt(1, i);
prep.setInt(2, i / tellers);
......@@ -80,7 +90,9 @@ public class BenchA implements Bench {
}
db.commit();
int len = accounts * scale;
prep = db.prepare("INSERT INTO ACCOUNTS(AID,BID,ABALANCE,FILLER) VALUES(?,?,10000.00,'" + FILLER + "')");
prep = db.prepare(
"INSERT INTO ACCOUNTS(AID, BID, ABALANCE, FILLER) " +
"VALUES(?, ?, 10000.00, '" + FILLER + "')");
for (int i = 0; i < len; i++) {
prep.setInt(1, i);
prep.setInt(2, i / accounts);
......@@ -129,7 +141,8 @@ public class BenchA implements Bench {
PreparedStatement updateBranch = database.prepare(
"UPDATE BRANCHES SET BBALANCE=BBALANCE+? WHERE BID=?");
PreparedStatement insertHistory = database.prepare(
"INSERT INTO HISTORY(AID,TID,BID,DELTA,HTIME,FILLER) VALUES(?,?,?,?,?,?)");
"INSERT INTO HISTORY(AID, TID, BID, DELTA, HTIME, FILLER) " +
"VALUES(?, ?, ?, ?, ?, ?)");
int accountsPerBranch = accounts / branches;
database.setAutoCommit(false);
......
......@@ -74,10 +74,19 @@ public class BenchB implements Bench, Runnable {
db.dropTable("TELLERS");
db.dropTable("ACCOUNTS");
db.dropTable("HISTORY");
String[] create = { "CREATE TABLE BRANCHES(BID INT NOT NULL PRIMARY KEY, BBALANCE INT, FILLER VARCHAR(88))",
"CREATE TABLE TELLERS(TID INT NOT NULL PRIMARY KEY, BID INT, TBALANCE INT, FILLER VARCHAR(84))",
"CREATE TABLE ACCOUNTS(AID INT NOT NULL PRIMARY KEY, BID INT, ABALANCE INT, FILLER VARCHAR(84))",
"CREATE TABLE HISTORY(TID INT, BID INT, AID INT, DELTA INT, TIME DATETIME, FILLER VARCHAR(22))" };
String[] create = {
"CREATE TABLE BRANCHES(" +
"BID INT NOT NULL PRIMARY KEY, " +
"BBALANCE INT, FILLER VARCHAR(88))",
"CREATE TABLE TELLERS(" +
"TID INT NOT NULL PRIMARY KEY, " +
"BID INT, TBALANCE INT, FILLER VARCHAR(84))",
"CREATE TABLE ACCOUNTS(" +
"AID INT NOT NULL PRIMARY KEY, " +
"BID INT, ABALANCE INT, FILLER VARCHAR(84))",
"CREATE TABLE HISTORY(" +
"TID INT, BID INT, AID INT, " +
"DELTA INT, TIME DATETIME, FILLER VARCHAR(22))" };
for (String sql : create) {
db.update(sql);
}
......
......@@ -23,8 +23,9 @@ public class BenchC implements Bench {
private static final int COMMIT_EVERY = 1000;
private static final String[] TABLES = { "WAREHOUSE", "DISTRICT", "CUSTOMER", "HISTORY", "ORDERS",
"NEW_ORDER", "ITEM", "STOCK", "ORDER_LINE", "RESULTS" };
private static final String[] TABLES = { "WAREHOUSE", "DISTRICT",
"CUSTOMER", "HISTORY", "ORDERS", "NEW_ORDER", "ITEM", "STOCK",
"ORDER_LINE", "RESULTS" };
private static final String[] CREATE_SQL = {
"CREATE TABLE WAREHOUSE(\n" +
......
......@@ -26,7 +26,8 @@ public class BenchCThread {
private final Database db;
private final int warehouseId;
private final int terminalId;
private final HashMap<String, PreparedStatement> prepared = new HashMap<String, PreparedStatement>();
private final HashMap<String, PreparedStatement> prepared =
new HashMap<String, PreparedStatement>();
private final BenchCRandom random;
private final BenchC bench;
......
......@@ -95,7 +95,8 @@ class Database {
serverH2 = Server.createTcpServer().start();
Thread.sleep(100);
} else if (url.startsWith("jdbc:derby://")) {
serverDerby = Class.forName("org.apache.derby.drda.NetworkServerControl").newInstance();
serverDerby = Class.forName(
"org.apache.derby.drda.NetworkServerControl").newInstance();
Method m = serverDerby.getClass().getMethod("start", PrintWriter.class);
m.invoke(serverDerby, new Object[] { null });
// serverDerby = new NetworkServerControl();
......@@ -152,7 +153,8 @@ class Database {
* @param threadCount the number of threads to use
* @return a new database object with the given settings
*/
static Database parse(DatabaseTest test, int id, String dbString, int threadCount) {
static Database parse(DatabaseTest test, int id, String dbString,
int threadCount) {
try {
StringTokenizer tokenizer = new StringTokenizer(dbString, ",");
Database db = new Database();
......
......@@ -59,8 +59,10 @@ public class TestPerformance implements Database.DatabaseTest {
try {
conn = getResultConnection();
stat = conn.createStatement();
stat.execute("CREATE TABLE IF NOT EXISTS RESULTS(TESTID INT, TEST VARCHAR, "
+ "UNIT VARCHAR, DBID INT, DB VARCHAR, RESULT VARCHAR)");
stat.execute(
"CREATE TABLE IF NOT EXISTS RESULTS(" +
"TESTID INT, TEST VARCHAR, " +
"UNIT VARCHAR, DBID INT, DB VARCHAR, RESULT VARCHAR)");
} finally {
JdbcUtils.closeSilently(stat);
JdbcUtils.closeSilently(conn);
......@@ -128,8 +130,9 @@ public class TestPerformance implements Database.DatabaseTest {
openResults();
conn = getResultConnection();
stat = conn.createStatement();
prep = conn
.prepareStatement("INSERT INTO RESULTS(TESTID, TEST, UNIT, DBID, DB, RESULT) VALUES(?, ?, ?, ?, ?, ?)");
prep = conn.prepareStatement(
"INSERT INTO RESULTS(TESTID, TEST, " +
"UNIT, DBID, DB, RESULT) VALUES(?, ?, ?, ?, ?, ?)");
for (int i = 0; i < results.size(); i++) {
Object[] res = results.get(i);
prep.setInt(1, i);
......@@ -146,15 +149,19 @@ public class TestPerformance implements Database.DatabaseTest {
writer = new PrintWriter(new FileWriter(out));
ResultSet rs = stat.executeQuery(
"CALL '<table><tr><th>Test Case</th><th>Unit</th>' "
+"|| SELECT GROUP_CONCAT('<th>' || DB || '</th>' ORDER BY DBID SEPARATOR '') FROM "
+"(SELECT DISTINCT DBID, DB FROM RESULTS)"
+"|| '</tr>' || CHAR(10) "
+"|| SELECT GROUP_CONCAT('<tr><td>' || TEST || '</td><td>' || UNIT || '</td>' || ( "
+"SELECT GROUP_CONCAT('<td>' || RESULT || '</td>' ORDER BY DBID SEPARATOR '') FROM RESULTS R2 WHERE "
+"R2.TESTID = R1.TESTID) || '</tr>' ORDER BY TESTID SEPARATOR CHAR(10)) FROM "
+"(SELECT DISTINCT TESTID, TEST, UNIT FROM RESULTS) R1"
+"|| '</table>'"
"CALL '<table><tr><th>Test Case</th><th>Unit</th>' " +
"|| SELECT GROUP_CONCAT('<th>' || DB || '</th>' " +
"ORDER BY DBID SEPARATOR '') FROM " +
"(SELECT DISTINCT DBID, DB FROM RESULTS)" +
"|| '</tr>' || CHAR(10) " +
"|| SELECT GROUP_CONCAT('<tr><td>' || TEST || " +
"'</td><td>' || UNIT || '</td>' || ( " +
"SELECT GROUP_CONCAT('<td>' || RESULT || '</td>' " +
"ORDER BY DBID SEPARATOR '') FROM RESULTS R2 WHERE " +
"R2.TESTID = R1.TESTID) || '</tr>' " +
"ORDER BY TESTID SEPARATOR CHAR(10)) FROM " +
"(SELECT DISTINCT TESTID, TEST, UNIT FROM RESULTS) R1" +
"|| '</table>'"
);
rs.next();
String result = rs.getString(1);
......@@ -211,7 +218,8 @@ public class TestPerformance implements Database.DatabaseTest {
}
}
private void testAll(ArrayList<Database> dbs, ArrayList<Bench> tests, int size) throws Exception {
private void testAll(ArrayList<Database> dbs, ArrayList<Bench> tests,
int size) throws Exception {
for (int i = 0; i < dbs.size(); i++) {
if (i > 0) {
Thread.sleep(1000);
......@@ -224,7 +232,8 @@ public class TestPerformance implements Database.DatabaseTest {
db.startServer();
Connection conn = db.openNewConnection();
DatabaseMetaData meta = conn.getMetaData();
System.out.println(" " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion());
System.out.println(" " + meta.getDatabaseProductName() + " " +
meta.getDatabaseProductVersion());
runDatabase(db, tests, 1);
runDatabase(db, tests, 1);
collect = true;
......@@ -240,13 +249,15 @@ public class TestPerformance implements Database.DatabaseTest {
}
}
private static void runDatabase(Database db, ArrayList<Bench> tests, int size) throws Exception {
private static void runDatabase(Database db, ArrayList<Bench> tests,
int size) throws Exception {
for (Bench bench : tests) {
runTest(db, bench, size);
}
}
private static void runTest(Database db, Bench bench, int size) throws Exception {
private static void runTest(Database db, Bench bench, int size)
throws Exception {
bench.init(db, size);
bench.runTest();
}
......
......@@ -56,8 +56,10 @@ public class TestScalability implements Database.DatabaseTest {
try {
conn = getResultConnection();
stat = conn.createStatement();
stat.execute("CREATE TABLE IF NOT EXISTS RESULTS(TESTID INT, TEST VARCHAR, "
+ "UNIT VARCHAR, DBID INT, DB VARCHAR, RESULT VARCHAR)");
stat.execute(
"CREATE TABLE IF NOT EXISTS RESULTS(TESTID INT, " +
"TEST VARCHAR, UNIT VARCHAR, DBID INT, " +
"DB VARCHAR, RESULT VARCHAR)");
} finally {
JdbcUtils.closeSilently(stat);
JdbcUtils.closeSilently(conn);
......@@ -72,7 +74,8 @@ public class TestScalability implements Database.DatabaseTest {
ArrayList<Database> dbs = new ArrayList<Database>();
int id = 1;
final String h2Url = "jdbc:h2:data/test;LOCK_TIMEOUT=10000;LOCK_MODE=3";
final String h2Url = "jdbc:h2:data/test;" +
"LOCK_TIMEOUT=10000;LOCK_MODE=3";
dbs.add(createDbEntry(id++, "H2", 1, h2Url));
dbs.add(createDbEntry(id++, "H2", 10, h2Url));
dbs.add(createDbEntry(id++, "H2", 20, h2Url));
......@@ -81,7 +84,8 @@ public class TestScalability implements Database.DatabaseTest {
dbs.add(createDbEntry(id++, "H2", 50, h2Url));
dbs.add(createDbEntry(id++, "H2", 100, h2Url));
final String mvUrl = "jdbc:h2:data/mvTest;LOCK_TIMEOUT=10000;MV_STORE=TRUE";
final String mvUrl = "jdbc:h2:data/mvTest;" +
"LOCK_TIMEOUT=10000;MV_STORE=TRUE";
dbs.add(createDbEntry(id++, "MV", 1, mvUrl));
dbs.add(createDbEntry(id++, "MV", 10, mvUrl));
dbs.add(createDbEntry(id++, "MV", 20, mvUrl));
......@@ -103,8 +107,9 @@ public class TestScalability implements Database.DatabaseTest {
openResults();
conn = getResultConnection();
stat = conn.createStatement();
prep = conn
.prepareStatement("INSERT INTO RESULTS(TESTID, TEST, UNIT, DBID, DB, RESULT) VALUES(?, ?, ?, ?, ?, ?)");
prep = conn.prepareStatement(
"INSERT INTO RESULTS(TESTID, " +
"TEST, UNIT, DBID, DB, RESULT) VALUES(?, ?, ?, ?, ?, ?)");
for (int i = 0; i < results.size(); i++) {
Object[] res = results.get(i);
prep.setInt(1, i);
......@@ -120,15 +125,21 @@ public class TestScalability implements Database.DatabaseTest {
}
writer = new PrintWriter(new FileWriter(out));
ResultSet rs = stat
.executeQuery("CALL '<table><tr><th>Test Case</th><th>Unit</th>' "
+ "|| SELECT GROUP_CONCAT('<th>' || DB || '</th>' ORDER BY DBID SEPARATOR '') FROM "
+ "(SELECT DISTINCT DBID, DB FROM RESULTS)"
+ "|| '</tr>' || CHAR(10) "
+ "|| SELECT GROUP_CONCAT('<tr><td>' || TEST || '</td><td>' || UNIT || '</td>' || ( "
+ "SELECT GROUP_CONCAT('<td>' || RESULT || '</td>' ORDER BY DBID SEPARATOR '') FROM RESULTS R2 WHERE "
+ "R2.TESTID = R1.TESTID) || '</tr>' ORDER BY TESTID SEPARATOR CHAR(10)) FROM "
+ "(SELECT DISTINCT TESTID, TEST, UNIT FROM RESULTS) R1" + "|| '</table>'");
ResultSet rs = stat.executeQuery(
"CALL '<table><tr><th>Test Case</th>" +
"<th>Unit</th>' " +
"|| SELECT GROUP_CONCAT('<th>' || DB || '</th>' " +
"ORDER BY DBID SEPARATOR '') FROM " +
"(SELECT DISTINCT DBID, DB FROM RESULTS)" +
"|| '</tr>' || CHAR(10) " +
"|| SELECT GROUP_CONCAT('<tr><td>' || " +
"TEST || '</td><td>' || UNIT || '</td>' || ( " +
"SELECT GROUP_CONCAT('<td>' || RESULT || '</td>' " +
"ORDER BY DBID SEPARATOR '') FROM RESULTS R2 WHERE " +
"R2.TESTID = R1.TESTID) || '</tr>' " +
"ORDER BY TESTID SEPARATOR CHAR(10)) FROM " +
"(SELECT DISTINCT TESTID, TEST, UNIT FROM RESULTS) R1" +
"|| '</table>'");
rs.next();
String result = rs.getString(1);
writer.println(result);
......@@ -144,14 +155,16 @@ public class TestScalability implements Database.DatabaseTest {
}
}
private Database createDbEntry(int id, String namePrefix, int threadCount, String url) {
Database db = Database.parse(this, id,
namePrefix + "(" + threadCount + "threads), org.h2.Driver, " + url + ", sa, sa", threadCount);
private Database createDbEntry(int id, String namePrefix,
int threadCount, String url) {
Database db = Database.parse(this, id, namePrefix + "(" + threadCount +
"threads), org.h2.Driver, " + url + ", sa, sa", threadCount);
return db;
}
private void testAll(ArrayList<Database> dbs, BenchB test, int size) throws Exception {
private void testAll(ArrayList<Database> dbs, BenchB test, int size)
throws Exception {
for (int i = 0; i < dbs.size(); i++) {
if (i > 0) {
Thread.sleep(1000);
......@@ -163,7 +176,8 @@ public class TestScalability implements Database.DatabaseTest {
db.startServer();
Connection conn = db.openNewConnection();
DatabaseMetaData meta = conn.getMetaData();
System.out.println(" " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion());
System.out.println(" " + meta.getDatabaseProductName() + " " +
meta.getDatabaseProductVersion());
runDatabase(db, test, 1);
runDatabase(db, test, 1);
collect = true;
......@@ -171,7 +185,8 @@ public class TestScalability implements Database.DatabaseTest {
conn.close();
db.log("Executed statements", "#", db.getExecutedStatements());
db.log("Total time", "ms", db.getTotalTime());
int statPerSec = (int) (db.getExecutedStatements() * 1000L / db.getTotalTime());
int statPerSec = (int) (db.getExecutedStatements() *
1000L / db.getTotalTime());
db.log("Statements per second", "#", statPerSec);
System.out.println("Statements per second: " + statPerSec);
collect = false;
......@@ -179,7 +194,8 @@ public class TestScalability implements Database.DatabaseTest {
}
}
private static void runDatabase(Database db, BenchB bench, int size) throws Exception {
private static void runDatabase(Database db, BenchB bench, int size)
throws Exception {
bench.init(db, size);
bench.setThreadCount(db.getThreadsCount());
bench.runTest();
......
......@@ -51,7 +51,8 @@ public class TestMultiThreadedKernel extends TestBase {
testConcurrentRead();
testCache();
deleteDb("multiThreadedKernel");
final String url = getURL("multiThreadedKernel;DB_CLOSE_DELAY=-1;MULTI_THREADED=1", true);
final String url = getURL("multiThreadedKernel;" +
"DB_CLOSE_DELAY=-1;MULTI_THREADED=1", true);
final String user = getUser(), password = getPassword();
int len = 3;
Thread[] threads = new Thread[len];
......@@ -64,8 +65,10 @@ public class TestMultiThreadedKernel extends TestBase {
for (int j = 0; j < 100 && !stop; j++) {
conn = DriverManager.getConnection(url, user, password);
Statement stat = conn.createStatement();
stat.execute("create local temporary table temp(id identity)");
stat.execute("insert into temp values(1)");
stat.execute(
"create local temporary table temp(id identity)");
stat.execute(
"insert into temp values(1)");
conn.close();
}
} catch (Exception e) {
......
......@@ -49,7 +49,8 @@ public class Player {
// TODO support Map
// TODO support SQLXML
private static final String[] IMPORTED_PACKAGES = { "", "java.lang.", "java.sql.", "javax.sql." };
private static final String[] IMPORTED_PACKAGES = {
"", "java.lang.", "java.sql.", "javax.sql." };
private boolean trace;
private final HashMap<String, Object> objects = New.hashMap();
......
......@@ -64,16 +64,21 @@ public class TestAutoReconnect extends TestBase {
deleteDb("autoReconnect");
Server tcp = Server.createTcpServer().start();
try {
conn = getConnection("jdbc:h2:" + getBaseDir() + "/autoReconnect;AUTO_SERVER=TRUE");
conn = getConnection("jdbc:h2:" + getBaseDir() +
"/autoReconnect;AUTO_SERVER=TRUE");
assertThrows(ErrorCode.DATABASE_ALREADY_OPEN_1, this).
getConnection("jdbc:h2:" + getBaseDir() + "/autoReconnect;OPEN_NEW=TRUE");
getConnection("jdbc:h2:" + getBaseDir() +
"/autoReconnect;OPEN_NEW=TRUE");
assertThrows(ErrorCode.DATABASE_ALREADY_OPEN_1, this).
getConnection("jdbc:h2:" + getBaseDir() + "/autoReconnect;OPEN_NEW=TRUE");
getConnection("jdbc:h2:" + getBaseDir() +
"/autoReconnect;OPEN_NEW=TRUE");
conn.close();
conn = getConnection("jdbc:h2:tcp://localhost/" + getBaseDir() + "/autoReconnect");
conn = getConnection("jdbc:h2:tcp://localhost/" + getBaseDir() +
"/autoReconnect");
assertThrows(ErrorCode.DATABASE_ALREADY_OPEN_1, this).
getConnection("jdbc:h2:" + getBaseDir() + "/autoReconnect;AUTO_SERVER=TRUE;OPEN_NEW=TRUE");
getConnection("jdbc:h2:" + getBaseDir() +
"/autoReconnect;AUTO_SERVER=TRUE;OPEN_NEW=TRUE");
conn.close();
} finally {
tcp.stop();
......@@ -94,7 +99,8 @@ public class TestAutoReconnect extends TestBase {
}
// test the database event listener
conn = getConnection(url + ";DATABASE_EVENT_LISTENER='" + MyDatabaseEventListener.class.getName() + "'");
conn = getConnection(url + ";DATABASE_EVENT_LISTENER='" +
MyDatabaseEventListener.class.getName() + "'");
conn.close();
Statement stat;
......@@ -105,7 +111,8 @@ public class TestAutoReconnect extends TestBase {
restart();
stat.execute("create table test(id identity, name varchar)");
restart();
PreparedStatement prep = conn.prepareStatement("insert into test values(null, ?)");
PreparedStatement prep = conn.prepareStatement(
"insert into test values(null, ?)");
restart();
prep.setString(1, "Hello");
restart();
......
......@@ -81,10 +81,17 @@ public class TestBnf extends TestBase {
private void testProcedures(Connection conn, boolean isMySQLMode) throws Exception {
// Register a procedure and check if it is present in DbContents
conn.createStatement().execute("DROP ALIAS IF EXISTS CUSTOM_PRINT");
conn.createStatement().execute("CREATE ALIAS CUSTOM_PRINT AS $$ void print(String s) { System.out.println(s); } $$");
conn.createStatement().execute("DROP TABLE IF EXISTS TABLE_WITH_STRING_FIELD");
conn.createStatement().execute("CREATE TABLE TABLE_WITH_STRING_FIELD (STRING_FIELD VARCHAR(50), INT_FIELD integer)");
conn.createStatement().execute(
"DROP ALIAS IF EXISTS CUSTOM_PRINT");
conn.createStatement().execute(
"CREATE ALIAS CUSTOM_PRINT " +
"AS $$ void print(String s) { System.out.println(s); } $$");
conn.createStatement().execute(
"DROP TABLE IF EXISTS " +
"TABLE_WITH_STRING_FIELD");
conn.createStatement().execute(
"CREATE TABLE " +
"TABLE_WITH_STRING_FIELD (STRING_FIELD VARCHAR(50), INT_FIELD integer)");
DbContents dbContents = new DbContents();
dbContents.readContents("jdbc:h2:test", conn);
assertTrue(dbContents.isH2());
......@@ -126,9 +133,11 @@ public class TestBnf extends TestBase {
// Test completion
Bnf bnf = Bnf.getInstance(null);
DbContextRule columnRule = new DbContextRule(dbContents, DbContextRule.COLUMN);
DbContextRule columnRule = new
DbContextRule(dbContents, DbContextRule.COLUMN);
bnf.updateTopic("column_name", columnRule);
bnf.updateTopic("expression", new DbContextRule(dbContents, DbContextRule.PROCEDURE));
bnf.updateTopic("expression", new
DbContextRule(dbContents, DbContextRule.PROCEDURE));
bnf.linkStatements();
// Test partial
Map<String, String> tokens = bnf.getNextTokenList("SELECT CUSTOM_PR");
......
......@@ -84,12 +84,14 @@ public class TestCache extends TestBase implements CacheWriter {
}
private void testTQ(String cacheType, boolean scanResistant) throws Exception {
Connection conn = getConnection("cache;CACHE_TYPE=" + cacheType + ";CACHE_SIZE=4096");
Connection conn = getConnection(
"cache;CACHE_TYPE=" + cacheType + ";CACHE_SIZE=4096");
Statement stat = conn.createStatement();
PreparedStatement prep;
for (int k = 0; k < 10; k++) {
int rc;
prep = conn.prepareStatement("select * from test where id = ?");
prep = conn.prepareStatement(
"select * from test where id = ?");
rc = getReadCount(stat);
for (int x = 0; x < 2; x++) {
for (int i = 0; i < 15000; i++) {
......@@ -106,7 +108,8 @@ public class TestCache extends TestBase implements CacheWriter {
assertTrue(rcData > 0);
}
rc = getReadCount(stat);
ResultSet rs = stat.executeQuery("select * from lob where id = " + k);
ResultSet rs = stat.executeQuery(
"select * from lob where id = " + k);
rs.next();
InputStream in = rs.getBinaryStream(2);
while (in.read() >= 0) {
......@@ -121,7 +124,9 @@ public class TestCache extends TestBase implements CacheWriter {
private static int getReadCount(Statement stat) throws Exception {
ResultSet rs;
rs = stat.executeQuery("select value from information_schema.settings where name = 'info.FILE_READ'");
rs = stat.executeQuery(
"select value from information_schema.settings " +
"where name = 'info.FILE_READ'");
rs.next();
return rs.getInt(1);
}
......@@ -152,12 +157,16 @@ public class TestCache extends TestBase implements CacheWriter {
// -XX:+HeapDumpOnOutOfMemoryError
stat.execute("insert into test select x, random_uuid() || space(1) from system_range(1, 10000)");
stat.execute(
"insert into test select x, random_uuid() || space(1) " +
"from system_range(1, 10000)");
// stat.execute("create index idx_test_n on test(data)");
// stat.execute("select data from test where data >= ''");
rs = stat.executeQuery("select value from information_schema.settings where name = 'info.CACHE_SIZE'");
rs = stat.executeQuery(
"select value from information_schema.settings " +
"where name = 'info.CACHE_SIZE'");
rs.next();
int calculated = rs.getInt(1);
rs = null;
......@@ -167,8 +176,10 @@ public class TestCache extends TestBase implements CacheWriter {
stat = null;
conn = null;
long afterClose = getRealMemory();
trace("Used memory: " + (afterInsert - afterClose) + " calculated cache size: " + calculated);
trace("Before: " + before + " after: " + afterInsert + " after closing: " + afterClose);
trace("Used memory: " + (afterInsert - afterClose) +
" calculated cache size: " + calculated);
trace("Before: " + before + " after: " + afterInsert +
" after closing: " + afterClose);
}
private int getRealMemory() {
......@@ -240,13 +251,16 @@ public class TestCache extends TestBase implements CacheWriter {
return;
}
deleteDb("cache");
Connection conn = getConnection("cache;CACHE_TYPE=" + (lru ? "LRU" : "SOFT_LRU"));
Connection conn = getConnection(
"cache;CACHE_TYPE=" + (lru ? "LRU" : "SOFT_LRU"));
Statement stat = conn.createStatement();
stat.execute("SET CACHE_SIZE 1024");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
stat.execute("CREATE TABLE MAIN(ID INT PRIMARY KEY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
PreparedStatement prep2 = conn.prepareStatement("INSERT INTO MAIN VALUES(?, ?)");
PreparedStatement prep = conn.prepareStatement(
"INSERT INTO TEST VALUES(?, ?)");
PreparedStatement prep2 = conn.prepareStatement(
"INSERT INTO MAIN VALUES(?, ?)");
int max = 10000;
for (int i = 0; i < max; i++) {
prep.setInt(1, i);
......
......@@ -63,8 +63,10 @@ public class TestClassLoaderLeak extends TestBase {
memory.add(new byte[1024]);
}
}
DriverManager.registerDriver((Driver) Class.forName("org.h2.Driver").newInstance());
DriverManager.registerDriver((Driver) Class.forName("org.h2.upgrade.v1_1.Driver").newInstance());
DriverManager.registerDriver((Driver)
Class.forName("org.h2.Driver").newInstance());
DriverManager.registerDriver((Driver)
Class.forName("org.h2.upgrade.v1_1.Driver").newInstance());
}
private static WeakReference<ClassLoader> createClassLoader() throws Exception {
......@@ -98,13 +100,14 @@ public class TestClassLoaderLeak extends TestBase {
private static class TestClassLoader extends URLClassLoader {
public TestClassLoader() {
super(((URLClassLoader) TestClassLoader.class.getClassLoader()).getURLs(), ClassLoader
.getSystemClassLoader());
super(((URLClassLoader) TestClassLoader.class.getClassLoader())
.getURLs(), ClassLoader.getSystemClassLoader());
}
// allows delegation of H2 to the AppClassLoader
@Override
public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
public synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
if (!name.contains(CLASS_NAME) && !name.startsWith("org.h2.")) {
return super.loadClass(name, resolve);
}
......
......@@ -149,7 +149,8 @@ public class TestCompress extends TestBase {
while (rs.next()) {
String table = rs.getString(1);
if (!"COLLATIONS".equals(table)) {
stat2.execute("create table " + table + " as select * from information_schema." + table);
stat2.execute("create table " + table +
" as select * from information_schema." + table);
}
}
conn.close();
......@@ -240,12 +241,14 @@ public class TestCompress extends TestBase {
}
CompressTool utils = CompressTool.getInstance();
// level 9 is highest, strategy 2 is huffman only
for (String a : new String[] { "LZF", "No", "Deflate", "Deflate level 9 strategy 2" }) {
for (String a : new String[] { "LZF", "No",
"Deflate", "Deflate level 9 strategy 2" }) {
long time = System.currentTimeMillis();
byte[] out = utils.compress(b, a);
byte[] test = utils.expand(out);
if (testPerformance) {
System.out.println("p:" + pattern + " len: " + out.length + " time: " + (System.currentTimeMillis() - time) + " " + a);
System.out.println("p:" + pattern + " len: " + out.length +
" time: " + (System.currentTimeMillis() - time) + " " + a);
}
assertEquals(b.length, test.length);
assertEquals(b, test);
......
......@@ -52,20 +52,28 @@ public class TestConnectionInfo extends TestBase {
";IFEXISTS=TRUE",
info);
assertEquals("jdbc:h2:mem:test", connectionInfo.getURL());
assertEquals("jdbc:h2:mem:test",
connectionInfo.getURL());
assertEquals("2", connectionInfo.getProperty("LOG", ""));
assertEquals("rws", connectionInfo.getProperty("ACCESS_MODE_DATA", ""));
assertEquals("CREATE this...;INSERT that...", connectionInfo.getProperty("INIT", ""));
assertEquals("TRUE", connectionInfo.getProperty("IFEXISTS", ""));
assertEquals("undefined", connectionInfo.getProperty("CACHE_TYPE", "undefined"));
assertEquals("2",
connectionInfo.getProperty("LOG", ""));
assertEquals("rws",
connectionInfo.getProperty("ACCESS_MODE_DATA", ""));
assertEquals("CREATE this...;INSERT that...",
connectionInfo.getProperty("INIT", ""));
assertEquals("TRUE",
connectionInfo.getProperty("IFEXISTS", ""));
assertEquals("undefined",
connectionInfo.getProperty("CACHE_TYPE", "undefined"));
}
private void testName() throws Exception {
char differentFileSeparator = File.separatorChar == '/' ? '\\' : '/';
ConnectionInfo connectionInfo = new ConnectionInfo("test" + differentFileSeparator + "subDir");
ConnectionInfo connectionInfo = new ConnectionInfo("test" +
differentFileSeparator + "subDir");
File file = new File("test" + File.separatorChar + "subDir");
assertEquals(file.getCanonicalPath().replace('\\', '/'), connectionInfo.getName());
assertEquals(file.getCanonicalPath().replace('\\', '/'),
connectionInfo.getName());
}
}
......@@ -200,8 +200,8 @@ public class TestDataPage extends TestBase implements DataHandler {
}
}
testValue(ValueArray.get(new Value[0]));
testValue(ValueArray.get(new Value[] {ValueBoolean.get(true), ValueInt.get(10)}));
testValue(ValueArray.get(new Value[] { ValueBoolean.get(true),
ValueInt.get(10) }));
SimpleResultSet rs = new SimpleResultSet();
rs.setAutoClose(false);
......@@ -332,7 +332,8 @@ public class TestDataPage extends TestBase implements DataHandler {
}
@Override
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff, int off, int length) {
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff,
int off, int length) {
return -1;
}
......
......@@ -19,7 +19,8 @@ import org.h2.util.DateTimeUtils;
*/
public class TestDateIso8601 extends TestBase {
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
private final SimpleDateFormat dateFormatter =
new SimpleDateFormat("yyyy-MM-dd");
/**
* Run just this test.
......
......@@ -17,14 +17,14 @@ import org.h2.test.TestBase;
import org.h2.test.utils.SelfDestructor;
/**
* Tests the flag db_close_on_exit.
* A new process is started.
* Tests the flag db_close_on_exit. A new process is started.
*/
public class TestExit extends TestBase {
private static Connection conn;
private static final int OPEN_WITH_CLOSE_ON_EXIT = 1, OPEN_WITHOUT_CLOSE_ON_EXIT = 2;
private static final int OPEN_WITH_CLOSE_ON_EXIT = 1,
OPEN_WITHOUT_CLOSE_ON_EXIT = 2;
@Override
public void test() throws Exception {
......@@ -37,8 +37,7 @@ public class TestExit extends TestBase {
deleteDb("exit");
String url = getURL(OPEN_WITH_CLOSE_ON_EXIT);
String selfDestruct = SelfDestructor.getPropertyString(60);
String[] procDef = { "java", selfDestruct,
"-cp", getClassPath(),
String[] procDef = { "java", selfDestruct, "-cp", getClassPath(),
getClass().getName(), url };
Process proc = Runtime.getRuntime().exec(procDef);
while (true) {
......@@ -61,9 +60,8 @@ public class TestExit extends TestBase {
fail("did not close database");
}
url = getURL(OPEN_WITHOUT_CLOSE_ON_EXIT);
procDef = new String[] { "java",
"-cp", getClassPath(), getClass().getName(),
url };
procDef = new String[] { "java", "-cp", getClassPath(),
getClass().getName(), url };
proc = Runtime.getRuntime().exec(procDef);
proc.waitFor();
Thread.sleep(100);
......@@ -77,12 +75,16 @@ public class TestExit extends TestBase {
String url = "";
switch (action) {
case OPEN_WITH_CLOSE_ON_EXIT:
url = "jdbc:h2:" + getBaseDir() + "/exit;database_event_listener='" + MyDatabaseEventListener.class.getName()
+ "';db_close_on_exit=true";
url = "jdbc:h2:" + getBaseDir() +
"/exit;database_event_listener='" +
MyDatabaseEventListener.class.getName() +
"';db_close_on_exit=true";
break;
case OPEN_WITHOUT_CLOSE_ON_EXIT:
url = "jdbc:h2:" + getBaseDir() + "/exit;database_event_listener='" + MyDatabaseEventListener.class.getName()
+ "';db_close_on_exit=false";
url = "jdbc:h2:" + getBaseDir() +
"/exit;database_event_listener='" +
MyDatabaseEventListener.class.getName() +
"';db_close_on_exit=false";
break;
default:
}
......@@ -93,7 +95,7 @@ public class TestExit extends TestBase {
/**
* This method is called when executing this application from the command
* line.
*
*
* @param args the command line parameters
*/
public static void main(String... args) throws SQLException {
......@@ -126,7 +128,8 @@ public class TestExit extends TestBase {
/**
* A database event listener used in this test.
*/
public static final class MyDatabaseEventListener implements DatabaseEventListener {
public static final class MyDatabaseEventListener implements
DatabaseEventListener {
@Override
public void exceptionThrown(SQLException e, String sql) {
......
......@@ -24,7 +24,7 @@ public class TestFile extends TestBase implements DataHandler {
/**
* Run just this test.
*
*
* @param a ignored
*/
public static void main(String... a) throws Exception {
......@@ -45,7 +45,8 @@ public class TestFile extends TestBase implements DataHandler {
FileStore mem = null, file = null;
byte[] buffMem = null;
byte[] buffFile = null;
String prefix = nioMem ? (compress ? "nioMemLZF:" : "nioMemFS:") : (compress ? "memLZF:" : "memFS:");
String prefix = nioMem ? (compress ? "nioMemLZF:" : "nioMemFS:")
: (compress ? "memLZF:" : "memFS:");
FileUtils.delete(prefix + "test");
FileUtils.delete("~/testFile");
......@@ -91,7 +92,8 @@ public class TestFile extends TestBase implements DataHandler {
if (buffFile.length > 16) {
int off = random.nextInt(buffFile.length - 16);
int l = random.nextInt((buffFile.length - off) / 16) * 16;
l = (int) Math.min(l, file.length() - file.getFilePointer());
l = (int) Math
.min(l, file.length() - file.getFilePointer());
trace("read " + off + " " + l);
Exception a = null, b = null;
try {
......@@ -186,7 +188,8 @@ public class TestFile extends TestBase implements DataHandler {
}
@Override
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff, int off, int length) {
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff,
int off, int length) {
return -1;
}
......
......@@ -15,8 +15,8 @@ import org.h2.store.FileLock;
import org.h2.test.TestBase;
/**
* Tests the database file locking facility.
* Both lock files and sockets locking is tested.
* Tests the database file locking facility. Both lock files and sockets locking
* is tested.
*/
public class TestFileLock extends TestBase implements Runnable {
......@@ -41,7 +41,7 @@ public class TestFileLock extends TestBase implements Runnable {
/**
* Run just this test.
*
*
* @param a ignored
*/
public static void main(String... a) throws Exception {
......@@ -62,10 +62,11 @@ public class TestFileLock extends TestBase implements Runnable {
private void testFsFileLock() throws Exception {
deleteDb("fileLock");
String url = "jdbc:h2:" + getBaseDir() + "/fileLock;FILE_LOCK=FS;OPEN_NEW=TRUE";
String url = "jdbc:h2:" + getBaseDir() +
"/fileLock;FILE_LOCK=FS;OPEN_NEW=TRUE";
Connection conn = getConnection(url);
assertThrows(ErrorCode.DATABASE_ALREADY_OPEN_1, this).
getConnection(url);
assertThrows(ErrorCode.DATABASE_ALREADY_OPEN_1, this)
.getConnection(url);
conn.close();
}
......@@ -74,20 +75,24 @@ public class TestFileLock extends TestBase implements Runnable {
f.delete();
f.createNewFile();
f.setLastModified(System.currentTimeMillis() + 10000);
FileLock lock = new FileLock(new TraceSystem(null), getFile(), Constants.LOCK_SLEEP);
FileLock lock = new FileLock(new TraceSystem(null), getFile(),
Constants.LOCK_SLEEP);
lock.lock(FileLock.LOCK_FILE);
lock.unlock();
}
private void testSimple() {
FileLock lock1 = new FileLock(new TraceSystem(null), getFile(), Constants.LOCK_SLEEP);
FileLock lock2 = new FileLock(new TraceSystem(null), getFile(), Constants.LOCK_SLEEP);
FileLock lock1 = new FileLock(new TraceSystem(null), getFile(),
Constants.LOCK_SLEEP);
FileLock lock2 = new FileLock(new TraceSystem(null), getFile(),
Constants.LOCK_SLEEP);
lock1.lock(FileLock.LOCK_FILE);
createClassProxy(FileLock.class);
assertThrows(ErrorCode.DATABASE_ALREADY_OPEN_1, lock2).
lock(FileLock.LOCK_FILE);
assertThrows(ErrorCode.DATABASE_ALREADY_OPEN_1, lock2).lock(
FileLock.LOCK_FILE);
lock1.unlock();
lock2 = new FileLock(new TraceSystem(null), getFile(), Constants.LOCK_SLEEP);
lock2 = new FileLock(new TraceSystem(null), getFile(),
Constants.LOCK_SLEEP);
lock2.lock(FileLock.LOCK_FILE);
lock2.unlock();
}
......@@ -118,11 +123,13 @@ public class TestFileLock extends TestBase implements Runnable {
while (!stop) {
lock = new FileLock(new TraceSystem(null), getFile(), 100);
try {
lock.lock(allowSockets ? FileLock.LOCK_SOCKET : FileLock.LOCK_FILE);
lock.lock(allowSockets ? FileLock.LOCK_SOCKET
: FileLock.LOCK_FILE);
base.trace(lock + " locked");
locks++;
if (locks > 1) {
System.err.println("ERROR! LOCKS=" + locks + " sockets=" + allowSockets);
System.err.println("ERROR! LOCKS=" + locks + " sockets=" +
allowSockets);
stop = true;
}
Thread.sleep(wait + (int) (Math.random() * wait));
......
......@@ -271,12 +271,16 @@ public class TestFileSystem extends TestBase {
deleteDb("fsMem");
String url = "jdbc:h2:" + getBaseDir() + "/fsMem";
Connection conn = getConnection(url, "sa", "sa");
conn.createStatement().execute("CREATE TABLE TEST AS SELECT * FROM DUAL");
conn.createStatement().execute("BACKUP TO '" + getBaseDir() + "/fsMem.zip'");
conn.createStatement().execute(
"CREATE TABLE TEST AS SELECT * FROM DUAL");
conn.createStatement().execute(
"BACKUP TO '" + getBaseDir() + "/fsMem.zip'");
conn.close();
org.h2.tools.Restore.main("-file", getBaseDir() + "/fsMem.zip", "-dir", "memFS:");
org.h2.tools.Restore.main("-file", getBaseDir() + "/fsMem.zip", "-dir",
"memFS:");
conn = getConnection("jdbc:h2:memFS:fsMem", "sa", "sa");
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
ResultSet rs = conn.createStatement()
.executeQuery("SELECT * FROM TEST");
rs.close();
conn.close();
deleteDb("fsMem");
......@@ -294,8 +298,10 @@ public class TestFileSystem extends TestBase {
String url = "jdbc:h2:" + getBaseDir() + "/fsJar";
Connection conn = getConnection(url, "sa", "sa");
Statement stat = conn.createStatement();
stat.execute("create table test(id int primary key, name varchar, b blob, c clob)");
stat.execute("insert into test values(1, 'Hello', SECURE_RAND(2000), space(2000))");
stat.execute("create table test(id int primary key, " +
"name varchar, b blob, c clob)");
stat.execute("insert into test values(1, 'Hello', " +
"SECURE_RAND(2000), space(2000))");
ResultSet rs;
rs = stat.executeQuery("select * from test");
rs.next();
......@@ -308,7 +314,8 @@ public class TestFileSystem extends TestBase {
conn.close();
deleteDb("fsJar");
for (String f : FileUtils.newDirectoryStream("zip:" + getBaseDir() + "/fsJar.zip")) {
for (String f : FileUtils.newDirectoryStream(
"zip:" + getBaseDir() + "/fsJar.zip")) {
assertFalse(FileUtils.isAbsolute(f));
assertTrue(!FileUtils.isDirectory(f));
assertTrue(FileUtils.size(f) > 0);
......@@ -735,7 +742,8 @@ public class TestFileSystem extends TestBase {
}
}
private static ByteBuffer createSlicedBuffer(byte[] buffer, int offset, int len) {
private static ByteBuffer createSlicedBuffer(byte[] buffer, int offset,
int len) {
ByteBuffer byteBuff = ByteBuffer.wrap(buffer);
byteBuff.position(offset);
// force the arrayOffset to be non-0
......
......@@ -41,7 +41,8 @@ public class TestFtp extends TestBase implements FtpEventListener {
}
private void test(String dir) throws Exception {
Server server = FtpServer.createFtpServer("-ftpDir", dir, "-ftpPort", "8121").start();
Server server = FtpServer.createFtpServer(
"-ftpDir", dir, "-ftpPort", "8121").start();
FtpServer ftp = (FtpServer) server.getService();
ftp.setEventListener(this);
FtpClient client = FtpClient.open("localhost:8121");
......
......@@ -54,7 +54,8 @@ public class TestIntIntHashMap extends TestBase {
}
for (int i = 0; i < len; i++) {
if (map.get(x[i]) != i) {
throw new AssertionError("get " + x[i] + " = " + map.get(i) + " should be " + i);
throw new AssertionError("get " + x[i] + " = " + map.get(i) +
" should be " + i);
}
}
for (int i = 1; i < len; i += 2) {
......@@ -62,7 +63,8 @@ public class TestIntIntHashMap extends TestBase {
}
for (int i = 1; i < len; i += 2) {
if (map.get(x[i]) != -1) {
throw new AssertionError("get " + x[i] + " = " + map.get(i) + " should be <=0");
throw new AssertionError("get " + x[i] + " = " + map.get(i) +
" should be <=0");
}
}
for (int i = 1; i < len; i += 2) {
......@@ -70,7 +72,8 @@ public class TestIntIntHashMap extends TestBase {
}
for (int i = 0; i < len; i++) {
if (map.get(x[i]) != i) {
throw new AssertionError("get " + x[i] + " = " + map.get(i) + " should be " + i);
throw new AssertionError("get " + x[i] + " = " + map.get(i) +
" should be " + i);
}
}
}
......
......@@ -51,28 +51,45 @@ public class TestJmx extends TestBase {
name = new ObjectName("org.h2:name=JMX,path=mem_jmx");
info = mbeanServer.getMBeanInfo(name);
assertEquals("0", mbeanServer.getAttribute(name, "CacheSizeMax").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "CacheSizeMax").toString());
// cache size is ignored for in-memory databases
mbeanServer.setAttribute(name, new Attribute("CacheSizeMax", 1));
assertEquals("0", mbeanServer.getAttribute(name, "CacheSizeMax").toString());
assertEquals("0", mbeanServer.getAttribute(name, "CacheSize").toString());
assertEquals("false", mbeanServer.getAttribute(name, "Exclusive").toString());
assertEquals("0", mbeanServer.getAttribute(name, "FileSize").toString());
assertEquals("0", mbeanServer.getAttribute(name, "FileReadCount").toString());
assertEquals("0", mbeanServer.getAttribute(name, "FileWriteCount").toString());
assertEquals("0", mbeanServer.getAttribute(name, "FileWriteCountTotal").toString());
assertEquals("0", mbeanServer.getAttribute(name, "LogMode").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "CacheSizeMax").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "CacheSize").toString());
assertEquals("false", mbeanServer.
getAttribute(name, "Exclusive").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "FileSize").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "FileReadCount").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "FileWriteCount").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "FileWriteCountTotal").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "LogMode").toString());
// ignored for in-memory databases
mbeanServer.setAttribute(name, new Attribute("LogMode", 1));
assertEquals("0", mbeanServer.getAttribute(name, "LogMode").toString());
assertEquals("REGULAR", mbeanServer.getAttribute(name, "Mode").toString());
assertEquals("false", mbeanServer.getAttribute(name, "MultiThreaded").toString());
assertEquals("false", mbeanServer.getAttribute(name, "Mvcc").toString());
assertEquals("false", mbeanServer.getAttribute(name, "ReadOnly").toString());
assertEquals("1", mbeanServer.getAttribute(name, "TraceLevel").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "LogMode").toString());
assertEquals("REGULAR", mbeanServer.
getAttribute(name, "Mode").toString());
assertEquals("false", mbeanServer.
getAttribute(name, "MultiThreaded").toString());
assertEquals("false", mbeanServer.
getAttribute(name, "Mvcc").toString());
assertEquals("false", mbeanServer.
getAttribute(name, "ReadOnly").toString());
assertEquals("1", mbeanServer.
getAttribute(name, "TraceLevel").toString());
mbeanServer.setAttribute(name, new Attribute("TraceLevel", 0));
assertEquals("0", mbeanServer.getAttribute(name, "TraceLevel").toString());
assertTrue(mbeanServer.getAttribute(name, "Version").toString().startsWith("1."));
assertEquals("0", mbeanServer.
getAttribute(name, "TraceLevel").toString());
assertTrue(mbeanServer.
getAttribute(name, "Version").toString().startsWith("1."));
assertEquals(14, info.getAttributes().length);
result = mbeanServer.invoke(name, "listSettings", null, null).toString();
assertTrue(result.indexOf("ANALYZE_AUTO") >= 0);
......@@ -110,24 +127,37 @@ public class TestJmx extends TestBase {
Set set = mbeanServer.queryNames(name, null);
name = (ObjectName) set.iterator().next();
assertEquals("16384", mbeanServer.getAttribute(name, "CacheSizeMax").toString());
assertEquals("16384", mbeanServer.
getAttribute(name, "CacheSizeMax").toString());
mbeanServer.setAttribute(name, new Attribute("CacheSizeMax", 1));
if (config.mvStore) {
assertEquals("1024", mbeanServer.getAttribute(name, "CacheSizeMax").toString());
assertEquals("0", mbeanServer.getAttribute(name, "CacheSize").toString());
assertTrue(0 < (Long) mbeanServer.getAttribute(name, "FileReadCount"));
assertTrue(0 < (Long) mbeanServer.getAttribute(name, "FileWriteCount"));
assertEquals("0", mbeanServer.getAttribute(name, "FileWriteCountTotal").toString());
assertEquals("1024", mbeanServer.
getAttribute(name, "CacheSizeMax").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "CacheSize").toString());
assertTrue(0 < (Long) mbeanServer.
getAttribute(name, "FileReadCount"));
assertTrue(0 < (Long) mbeanServer.
getAttribute(name, "FileWriteCount"));
assertEquals("0", mbeanServer.
getAttribute(name, "FileWriteCountTotal").toString());
} else {
assertEquals("1", mbeanServer.getAttribute(name, "CacheSizeMax").toString());
assertTrue(0 < (Integer) mbeanServer.getAttribute(name, "CacheSize"));
assertTrue(0 < (Long) mbeanServer.getAttribute(name, "FileSize"));
assertTrue(0 < (Long) mbeanServer.getAttribute(name, "FileReadCount"));
assertTrue(0 < (Long) mbeanServer.getAttribute(name, "FileWriteCount"));
assertTrue(0 < (Long) mbeanServer.getAttribute(name, "FileWriteCountTotal"));
assertEquals("1", mbeanServer.
getAttribute(name, "CacheSizeMax").toString());
assertTrue(0 < (Integer) mbeanServer.
getAttribute(name, "CacheSize"));
assertTrue(0 < (Long) mbeanServer.
getAttribute(name, "FileSize"));
assertTrue(0 < (Long) mbeanServer.
getAttribute(name, "FileReadCount"));
assertTrue(0 < (Long) mbeanServer.
getAttribute(name, "FileWriteCount"));
assertTrue(0 < (Long) mbeanServer.
getAttribute(name, "FileWriteCountTotal"));
}
mbeanServer.setAttribute(name, new Attribute("LogMode", 0));
assertEquals("0", mbeanServer.getAttribute(name, "LogMode").toString());
assertEquals("0", mbeanServer.
getAttribute(name, "LogMode").toString());
conn.close();
......
......@@ -56,8 +56,10 @@ public class TestMathUtils extends TestBase {
private void testReverse() {
assertEquals(Integer.reverse(0), Integer.reverse(0));
assertEquals(Integer.reverse(Integer.MAX_VALUE), Integer.reverse(Integer.MAX_VALUE));
assertEquals(Integer.reverse(Integer.MIN_VALUE), Integer.reverse(Integer.MIN_VALUE));
assertEquals(Integer.reverse(Integer.MAX_VALUE),
Integer.reverse(Integer.MAX_VALUE));
assertEquals(Integer.reverse(Integer.MIN_VALUE),
Integer.reverse(Integer.MIN_VALUE));
assertEquals(Long.reverse(0), Long.reverse(0L));
assertEquals(Long.reverse(Long.MAX_VALUE), Long.reverse(Long.MAX_VALUE));
assertEquals(Long.reverse(Long.MIN_VALUE), Long.reverse(Long.MIN_VALUE));
......
......@@ -19,7 +19,8 @@ public class TestObjectDeserialization extends TestBase {
private static final String CLAZZ = "org.h2.test.unit.SampleObject";
private static final String OBJECT =
"aced00057372001d6f72672e68322e746573742e756e69742e53616d706c654f626a65637400000000000000010200007870";
"aced00057372001d6f72672e68322e746573742e756" +
"e69742e53616d706c654f626a65637400000000000000010200007870";
/**
* The thread context class loader was used.
......@@ -63,7 +64,8 @@ public class TestObjectDeserialization extends TestBase {
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
if (name.equals(CLAZZ)) {
usesThreadContextClassLoader = true;
}
......
......@@ -51,7 +51,8 @@ public class TestOldVersion extends TestBase {
return;
}
Connection conn = driver.connect("jdbc:h2:mem:", null);
assertEquals("1.2.127 (2010-01-15)", conn.getMetaData().getDatabaseProductVersion());
assertEquals("1.2.127 (2010-01-15)", conn.getMetaData()
.getDatabaseProductVersion());
conn.close();
testLobInFiles();
testOldClientNewServer();
......@@ -64,7 +65,8 @@ public class TestOldVersion extends TestBase {
conn = driver.connect("jdbc:h2:" + getBaseDir() + "/oldVersion", null);
stat = conn.createStatement();
stat.execute("create table test(id int primary key, b blob, c clob)");
PreparedStatement prep = conn.prepareStatement("insert into test values(?, ?, ?)");
PreparedStatement prep = conn
.prepareStatement("insert into test values(?, ?, ?)");
prep.setInt(1, 0);
prep.setNull(2, Types.BLOB);
prep.setNull(3, Types.CLOB);
......@@ -82,7 +84,8 @@ public class TestOldVersion extends TestBase {
prep.setString(3, new String(new char[100000]));
prep.execute();
conn.close();
conn = DriverManager.getConnection("jdbc:h2:" + getBaseDir() + "/oldVersion", new Properties());
conn = DriverManager.getConnection("jdbc:h2:" + getBaseDir() +
"/oldVersion", new Properties());
stat = conn.createStatement();
checkResult(stat.executeQuery("select * from test order by id"));
stat.execute("create table test2 as select * from test");
......@@ -113,14 +116,15 @@ public class TestOldVersion extends TestBase {
private void testOldClientNewServer() throws Exception {
Server server = org.h2.tools.Server.createTcpServer("-tcpPort", "9001");
server.start();
assertThrows(ErrorCode.DRIVER_VERSION_ERROR_2, driver).
connect("jdbc:h2:tcp://localhost:9001/mem:test", null);
assertThrows(ErrorCode.DRIVER_VERSION_ERROR_2, driver).connect(
"jdbc:h2:tcp://localhost:9001/mem:test", null);
server.stop();
Class<?> serverClass = cl.loadClass("org.h2.tools.Server");
Method m;
m = serverClass.getMethod("createTcpServer", String[].class);
Object serverOld = m.invoke(null, new Object[]{new String[]{"-tcpPort", "9001"}});
Object serverOld = m.invoke(null, new Object[] { new String[] {
"-tcpPort", "9001" } });
m = serverOld.getClass().getMethod("start");
m.invoke(serverOld);
Connection conn;
......
......@@ -22,7 +22,8 @@ import org.h2.tools.Restore;
*/
public class TestPageStoreCoverage extends TestBase {
private static final String URL = "pageStoreCoverage;PAGE_SIZE=64;CACHE_SIZE=16;MAX_LOG_SIZE=1";
private static final String URL = "pageStoreCoverage;" +
"PAGE_SIZE=64;CACHE_SIZE=16;MAX_LOG_SIZE=1";
/**
* Run just this test.
......@@ -56,9 +57,11 @@ public class TestPageStoreCoverage extends TestBase {
conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("create memory table test(id int primary key) as select x from system_range(1, 20)");
stat.execute("create memory table test(id int primary key) " +
"as select x from system_range(1, 20)");
for (int i = 0; i < 10; i++) {
stat.execute("create memory table test" + i + "(id int primary key) as select x from system_range(1, 2)");
stat.execute("create memory table test" + i +
"(id int primary key) as select x from system_range(1, 2)");
}
stat.execute("drop table test");
conn.close();
......@@ -70,9 +73,11 @@ public class TestPageStoreCoverage extends TestBase {
conn = getConnection(URL);
stat = conn.createStatement();
stat.execute("create table test(id int primary key) as select x from system_range(1, 100)");
stat.execute("create table test(id int primary key) " +
"as select x from system_range(1, 100)");
for (int i = 0; i < 10; i++) {
stat.execute("create table test" + i + "(id int primary key) as select x from system_range(1, 2)");
stat.execute("create table test" + i + "(id int primary key) " +
"as select x from system_range(1, 2)");
}
stat.execute("drop table test");
conn.close();
......@@ -202,14 +207,18 @@ public class TestPageStoreCoverage extends TestBase {
Connection conn;
conn = getConnection(URL);
Statement stat = conn.createStatement();
stat.execute("create table test(id int primary key, name varchar)");
stat.execute("create index idx_name on test(name, id)");
stat.execute("insert into test select x, x || space(200 * x) from system_range(1, 10)");
stat.execute(
"create table test(id int primary key, name varchar)");
stat.execute(
"create index idx_name on test(name, id)");
stat.execute(
"insert into test select x, x || space(200 * x) from system_range(1, 10)");
conn.setAutoCommit(false);
stat.execute("delete from test where id > 5");
stat.execute("backup to '" + getBaseDir() + "/backup.zip'");
conn.rollback();
Restore.execute(getBaseDir() + "/backup.zip", getBaseDir(), "pageStore2");
Restore.execute(getBaseDir() + "/backup.zip", getBaseDir(),
"pageStore2");
Connection conn2;
conn2 = getConnection("pageStore2");
Statement stat2 = conn2.createStatement();
......
......@@ -63,7 +63,8 @@ public class TestPattern extends TestBase {
boolean resultRegexp = value.matches(regexp);
boolean result = comp.test(pattern, value, '\\');
if (result != resultRegexp) {
fail("Error: >" + value + "< LIKE >" + pattern + "< result=" + result + " resultReg=" + resultRegexp);
fail("Error: >" + value + "< LIKE >" + pattern + "< result=" +
result + " resultReg=" + resultRegexp);
}
}
......
......@@ -54,14 +54,17 @@ public class TestPgServer extends TestBase {
return;
}
deleteDb("test");
Connection conn = getConnection("test;DATABASE_TO_UPPER=false", "sa", "sa");
Connection conn = getConnection(
"test;DATABASE_TO_UPPER=false", "sa", "sa");
Statement stat = conn.createStatement();
stat.execute("create table test(id int, name varchar(255))");
Server server = Server.createPgServer("-baseDir", getBaseDir(), "-pgPort", "5535", "-pgDaemon");
Server server = Server.createPgServer(
"-baseDir", getBaseDir(), "-pgPort", "5535", "-pgDaemon");
server.start();
try {
Connection conn2;
conn2 = DriverManager.getConnection("jdbc:postgresql://localhost:5535/test", "sa", "sa");
conn2 = DriverManager.getConnection(
"jdbc:postgresql://localhost:5535/test", "sa", "sa");
stat = conn2.createStatement();
stat.execute("select * from test");
conn2.close();
......@@ -84,7 +87,8 @@ public class TestPgServer extends TestBase {
private void testPgAdapter() throws SQLException {
deleteDb("test");
Server server = Server.createPgServer("-baseDir", getBaseDir(), "-pgPort", "5535", "-pgDaemon");
Server server = Server.createPgServer(
"-baseDir", getBaseDir(), "-pgPort", "5535", "-pgDaemon");
assertEquals(5535, server.getPort());
assertEquals("Not started", server.getStatus());
server.start();
......@@ -103,12 +107,14 @@ public class TestPgServer extends TestBase {
return;
}
Server server = Server.createPgServer("-pgPort", "5535", "-pgDaemon", "-key", "test", "mem:test");
Server server = Server.createPgServer(
"-pgPort", "5535", "-pgDaemon", "-key", "test", "mem:test");
server.start();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5535/test", "sa", "sa");
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5535/test", "sa", "sa");
final Statement stat = conn.createStatement();
stat.execute("create alias sleep for \"java.lang.Thread.sleep\"");
......@@ -133,7 +139,8 @@ public class TestPgServer extends TestBase {
future.get();
throw new IllegalStateException();
} catch (ExecutionException e) {
assertStartsWith(e.getCause().getMessage(), "ERROR: canceling statement due to user request");
assertStartsWith(e.getCause().getMessage(),
"ERROR: canceling statement due to user request");
} finally {
conn.close();
}
......@@ -145,7 +152,8 @@ public class TestPgServer extends TestBase {
}
private void testPgClient() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5535/test", "sa", "sa");
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5535/test", "sa", "sa");
Statement stat = conn.createStatement();
assertThrows(SQLException.class, stat).
execute("select ***");
......@@ -156,7 +164,8 @@ public class TestPgServer extends TestBase {
stat.close();
conn.close();
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5535/test", "test", "test");
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5535/test", "test", "test");
stat = conn.createStatement();
ResultSet rs;
......@@ -189,7 +198,9 @@ public class TestPgServer extends TestBase {
assertEquals(1, rs.getInt(1));
assertEquals("Hello", rs.getString(2));
assertFalse(rs.next());
prep = conn.prepareStatement("select * from test where id = ? and name = ?");
prep = conn.prepareStatement(
"select * from test " +
"where id = ? and name = ?");
prep.setInt(1, 1);
prep.setString(2, "Hello");
rs = prep.executeQuery();
......@@ -216,7 +227,8 @@ public class TestPgServer extends TestBase {
// rs.next();
// assertEquals("TEST", rs.getString("TABLE_NAME"));
assertFalse(rs.next());
rs = stat.executeQuery("select version(), pg_postmaster_start_time(), current_schema()");
rs = stat.executeQuery(
"select version(), pg_postmaster_start_time(), current_schema()");
rs.next();
String s = rs.getString(1);
assertTrue(s.indexOf("H2") >= 0);
......@@ -237,7 +249,8 @@ public class TestPgServer extends TestBase {
assertEquals("Hallo", rs.getString(2));
assertFalse(rs.next());
rs = stat.executeQuery("select id, name, pg_get_userbyid(id) from information_schema.users order by id");
rs = stat.executeQuery("select id, name, pg_get_userbyid(id) " +
"from information_schema.users order by id");
rs.next();
assertEquals(rs.getString(2), rs.getString(3));
assertFalse(rs.next());
......@@ -292,7 +305,8 @@ public class TestPgServer extends TestBase {
rs.next();
assertEquals("", rs.getString(1));
rs = stat.executeQuery("select id from information_schema.indexes where index_name='IDX_TEST_NAME'");
rs = stat.executeQuery("select id from information_schema.indexes " +
"where index_name='IDX_TEST_NAME'");
rs.next();
int indexId = rs.getInt(1);
......@@ -301,7 +315,9 @@ public class TestPgServer extends TestBase {
assertEquals("CREATE INDEX PUBLIC.IDX_TEST_NAME ON PUBLIC.TEST(NAME, ID)", rs.getString(1));
rs = stat.executeQuery("select pg_get_indexdef("+indexId+", null, false)");
rs.next();
assertEquals("CREATE INDEX PUBLIC.IDX_TEST_NAME ON PUBLIC.TEST(NAME, ID)", rs.getString(1));
assertEquals(
"CREATE INDEX PUBLIC.IDX_TEST_NAME ON PUBLIC.TEST(NAME, ID)",
rs.getString(1));
rs = stat.executeQuery("select pg_get_indexdef("+indexId+", 1, false)");
rs.next();
assertEquals("NAME", rs.getString(1));
......@@ -316,16 +332,20 @@ public class TestPgServer extends TestBase {
if (!getPgJdbcDriver()) {
return;
}
Server server = Server.createPgServer("-pgPort", "5535", "-pgDaemon", "-key", "test", "mem:test");
Server server = Server.createPgServer(
"-pgPort", "5535", "-pgDaemon", "-key", "test", "mem:test");
server.start();
try {
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5535/test", "sa", "sa");
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5535/test", "sa", "sa");
Statement stat = conn.createStatement();
// confirm that we've got the in memory implementation
// by creating a table and checking flags
stat.execute("create table test(id int primary key, name varchar)");
ResultSet rs = stat.executeQuery("select storage_type from information_schema.tables where table_name = 'TEST'");
ResultSet rs = stat.executeQuery(
"select storage_type from information_schema.tables " +
"where table_name = 'TEST'");
assertTrue(rs.next());
assertEquals("MEMORY", rs.getString(1));
......@@ -340,16 +360,21 @@ public class TestPgServer extends TestBase {
return;
}
Server server = Server.createPgServer("-pgPort", "5535", "-pgDaemon", "-key", "test", "mem:test");
Server server = Server.createPgServer(
"-pgPort", "5535", "-pgDaemon", "-key", "test", "mem:test");
server.start();
try {
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5535/test", "sa", "sa");
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5535/test", "sa", "sa");
Statement stat = conn.createStatement();
stat.execute("create table test(x1 varchar, x2 int, x3 smallint, x4 bigint, x5 double, x6 float, " +
"x7 real, x8 boolean, x9 char, x10 bytea)");
stat.execute(
"create table test(x1 varchar, x2 int, " +
"x3 smallint, x4 bigint, x5 double, x6 float, " +
"x7 real, x8 boolean, x9 char, x10 bytea)");
PreparedStatement ps = conn.prepareStatement("insert into test values (?,?,?,?,?,?,?,?,?,?)");
PreparedStatement ps = conn.prepareStatement(
"insert into test values (?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, "test");
ps.setInt(2, 12345678);
ps.setShort(3, (short) 12345);
......
......@@ -36,7 +36,8 @@ public class TestReopen extends TestBase implements Recorder {
private String testDatabase = "memFS:" + TestBase.BASE_TEST_DIR + "/reopen";
private int writeCount = Utils.getProperty("h2.reopenOffset", 0);
private final int testEvery = 1 << Utils.getProperty("h2.reopenShift", 6);
private final long maxFileSize = Utils.getProperty("h2.reopenMaxFileSize", Integer.MAX_VALUE) * 1024L * 1024;
private final long maxFileSize = Utils.getProperty("h2.reopenMaxFileSize",
Integer.MAX_VALUE) * 1024L * 1024;
private int verifyCount;
private final HashSet<String> knownErrors = New.hashSet();
private volatile boolean testing;
......@@ -100,9 +101,11 @@ public class TestReopen extends TestBase implements Recorder {
try {
if (fileName.endsWith(Constants.SUFFIX_PAGE_FILE)) {
IOUtils.copyFiles(fileName, testDatabase + Constants.SUFFIX_PAGE_FILE);
IOUtils.copyFiles(fileName, testDatabase +
Constants.SUFFIX_PAGE_FILE);
} else {
IOUtils.copyFiles(fileName, testDatabase + Constants.SUFFIX_MV_FILE);
IOUtils.copyFiles(fileName, testDatabase +
Constants.SUFFIX_MV_FILE);
}
verifyCount++;
// avoid using the Engine class to avoid deadlocks
......@@ -110,7 +113,8 @@ public class TestReopen extends TestBase implements Recorder {
String userName = getUser();
p.setProperty("user", userName);
p.setProperty("password", getPassword());
String url = "jdbc:h2:" + testDatabase + ";FILE_LOCK=NO;TRACE_LEVEL_FILE=0";
String url = "jdbc:h2:" + testDatabase +
";FILE_LOCK=NO;TRACE_LEVEL_FILE=0";
if (config.mvStore) {
url += ";MV_STORE=TRUE";
}
......@@ -146,7 +150,8 @@ public class TestReopen extends TestBase implements Recorder {
}
e.printStackTrace(System.out);
}
System.out.println("begin ------------------------------ " + writeCount);
System.out.println(
"begin ------------------------------ " + writeCount);
try {
Recover.execute(fileName.substring(0, fileName.lastIndexOf('/')), null);
} catch (SQLException e) {
......@@ -155,9 +160,11 @@ public class TestReopen extends TestBase implements Recorder {
testDatabase += "X";
try {
if (fileName.endsWith(Constants.SUFFIX_PAGE_FILE)) {
IOUtils.copyFiles(fileName, testDatabase + Constants.SUFFIX_PAGE_FILE);
IOUtils.copyFiles(fileName, testDatabase +
Constants.SUFFIX_PAGE_FILE);
} else {
IOUtils.copyFiles(fileName, testDatabase + Constants.SUFFIX_MV_FILE);
IOUtils.copyFiles(fileName, testDatabase +
Constants.SUFFIX_MV_FILE);
}
// avoid using the Engine class to avoid deadlocks
Properties p = new Properties();
......@@ -187,7 +194,8 @@ public class TestReopen extends TestBase implements Recorder {
}
String s = buff.toString();
if (!knownErrors.contains(s)) {
System.out.println(writeCount + " code: " + errorCode + " " + e.toString());
System.out.println(writeCount + " code: " + errorCode + " " +
e.toString());
e.printStackTrace(System.out);
knownErrors.add(s);
} else {
......
......@@ -40,18 +40,24 @@ public class TestSampleApps extends TestBase {
return;
}
deleteDb("optimizations");
InputStream in = getClass().getClassLoader().getResourceAsStream("org/h2/samples/optimizations.sql");
InputStream in = getClass().getClassLoader().getResourceAsStream(
"org/h2/samples/optimizations.sql");
new File(getBaseDir()).mkdirs();
FileOutputStream out = new FileOutputStream(getBaseDir() + "/optimizations.sql");
FileOutputStream out = new FileOutputStream(getBaseDir() +
"/optimizations.sql");
IOUtils.copyAndClose(in, out);
String url = "jdbc:h2:" + getBaseDir() + "/optimizations";
testApp("", org.h2.tools.RunScript.class, "-url", url, "-user", "sa", "-password", "sa", "-script",
getBaseDir() + "/optimizations.sql", "-checkResults");
testApp("", org.h2.tools.RunScript.class, "-url", url, "-user", "sa",
"-password", "sa", "-script", getBaseDir() +
"/optimizations.sql", "-checkResults");
deleteDb("optimizations");
testApp("Compacting...\nDone.", org.h2.samples.Compact.class);
testApp("NAME: Bob Meier\n" + "EMAIL: bob.meier@abcde.abc\n"
+ "PHONE: +41123456789\n\n" + "NAME: John Jones\n" + "EMAIL: john.jones@abcde.abc\n"
+ "PHONE: +41976543210\n",
testApp("NAME: Bob Meier\n" +
"EMAIL: bob.meier@abcde.abc\n" +
"PHONE: +41123456789\n\n" +
"NAME: John Jones\n" +
"EMAIL: john.jones@abcde.abc\n" +
"PHONE: +41976543210\n",
org.h2.samples.CsvSample.class);
testApp("",
org.h2.samples.CachedPreparedStatements.class);
......@@ -106,7 +112,8 @@ public class TestSampleApps extends TestBase {
FileUtils.delete(getBaseDir() + "/optimizations.sql");
}
private void testApp(String expected, Class<?> clazz, String... args) throws Exception {
private void testApp(String expected, Class<?> clazz, String... args)
throws Exception {
DeleteDbFiles.execute("data", "test", true);
Method m = clazz.getMethod("main", String[].class);
PrintStream oldOut = System.out, oldErr = System.err;
......
......@@ -76,7 +76,8 @@ public class TestScriptReader extends TestBase {
case 1: {
buff.append('\'');
int l = random.nextInt(4);
String[] ch = { ";", "\n", "\r", "--", "//", "/", "-", "*", "/*", "*/", "\"", "$ " };
String[] ch = { ";", "\n", "\r", "--", "//", "/", "-", "*",
"/*", "*/", "\"", "$ " };
for (int j = 0; j < l; j++) {
buff.append(ch[random.nextInt(ch.length)]);
}
......@@ -86,7 +87,8 @@ public class TestScriptReader extends TestBase {
case 2: {
buff.append('"');
int l = random.nextInt(4);
String[] ch = { ";", "\n", "\r", "--", "//", "/", "-", "*", "/*", "*/", "\'", "$" };
String[] ch = { ";", "\n", "\r", "--", "//", "/", "-", "*",
"/*", "*/", "\'", "$" };
for (int j = 0; j < l; j++) {
buff.append(ch[random.nextInt(ch.length)]);
}
......
......@@ -39,9 +39,12 @@ public class TestSecurity extends TestBase {
}
private static void testConnectWithHash() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:test", "sa", "sa");
String pwd = StringUtils.convertBytesToHex(SHA256.getKeyPasswordHash("SA", "sa".toCharArray()));
Connection conn2 = DriverManager.getConnection("jdbc:h2:mem:test;PASSWORD_HASH=TRUE", "sa", pwd);
Connection conn = DriverManager.getConnection(
"jdbc:h2:mem:test", "sa", "sa");
String pwd = StringUtils.convertBytesToHex(
SHA256.getKeyPasswordHash("SA", "sa".toCharArray()));
Connection conn2 = DriverManager.getConnection(
"jdbc:h2:mem:test;PASSWORD_HASH=TRUE", "sa", pwd);
conn.close();
conn2.close();
}
......@@ -121,35 +124,49 @@ public class TestSecurity extends TestBase {
}
private void testOneSHA() {
assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
assertEquals(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
getHashString(new byte[] {}));
assertEquals("68aa2e2ee5dff96e3355e6c7ee373e3d6a4e17f75f9518d843709c0c9bc3e3d4",
assertEquals(
"68aa2e2ee5dff96e3355e6c7ee373e3d6a4e17f75f9518d843709c0c9bc3e3d4",
getHashString(new byte[] { 0x19 }));
assertEquals("175ee69b02ba9b58e2b0a5fd13819cea573f3940a94f825128cf4209beabb4e8",
assertEquals(
"175ee69b02ba9b58e2b0a5fd13819cea573f3940a94f825128cf4209beabb4e8",
getHashString(
new byte[] { (byte) 0xe3, (byte) 0xd7, 0x25, 0x70, (byte) 0xdc, (byte) 0xdd, 0x78, 0x7c, (byte) 0xe3,
(byte) 0x88, 0x7a, (byte) 0xb2, (byte) 0xcd, 0x68, 0x46, 0x52 }));
checkSHA256("",
new byte[] { (byte) 0xe3, (byte) 0xd7, 0x25,
0x70, (byte) 0xdc, (byte) 0xdd, 0x78, 0x7c,
(byte) 0xe3, (byte) 0x88, 0x7a, (byte) 0xb2,
(byte) 0xcd, 0x68, 0x46, 0x52 }));
checkSHA256(
"",
"E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855");
checkSHA256("a",
checkSHA256(
"a",
"CA978112CA1BBDCAFAC231B39A23DC4DA786EFF8147C4E72B9807785AFEE48BB");
checkSHA256("abc",
checkSHA256(
"abc",
"BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD");
checkSHA256("message digest",
checkSHA256(
"message digest",
"F7846F55CF23E14EEBEAB5B4E1550CAD5B509E3348FBC4EFA3A1413D393CB650");
checkSHA256("abcdefghijklmnopqrstuvwxyz",
checkSHA256(
"abcdefghijklmnopqrstuvwxyz",
"71C480DF93D6AE2F1EFAD1447C66C9525E316218CF51FC8D9ED832F2DAF18B73");
checkSHA256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
checkSHA256(
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167F6ECEDD419DB06C1");
checkSHA256("12345678901234567890123456789012345678901234567890123456789012345678901234567890",
checkSHA256(
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"F371BC4A311F2B009EEF952DD83CA80E2B60026C8E935592D0F9C308453C813E");
StringBuilder buff = new StringBuilder(1000000);
buff.append('a');
checkSHA256(buff.toString(), "CA978112CA1BBDCAFAC231B39A23DC4DA786EFF8147C4E72B9807785AFEE48BB");
checkSHA256(buff.toString(),
"CA978112CA1BBDCAFAC231B39A23DC4DA786EFF8147C4E72B9807785AFEE48BB");
}
private void checkSHA256(String message, String expected) {
String hash = StringUtils.convertBytesToHex(SHA256.getHash(message.getBytes(), true)).toUpperCase();
String hash = StringUtils.convertBytesToHex(
SHA256.getHash(message.getBytes(), true)).toUpperCase();
assertEquals(expected, hash);
}
......
......@@ -233,8 +233,9 @@ public class TestServlet extends TestBase {
listener.contextDestroyed(event);
// listener must be stopped
assertThrows(ErrorCode.CONNECTION_BROKEN_1, this).
getConnection("jdbc:h2:tcp://localhost:8888/" + getBaseDir() + "/servlet", getUser(), getPassword());
assertThrows(ErrorCode.CONNECTION_BROKEN_1, this).getConnection(
"jdbc:h2:tcp://localhost:8888/" + getBaseDir() + "/servlet",
getUser(), getPassword());
// connection must be closed
assertThrows(ErrorCode.OBJECT_CLOSED, stat1).
......
......@@ -50,7 +50,8 @@ public class TestShell extends TestBase {
ByteArrayOutputStream buff = new ByteArrayOutputStream();
shell.setOut(new PrintStream(buff));
shell.runTool("-url", "jdbc:h2:mem:", "-driver", "org.h2.Driver",
"-user", "sa", "-password", "sa", "-properties", "null", "-sql", "select 'Hello ' || 'World' as hi");
"-user", "sa", "-password", "sa", "-properties", "null",
"-sql", "select 'Hello ' || 'World' as hi");
String s = new String(buff.toByteArray());
assertContains(s, "HI");
assertContains(s, "Hello World");
......@@ -61,7 +62,8 @@ public class TestShell extends TestBase {
shell.setOut(new PrintStream(buff));
shell.runTool("-help");
s = new String(buff.toByteArray());
assertContains(s, "Interactive command line tool to access a database using JDBC.");
assertContains(s,
"Interactive command line tool to access a database using JDBC.");
test(true);
test(false);
......
......@@ -94,7 +94,8 @@ public class TestSort extends TestBase {
// long t = System.currentTimeMillis();
clazz.getMethod("sort", Object[].class, Comparator.class).invoke(null, array, comp);
clazz.getMethod("sort", Object[].class, Comparator.class).invoke(null,
array, comp);
// System.out.printf(
// "%4d ms; %10d comparisons order: %s data: %s\n",
......
......@@ -21,7 +21,8 @@ public class TestStringCache extends TestBase {
*/
volatile boolean stop;
private final Random random = new Random(1);
private final String[] some = { null, "", "ABC", "this is a medium sized string", "1", "2" };
private final String[] some = { null, "", "ABC",
"this is a medium sized string", "1", "2" };
private boolean returnNew;
private boolean useIntern;
......@@ -88,7 +89,8 @@ public class TestStringCache extends TestBase {
TestBase.logError("error", e);
}
if (a != null && a == b && a.length() > 0) {
throw new AssertionError("a=" + System.identityHashCode(a) + " b=" + System.identityHashCode(b));
throw new AssertionError("a=" + System.identityHashCode(a) +
" b=" + System.identityHashCode(b));
}
} else {
String b;
......
......@@ -179,8 +179,11 @@ public class TestStringUtils extends TestBase {
}
private void testSplit() {
assertEquals(3, StringUtils.arraySplit("ABC,DEF,G\\,HI", ',', false).length);
assertEquals(StringUtils.arrayCombine(new String[] { "", " ", "," }, ','), ", ,\\,");
assertEquals(3,
StringUtils.arraySplit("ABC,DEF,G\\,HI", ',', false).length);
assertEquals(
StringUtils.arrayCombine(new String[] { "", " ", "," }, ','),
", ,\\,");
Random random = new Random(1);
for (int i = 0; i < 100; i++) {
int len = random.nextInt(10);
......
......@@ -149,7 +149,8 @@ public class TestUtils extends TestBase {
Arrays.sort(arr2, comp);
for (int i = offset, end = Math.min(offset + limit, arr.length); i < end; i++) {
if (!arr[i].equals(arr2[i])) {
fail(offset + " " + end + "\n" + Arrays.toString(arr) + "\n" + Arrays.toString(arr2));
fail(offset + " " + end + "\n" + Arrays.toString(arr) +
"\n" + Arrays.toString(arr2));
}
}
}
......@@ -176,7 +177,8 @@ public class TestUtils extends TestBase {
private void testReflectionUtils() throws Exception {
// Static method call
long currentTimeMillis1 = System.currentTimeMillis();
long currentTimeMillis2 = (Long) Utils.callStaticMethod("java.lang.System.currentTimeMillis");
long currentTimeMillis2 = (Long) Utils.callStaticMethod(
"java.lang.System.currentTimeMillis");
assertTrue(currentTimeMillis1 <= currentTimeMillis2);
// New Instance
Object instance = Utils.newInstance("java.lang.StringBuilder");
......@@ -201,11 +203,21 @@ public class TestUtils extends TestBase {
Utils.callStaticMethod("java.awt.AWTKeyStroke.getAWTKeyStroke",
'x', java.awt.event.InputEvent.SHIFT_DOWN_MASK);
// Common comparable superclass
assertFalse(Utils.haveCommonComparableSuperclass(Integer.class, Long.class));
assertTrue(Utils.haveCommonComparableSuperclass(Integer.class, Integer.class));
assertTrue(Utils.haveCommonComparableSuperclass(Timestamp.class, Date.class));
assertFalse(Utils.haveCommonComparableSuperclass(ArrayList.class, Long.class));
assertFalse(Utils.haveCommonComparableSuperclass(Integer.class, ArrayList.class));
assertFalse(Utils.haveCommonComparableSuperclass(
Integer.class,
Long.class));
assertTrue(Utils.haveCommonComparableSuperclass(
Integer.class,
Integer.class));
assertTrue(Utils.haveCommonComparableSuperclass(
Timestamp.class,
Date.class));
assertFalse(Utils.haveCommonComparableSuperclass(
ArrayList.class,
Long.class));
assertFalse(Utils.haveCommonComparableSuperclass(
Integer.class,
ArrayList.class));
}
}
......@@ -62,7 +62,8 @@ public class TestValue extends TestBase {
Value v;
String spaces = new String(new char[100]).replace((char) 0, ' ');
v = ValueArray.get(new Value[]{ValueString.get("hello"), ValueString.get("world")});
v = ValueArray.get(new Value[] { ValueString.get("hello"),
ValueString.get("world") });
assertEquals(10, v.getPrecision());
assertEquals(5, v.convertPrecision(5, true).getPrecision());
v = ValueArray.get(new Value[]{ValueString.get(""), ValueString.get("")});
......@@ -79,10 +80,12 @@ public class TestValue extends TestBase {
final Value vd = ValueDecimal.get(new BigDecimal("1234567890.123456789"));
assertEquals(19, vd.getPrecision());
assertEquals("1234567890.1234567", vd.convertPrecision(10, true).getString());
new AssertThrows(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1) { @Override
public void test() {
vd.convertPrecision(10, false);
}};
new AssertThrows(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1) {
@Override
public void test() {
vd.convertPrecision(10, false);
}
};
v = ValueLobDb.createSmallLob(Value.CLOB, spaces.getBytes(), 100);
assertEquals(100, v.getPrecision());
......@@ -200,7 +203,8 @@ public class TestValue extends TestBase {
};
Value[] values = new Value[d.length];
for (int i = 0; i < d.length; i++) {
Value v = useFloat ? (Value) ValueFloat.get((float) d[i]) : (Value) ValueDouble.get(d[i]);
Value v = useFloat ? (Value) ValueFloat.get((float) d[i])
: (Value) ValueDouble.get(d[i]);
values[i] = v;
assertTrue(values[i].compareTypeSave(values[i], null) == 0);
assertTrue(v.equals(v));
......
......@@ -163,7 +163,8 @@ public class TestValueHashMap extends TestBase implements DataHandler {
}
@Override
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff, int off, int length) {
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff,
int off, int length) {
return -1;
}
......
......@@ -56,7 +56,8 @@ import org.h2.value.ValueUuid;
public class TestValueMemory extends TestBase implements DataHandler {
private final Random random = new Random(1);
private final SmallLRUCache<String, String[]> lobFileListCache = SmallLRUCache.newInstance(128);
private final SmallLRUCache<String, String[]> lobFileListCache = SmallLRUCache
.newInstance(128);
private LobStorageFrontend lobStorage;
/**
......@@ -198,7 +199,8 @@ public class TestValueMemory extends TestBase implements DataHandler {
if (DataType.GEOMETRY_CLASS == null) {
return ValueNull.INSTANCE;
}
return ValueGeometry.get("POINT (" + random.nextInt(100) + " "+random.nextInt(100)+")");
return ValueGeometry.get("POINT (" + random.nextInt(100) + " " +
random.nextInt(100) + ")");
default:
throw new AssertionError("type=" + type);
}
......@@ -278,7 +280,8 @@ public class TestValueMemory extends TestBase implements DataHandler {
}
@Override
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff, int off, int length) {
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff,
int off, int length) {
return -1;
}
......
......@@ -29,7 +29,8 @@ public abstract class AssertThrows {
public AssertThrows(final Class<? extends Exception> expectedExceptionClass) {
this(new ResultVerifier() {
@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) {
throw new AssertionError("Expected an exception of type " +
expectedExceptionClass.getSimpleName() +
......@@ -77,7 +78,8 @@ public abstract class AssertThrows {
public AssertThrows(final int expectedErrorCode) {
this(new ResultVerifier() {
@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;
if (t instanceof DbException) {
errorCode = ((DbException) t).getErrorCode();
......
......@@ -25,7 +25,8 @@ public class FilePathDebug extends FilePathWrapper {
private static final FilePathDebug INSTANCE = new FilePathDebug();
private static final IOException POWER_OFF = new IOException("Simulated power failure");
private static final IOException POWER_OFF = new IOException(
"Simulated power failure");
private int powerOffCount;
private boolean trace;
......@@ -191,8 +192,8 @@ public class FilePathDebug extends FilePathWrapper {
}
@Override
public FilePath createTempFile(String suffix, boolean deleteOnExit, boolean inTempDir)
throws IOException {
public FilePath createTempFile(String suffix, boolean deleteOnExit,
boolean inTempDir) throws IOException {
trace(name, "createTempFile", suffix, deleteOnExit, inTempDir);
return super.createTempFile(suffix, deleteOnExit, inTempDir);
}
......@@ -323,7 +324,8 @@ class FileDebug extends FileBase {
}
@Override
public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException {
public synchronized FileLock tryLock(long position, long size,
boolean shared) throws IOException {
debug("tryLock");
return channel.tryLock(position, size, shared);
}
......
......@@ -199,8 +199,8 @@ public class FilePathUnstable extends FilePathWrapper {
}
@Override
public FilePath createTempFile(String suffix, boolean deleteOnExit, boolean inTempDir)
throws IOException {
public FilePath createTempFile(String suffix, boolean deleteOnExit,
boolean inTempDir) throws IOException {
return super.createTempFile(suffix, deleteOnExit, inTempDir);
}
......@@ -296,7 +296,8 @@ class FileUnstable extends FileBase {
}
@Override
public synchronized FileLock tryLock(long position, long size, boolean shared) throws IOException {
public synchronized FileLock tryLock(long position, long size,
boolean shared) throws IOException {
return channel.tryLock(position, size, shared);
}
......
......@@ -54,7 +54,8 @@ public class MemoryFootprint {
print("long[" + i +"]", new long[i]);
print("double[" + i +"]", new double[i]);
System.out.println(getArraySize(Constants.MEMORY_POINTER, i) + " bytes per obj[]");
System.out.println(getArraySize(Constants.MEMORY_POINTER, i) +
" bytes per obj[]");
print("Object[" + i +"]", new Object[i]);
System.out.println();
......
......@@ -60,11 +60,15 @@ public class OutputCatcher {
file.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter(new FileOutputStream(file));
writer.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 " +
"Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
writer.write("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n");
writer.write("<head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /><title>\n");
"Strict//EN\" " +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
writer.write("<html xmlns=\"http://www.w3.org/1999/xhtml\" " +
"lang=\"en\" xml:lang=\"en\">\n");
writer.write("<head><meta http-equiv=\"Content-Type\" " +
"content=\"text/html;charset=utf-8\" /><title>\n");
writer.print(title);
writer.print("</title><link rel=\"stylesheet\" type=\"text/css\" href=\"stylesheet.css\" />\n");
writer.print("</title><link rel=\"stylesheet\" " +
"type=\"text/css\" href=\"stylesheet.css\" />\n");
writer.print("</head><body style=\"margin: 20px;\">\n");
writer.print("<h1>" + title + "</h1><br />\n");
writer.print(output);
......
......@@ -122,7 +122,8 @@ public class ProxyCodeGenerator {
}
if (constructor == null) {
constructor = c;
} else if (c.getParameterTypes().length < constructor.getParameterTypes().length) {
} else if (c.getParameterTypes().length <
constructor.getParameterTypes().length) {
constructor = c;
}
}
......@@ -203,7 +204,8 @@ public class ProxyCodeGenerator {
writer.println(" public " + className + "() {");
writer.println(" this(new InvocationHandler() {");
writer.println(" public Object invoke(Object proxy,");
writer.println(" Method method, Object[] args) throws Throwable {");
writer.println(" Method method, Object[] args) " +
"throws Throwable {");
writer.println(" return method.invoke(proxy, args);");
writer.println(" }});");
writer.println(" }");
......@@ -243,7 +245,8 @@ public class ProxyCodeGenerator {
writer.println(" this.ih = ih;");
writer.println(" }");
writer.println(" @SuppressWarnings(\"unchecked\")");
writer.println(" private static <T extends RuntimeException> T convertException(Throwable e) {");
writer.println(" private static <T extends RuntimeException> " +
"T convertException(Throwable e) {");
writer.println(" if (e instanceof Error) {");
writer.println(" throw (Error) e;");
writer.println(" }");
......
......@@ -27,81 +27,87 @@ public class SelfDestructor extends Thread {
* current process is killed.
*/
public static void startCountdown(int defaultMinutes) {
final int minutes = Integer.parseInt(System.getProperty(PROPERTY_NAME, "" + defaultMinutes));
if (minutes != 0) {
Thread thread = new Thread() {
@Override
public void run() {
for (int i = minutes; i >= 0; i--) {
while (true) {
try {
String name = "SelfDestructor " + i + " min";
setName(name);
break;
} catch (OutOfMemoryError e) {
// ignore
}
}
final int minutes = Integer.parseInt(
System.getProperty(PROPERTY_NAME, "" + defaultMinutes));
if (minutes == 0) {
return;
}
Thread thread = new Thread() {
@Override
public void run() {
for (int i = minutes; i >= 0; i--) {
while (true) {
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
String name = "SelfDestructor " + i + " min";
setName(name);
break;
} catch (OutOfMemoryError e) {
// ignore
}
}
try {
String time = new Timestamp(System.currentTimeMillis()).toString();
System.out.println(time + " Killing the process after " + minutes + " minute(s)");
try {
Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> en : map.entrySet()) {
System.out.println(en.getKey());
for (StackTraceElement el : en.getValue()) {
System.out.println(" " + el);
}
}
System.out.println();
System.out.flush();
try {
Thread.sleep(1000);
} catch (Exception e) {
// ignore
}
int activeCount = Thread.activeCount();
Thread[] threads = new Thread[activeCount + 100];
int len = Thread.enumerate(threads);
Method stop = Thread.class.getMethod("stop", Throwable.class);
for (int i = 0; i < len; i++) {
Thread t = threads[i];
String threadName = "Thread #" + i + ": " + t.getName();
Error e = new Error(threadName);
if (t != Thread.currentThread()) {
stop.invoke(t, e);
t.interrupt();
}
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
// ignore
}
}
try {
String time = new Timestamp(
System.currentTimeMillis()).toString();
System.out.println(time + " Killing the process after " +
minutes + " minute(s)");
try {
Map<Thread, StackTraceElement[]> map =
Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> en :
map.entrySet()) {
System.out.println(en.getKey());
for (StackTraceElement el : en.getValue()) {
System.out.println(" " + el);
}
} catch (Throwable t) {
t.printStackTrace();
// ignore
}
System.out.println();
System.out.flush();
try {
Thread.sleep(1000);
} catch (Exception e) {
// ignore
}
System.out.println("Killing the process now");
} catch (Throwable t) {
try {
t.printStackTrace(System.out);
} catch (Throwable t2) {
// ignore (out of memory)
int activeCount = Thread.activeCount();
Thread[] threads = new Thread[activeCount + 100];
int len = Thread.enumerate(threads);
Method stop = Thread.class.getMethod("stop", Throwable.class);
for (int i = 0; i < len; i++) {
Thread t = threads[i];
String threadName = "Thread #" + i + ": " + t.getName();
Error e = new Error(threadName);
if (t != Thread.currentThread()) {
stop.invoke(t, e);
t.interrupt();
}
}
} catch (Throwable t) {
t.printStackTrace();
// ignore
}
try {
Thread.sleep(1000);
} catch (Exception e) {
// ignore
}
System.out.println("Killing the process now");
} catch (Throwable t) {
try {
t.printStackTrace(System.out);
} catch (Throwable t2) {
// ignore (out of memory)
}
Runtime.getRuntime().halt(1);
}
};
thread.setDaemon(true);
thread.start();
}
Runtime.getRuntime().halt(1);
}
};
thread.setDaemon(true);
thread.start();
}
/**
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论