提交 0a92f254 authored 作者: Noel Grandin's avatar Noel Grandin

use try-with-resources where feasible

上级 6a89e09b
...@@ -466,8 +466,7 @@ public class ScriptCommand extends ScriptBase { ...@@ -466,8 +466,7 @@ public class ScriptCommand extends ScriptBase {
switch (v.getType()) { switch (v.getType()) {
case Value.BLOB: { case Value.BLOB: {
byte[] bytes = new byte[lobBlockSize]; byte[] bytes = new byte[lobBlockSize];
InputStream input = v.getInputStream(); try (InputStream input = v.getInputStream()) {
try {
for (int i = 0;; i++) { for (int i = 0;; i++) {
StringBuilder buff = new StringBuilder(lobBlockSize * 2); StringBuilder buff = new StringBuilder(lobBlockSize * 2);
buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(" + id + buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(" + id +
...@@ -480,15 +479,13 @@ public class ScriptCommand extends ScriptBase { ...@@ -480,15 +479,13 @@ public class ScriptCommand extends ScriptBase {
String sql = buff.toString(); String sql = buff.toString();
add(sql, true); add(sql, true);
} }
} finally {
IOUtils.closeSilently(input);
} }
break; break;
} }
case Value.CLOB: { case Value.CLOB: {
char[] chars = new char[lobBlockSize]; char[] chars = new char[lobBlockSize];
Reader reader = v.getReader();
try { try (Reader reader = v.getReader()) {
for (int i = 0;; i++) { for (int i = 0;; i++) {
StringBuilder buff = new StringBuilder(lobBlockSize * 2); StringBuilder buff = new StringBuilder(lobBlockSize * 2);
buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(" + id + ", " + i + ", "); buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(" + id + ", " + i + ", ");
...@@ -501,8 +498,6 @@ public class ScriptCommand extends ScriptBase { ...@@ -501,8 +498,6 @@ public class ScriptCommand extends ScriptBase {
String sql = buff.toString(); String sql = buff.toString();
add(sql, true); add(sql, true);
} }
} finally {
IOUtils.closeSilently(reader);
} }
break; break;
} }
......
...@@ -46,8 +46,7 @@ public class ConditionInSelect extends Condition { ...@@ -46,8 +46,7 @@ public class ConditionInSelect extends Condition {
if (!query.hasOrder()) { if (!query.hasOrder()) {
query.setDistinct(true); query.setDistinct(true);
} }
LocalResult rows = query.query(0); try (LocalResult rows = query.query(0)) {
try {
Value l = left.getValue(session); Value l = left.getValue(session);
if (rows.getRowCount() == 0) { if (rows.getRowCount() == 0) {
return ValueBoolean.get(all); return ValueBoolean.get(all);
...@@ -73,8 +72,6 @@ public class ConditionInSelect extends Condition { ...@@ -73,8 +72,6 @@ public class ConditionInSelect extends Condition {
return ValueNull.INSTANCE; return ValueNull.INSTANCE;
} }
return ValueBoolean.get(false); return ValueBoolean.get(false);
} finally {
rows.close();
} }
} }
......
...@@ -122,7 +122,7 @@ public class Function extends Expression implements FunctionCall { ...@@ -122,7 +122,7 @@ public class Function extends Expression implements FunctionCall {
NVL2 = 228, DECODE = 229, ARRAY_CONTAINS = 230, FILE_WRITE = 232; NVL2 = 228, DECODE = 229, ARRAY_CONTAINS = 230, FILE_WRITE = 232;
public static final int REGEXP_LIKE = 240; public static final int REGEXP_LIKE = 240;
/** /**
* Used in MySQL-style INSERT ... ON DUPLICATE KEY UPDATE ... VALUES * Used in MySQL-style INSERT ... ON DUPLICATE KEY UPDATE ... VALUES
*/ */
...@@ -1636,12 +1636,9 @@ public class Function extends Expression implements FunctionCall { ...@@ -1636,12 +1636,9 @@ public class Function extends Expression implements FunctionCall {
String fileName = v1.getString(); String fileName = v1.getString();
try { try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName); FileOutputStream fileOutputStream = new FileOutputStream(fileName);
InputStream in = v0.getInputStream(); try (InputStream in = v0.getInputStream()) {
try {
result = ValueLong.get(IOUtils.copyAndClose(in, result = ValueLong.get(IOUtils.copyAndClose(in,
fileOutputStream)); fileOutputStream));
} finally {
in.close();
} }
} catch (IOException e) { } catch (IOException e) {
throw DbException.convertIOException(e, fileName); throw DbException.convertIOException(e, fileName);
......
...@@ -33,8 +33,7 @@ public class Subquery extends Expression { ...@@ -33,8 +33,7 @@ public class Subquery extends Expression {
@Override @Override
public Value getValue(Session session) { public Value getValue(Session session) {
query.setSession(session); query.setSession(session);
ResultInterface result = query.query(2); try (ResultInterface result = query.query(2)) {
try {
int rowcount = result.getRowCount(); int rowcount = result.getRowCount();
if (rowcount > 1) { if (rowcount > 1) {
throw DbException.get(ErrorCode.SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW); throw DbException.get(ErrorCode.SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW);
...@@ -52,8 +51,6 @@ public class Subquery extends Expression { ...@@ -52,8 +51,6 @@ public class Subquery extends Expression {
} }
} }
return v; return v;
} finally {
result.close();
} }
} }
......
...@@ -16,13 +16,12 @@ import java.io.PipedInputStream; ...@@ -16,13 +16,12 @@ import java.io.PipedInputStream;
import java.io.PipedOutputStream; import java.io.PipedOutputStream;
import java.sql.Blob; import java.sql.Blob;
import java.sql.SQLException; import java.sql.SQLException;
import org.h2.api.ErrorCode; import org.h2.api.ErrorCode;
import org.h2.engine.Constants; import org.h2.engine.Constants;
import org.h2.message.DbException; import org.h2.message.DbException;
import org.h2.message.TraceObject; import org.h2.message.TraceObject;
import org.h2.util.Task;
import org.h2.util.IOUtils; import org.h2.util.IOUtils;
import org.h2.util.Task;
import org.h2.value.Value; import org.h2.value.Value;
/** /**
...@@ -89,12 +88,9 @@ public class JdbcBlob extends TraceObject implements Blob { ...@@ -89,12 +88,9 @@ public class JdbcBlob extends TraceObject implements Blob {
} }
checkClosed(); checkClosed();
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = value.getInputStream(); try (InputStream in = value.getInputStream()) {
try {
IOUtils.skipFully(in, pos - 1); IOUtils.skipFully(in, pos - 1);
IOUtils.copy(in, out, length); IOUtils.copy(in, out, length);
} finally {
in.close();
} }
return out.toByteArray(); return out.toByteArray();
} catch (Exception e) { } catch (Exception e) {
......
...@@ -17,7 +17,6 @@ import java.io.Writer; ...@@ -17,7 +17,6 @@ import java.io.Writer;
import java.sql.Clob; import java.sql.Clob;
import java.sql.NClob; import java.sql.NClob;
import java.sql.SQLException; import java.sql.SQLException;
import org.h2.api.ErrorCode; import org.h2.api.ErrorCode;
import org.h2.engine.Constants; import org.h2.engine.Constants;
import org.h2.message.DbException; import org.h2.message.DbException;
...@@ -189,12 +188,9 @@ public class JdbcClob extends TraceObject implements NClob ...@@ -189,12 +188,9 @@ public class JdbcClob extends TraceObject implements NClob
} }
StringWriter writer = new StringWriter( StringWriter writer = new StringWriter(
Math.min(Constants.IO_BUFFER_SIZE, length)); Math.min(Constants.IO_BUFFER_SIZE, length));
Reader reader = value.getReader(); try (Reader reader = value.getReader()) {
try {
IOUtils.skipFully(reader, pos - 1); IOUtils.skipFully(reader, pos - 1);
IOUtils.copyAndCloseInput(reader, writer, length); IOUtils.copyAndCloseInput(reader, writer, length);
} finally {
reader.close();
} }
return writer.toString(); return writer.toString();
} catch (Exception e) { } catch (Exception e) {
......
...@@ -17,14 +17,11 @@ import javax.sql.XAConnection; ...@@ -17,14 +17,11 @@ import javax.sql.XAConnection;
import javax.transaction.xa.XAException; import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource; import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid; import javax.transaction.xa.Xid;
import org.h2.api.ErrorCode; import org.h2.api.ErrorCode;
import org.h2.jdbc.JdbcConnection; import org.h2.jdbc.JdbcConnection;
import org.h2.util.JdbcUtils;
import org.h2.util.New;
import org.h2.message.DbException; import org.h2.message.DbException;
import org.h2.message.TraceObject; import org.h2.message.TraceObject;
import org.h2.util.New;
/** /**
...@@ -193,9 +190,7 @@ public class JdbcXAConnection extends TraceObject implements XAConnection, ...@@ -193,9 +190,7 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
public Xid[] recover(int flag) throws XAException { public Xid[] recover(int flag) throws XAException {
debugCodeCall("recover", quoteFlags(flag)); debugCodeCall("recover", quoteFlags(flag));
checkOpen(); checkOpen();
Statement stat = null; try (Statement stat = physicalConn.createStatement()) {
try {
stat = physicalConn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM " + ResultSet rs = stat.executeQuery("SELECT * FROM " +
"INFORMATION_SCHEMA.IN_DOUBT ORDER BY TRANSACTION"); "INFORMATION_SCHEMA.IN_DOUBT ORDER BY TRANSACTION");
ArrayList<Xid> list = New.arrayList(); ArrayList<Xid> list = New.arrayList();
...@@ -216,8 +211,6 @@ public class JdbcXAConnection extends TraceObject implements XAConnection, ...@@ -216,8 +211,6 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
XAException xa = new XAException(XAException.XAER_RMERR); XAException xa = new XAException(XAException.XAER_RMERR);
xa.initCause(e); xa.initCause(e);
throw xa; throw xa;
} finally {
JdbcUtils.closeSilently(stat);
} }
} }
...@@ -236,15 +229,12 @@ public class JdbcXAConnection extends TraceObject implements XAConnection, ...@@ -236,15 +229,12 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
if (!currentTransaction.equals(xid)) { if (!currentTransaction.equals(xid)) {
throw new XAException(XAException.XAER_INVAL); throw new XAException(XAException.XAER_INVAL);
} }
Statement stat = null;
try { try (Statement stat = physicalConn.createStatement()) {
stat = physicalConn.createStatement();
stat.execute("PREPARE COMMIT " + JdbcXid.toString(xid)); stat.execute("PREPARE COMMIT " + JdbcXid.toString(xid));
prepared = true; prepared = true;
} catch (SQLException e) { } catch (SQLException e) {
throw convertException(e); throw convertException(e);
} finally {
JdbcUtils.closeSilently(stat);
} }
return XA_OK; return XA_OK;
} }
...@@ -275,12 +265,8 @@ public class JdbcXAConnection extends TraceObject implements XAConnection, ...@@ -275,12 +265,8 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
} }
try { try {
if (prepared) { if (prepared) {
Statement stat = null; try (Statement stat = physicalConn.createStatement()) {
try {
stat = physicalConn.createStatement();
stat.execute("ROLLBACK TRANSACTION " + JdbcXid.toString(xid)); stat.execute("ROLLBACK TRANSACTION " + JdbcXid.toString(xid));
} finally {
JdbcUtils.closeSilently(stat);
} }
prepared = false; prepared = false;
} else { } else {
...@@ -355,20 +341,19 @@ public class JdbcXAConnection extends TraceObject implements XAConnection, ...@@ -355,20 +341,19 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
if (isDebugEnabled()) { if (isDebugEnabled()) {
debugCode("commit("+JdbcXid.toString(xid)+", "+onePhase+");"); debugCode("commit("+JdbcXid.toString(xid)+", "+onePhase+");");
} }
Statement stat = null;
try { try {
if (onePhase) { if (onePhase) {
physicalConn.commit(); physicalConn.commit();
} else { } else {
stat = physicalConn.createStatement(); try (Statement stat = physicalConn.createStatement()) {
stat.execute("COMMIT TRANSACTION " + JdbcXid.toString(xid)); stat.execute("COMMIT TRANSACTION " + JdbcXid.toString(xid));
prepared = false; prepared = false;
}
} }
physicalConn.setAutoCommit(true); physicalConn.setAutoCommit(true);
} catch (SQLException e) { } catch (SQLException e) {
throw convertException(e); throw convertException(e);
} finally {
JdbcUtils.closeSilently(stat);
} }
currentTransaction = null; currentTransaction = null;
} }
......
...@@ -24,7 +24,7 @@ import org.h2.value.ValueArray; ...@@ -24,7 +24,7 @@ import org.h2.value.ValueArray;
* and it is also used directly by the ResultSet class in the embedded mode. * and it is also used directly by the ResultSet class in the embedded mode.
* If the result does not fit in memory, it is written to a temporary file. * If the result does not fit in memory, it is written to a temporary file.
*/ */
public class LocalResult implements ResultInterface, ResultTarget { public class LocalResult implements ResultInterface, ResultTarget, AutoCloseable {
private int maxMemoryRows; private int maxMemoryRows;
private Session session; private Session session;
......
...@@ -11,7 +11,7 @@ import org.h2.value.Value; ...@@ -11,7 +11,7 @@ import org.h2.value.Value;
* The result interface is used by the LocalResult and ResultRemote class. * The result interface is used by the LocalResult and ResultRemote class.
* A result may contain rows, or just an update count. * A result may contain rows, or just an update count.
*/ */
public interface ResultInterface { public interface ResultInterface extends AutoCloseable {
/** /**
* Go to the beginning of the result, that means * Go to the beginning of the result, that means
......
...@@ -92,9 +92,8 @@ public class TcpServer implements Service { ...@@ -92,9 +92,8 @@ public class TcpServer implements Service {
Connection conn = Driver.load().connect("jdbc:h2:" + Connection conn = Driver.load().connect("jdbc:h2:" +
getManagementDbName(port), prop); getManagementDbName(port), prop);
managementDb = conn; managementDb = conn;
Statement stat = null;
try { try (Statement stat = conn.createStatement()) {
stat = conn.createStatement();
stat.execute("CREATE ALIAS IF NOT EXISTS STOP_SERVER FOR \"" + stat.execute("CREATE ALIAS IF NOT EXISTS STOP_SERVER FOR \"" +
TcpServer.class.getName() + ".stopServer\""); TcpServer.class.getName() + ".stopServer\"");
stat.execute("CREATE TABLE IF NOT EXISTS SESSIONS" + stat.execute("CREATE TABLE IF NOT EXISTS SESSIONS" +
...@@ -104,8 +103,6 @@ public class TcpServer implements Service { ...@@ -104,8 +103,6 @@ public class TcpServer implements Service {
"INSERT INTO SESSIONS VALUES(?, ?, ?, NOW())"); "INSERT INTO SESSIONS VALUES(?, ?, ?, NOW())");
managementDbRemove = conn.prepareStatement( managementDbRemove = conn.prepareStatement(
"DELETE FROM SESSIONS WHERE ID=?"); "DELETE FROM SESSIONS WHERE ID=?");
} finally {
JdbcUtils.closeSilently(stat);
} }
SERVERS.put(port, this); SERVERS.put(port, this);
} }
......
...@@ -28,7 +28,6 @@ import java.sql.Types; ...@@ -28,7 +28,6 @@ import java.sql.Types;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Properties; import java.util.Properties;
import org.h2.command.CommandInterface; import org.h2.command.CommandInterface;
import org.h2.engine.ConnectionInfo; import org.h2.engine.ConnectionInfo;
import org.h2.engine.SysProperties; import org.h2.engine.SysProperties;
...@@ -37,7 +36,6 @@ import org.h2.jdbc.JdbcPreparedStatement; ...@@ -37,7 +36,6 @@ import org.h2.jdbc.JdbcPreparedStatement;
import org.h2.jdbc.JdbcStatement; import org.h2.jdbc.JdbcStatement;
import org.h2.message.DbException; import org.h2.message.DbException;
import org.h2.mvstore.DataUtils; import org.h2.mvstore.DataUtils;
import org.h2.util.IOUtils;
import org.h2.util.JdbcUtils; import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils; import org.h2.util.MathUtils;
import org.h2.util.ScriptReader; import org.h2.util.ScriptReader;
...@@ -827,10 +825,8 @@ public class PgServerThread implements Runnable { ...@@ -827,10 +825,8 @@ public class PgServerThread implements Runnable {
} }
private static void installPgCatalog(Statement stat) throws SQLException { private static void installPgCatalog(Statement stat) throws SQLException {
Reader r = null; try (Reader r = new InputStreamReader(new ByteArrayInputStream(Utils
try { .getResource("/org/h2/server/pg/pg_catalog.sql")))) {
r = new InputStreamReader(new ByteArrayInputStream(Utils
.getResource("/org/h2/server/pg/pg_catalog.sql")));
ScriptReader reader = new ScriptReader(r); ScriptReader reader = new ScriptReader(r);
while (true) { while (true) {
String sql = reader.readStatement(); String sql = reader.readStatement();
...@@ -842,8 +838,6 @@ public class PgServerThread implements Runnable { ...@@ -842,8 +838,6 @@ public class PgServerThread implements Runnable {
reader.close(); reader.close();
} catch (IOException e) { } catch (IOException e) {
throw DbException.convertIOException(e, "Can not read pg_catalog resource"); throw DbException.convertIOException(e, "Can not read pg_catalog resource");
} finally {
IOUtils.closeSilently(r);
} }
} }
......
...@@ -32,7 +32,6 @@ import java.util.Locale; ...@@ -32,7 +32,6 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.Random; import java.util.Random;
import org.h2.api.ErrorCode; import org.h2.api.ErrorCode;
import org.h2.bnf.Bnf; import org.h2.bnf.Bnf;
import org.h2.bnf.context.DbColumn; import org.h2.bnf.context.DbColumn;
...@@ -660,10 +659,9 @@ public class WebApp { ...@@ -660,10 +659,9 @@ public class WebApp {
treeIndex = addColumns(mainSchema, view, buff, treeIndex = addColumns(mainSchema, view, buff,
treeIndex, notManyTables, columnsBuffer); treeIndex, notManyTables, columnsBuffer);
if (schema.getContents().isH2()) { if (schema.getContents().isH2()) {
PreparedStatement prep = null;
try { try (PreparedStatement prep = conn.prepareStatement("SELECT * FROM " +
prep = conn.prepareStatement("SELECT * FROM " + "INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=?")) {
"INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=?");
prep.setString(1, view.getName()); prep.setString(1, view.getName());
ResultSet rs = prep.executeQuery(); ResultSet rs = prep.executeQuery();
if (rs.next()) { if (rs.next()) {
...@@ -675,8 +673,6 @@ public class WebApp { ...@@ -675,8 +673,6 @@ public class WebApp {
treeIndex++; treeIndex++;
} }
rs.close(); rs.close();
} finally {
JdbcUtils.closeSilently(prep);
} }
} }
buff.append("addTable('" + buff.append("addTable('" +
...@@ -717,9 +713,7 @@ public class WebApp { ...@@ -717,9 +713,7 @@ public class WebApp {
treeIndex = addTablesAndViews(schema, false, buff, treeIndex); treeIndex = addTablesAndViews(schema, false, buff, treeIndex);
} }
if (isH2) { if (isH2) {
Statement stat = null; try (Statement stat = conn.createStatement()) {
try {
stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM " + ResultSet rs = stat.executeQuery("SELECT * FROM " +
"INFORMATION_SCHEMA.SEQUENCES ORDER BY SEQUENCE_NAME"); "INFORMATION_SCHEMA.SEQUENCES ORDER BY SEQUENCE_NAME");
for (int i = 0; rs.next(); i++) { for (int i = 0; rs.next(); i++) {
...@@ -773,8 +767,6 @@ public class WebApp { ...@@ -773,8 +767,6 @@ public class WebApp {
} }
} }
rs.close(); rs.close();
} finally {
JdbcUtils.closeSilently(stat);
} }
} }
DatabaseMetaData meta = session.getMetaData(); DatabaseMetaData meta = session.getMetaData();
......
...@@ -5,12 +5,10 @@ ...@@ -5,12 +5,10 @@
*/ */
package org.h2.store; package org.h2.store;
import java.io.IOException;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.h2.api.ErrorCode; import org.h2.api.ErrorCode;
import org.h2.engine.Constants; import org.h2.engine.Constants;
import org.h2.message.DbException; import org.h2.message.DbException;
...@@ -51,23 +49,13 @@ public class FileLister { ...@@ -51,23 +49,13 @@ public class FileLister {
message).getSQLException(); message).getSQLException();
} }
} else if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) { } else if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) {
FileChannel f = null; try (FileChannel f = FilePath.get(fileName).open("r")) {
try {
f = FilePath.get(fileName).open("r");
java.nio.channels.FileLock lock = f.tryLock(0, Long.MAX_VALUE, true); java.nio.channels.FileLock lock = f.tryLock(0, Long.MAX_VALUE, true);
lock.release(); lock.release();
} catch (Exception e) { } catch (Exception e) {
throw DbException.get( throw DbException.get(
ErrorCode.CANNOT_CHANGE_SETTING_WHEN_OPEN_1, e, ErrorCode.CANNOT_CHANGE_SETTING_WHEN_OPEN_1, e,
message).getSQLException(); message).getSQLException();
} finally {
if (f != null) {
try {
f.close();
} catch (IOException e) {
// ignore
}
}
} }
} }
} }
......
...@@ -210,11 +210,8 @@ public class FileLock implements Runnable { ...@@ -210,11 +210,8 @@ public class FileLock implements Runnable {
*/ */
public Properties save() { public Properties save() {
try { try {
OutputStream out = FileUtils.newOutputStream(fileName, false); try (OutputStream out = FileUtils.newOutputStream(fileName, false)) {
try {
properties.store(out, MAGIC); properties.store(out, MAGIC);
} finally {
out.close();
} }
lastWrite = FileUtils.lastModified(fileName); lastWrite = FileUtils.lastModified(fileName);
if (trace.isDebugEnabled()) { if (trace.isDebugEnabled()) {
......
...@@ -55,11 +55,8 @@ public class FilePathZip extends FilePath { ...@@ -55,11 +55,8 @@ public class FilePathZip extends FilePath {
if (entryName.length() == 0) { if (entryName.length() == 0) {
return true; return true;
} }
ZipFile file = openZipFile(); try (ZipFile file = openZipFile()) {
try {
return file.getEntry(entryName) != null; return file.getEntry(entryName) != null;
} finally {
file.close();
} }
} catch (IOException e) { } catch (IOException e) {
return false; return false;
...@@ -95,8 +92,7 @@ public class FilePathZip extends FilePath { ...@@ -95,8 +92,7 @@ public class FilePathZip extends FilePath {
if (entryName.length() == 0) { if (entryName.length() == 0) {
return true; return true;
} }
ZipFile file = openZipFile(); try (ZipFile file = openZipFile()) {
try {
Enumeration<? extends ZipEntry> en = file.entries(); Enumeration<? extends ZipEntry> en = file.entries();
while (en.hasMoreElements()) { while (en.hasMoreElements()) {
ZipEntry entry = en.nextElement(); ZipEntry entry = en.nextElement();
...@@ -111,8 +107,6 @@ public class FilePathZip extends FilePath { ...@@ -111,8 +107,6 @@ public class FilePathZip extends FilePath {
} }
} }
} }
} finally {
file.close();
} }
return false; return false;
} catch (IOException e) { } catch (IOException e) {
...@@ -133,12 +127,9 @@ public class FilePathZip extends FilePath { ...@@ -133,12 +127,9 @@ public class FilePathZip extends FilePath {
@Override @Override
public long size() { public long size() {
try { try {
ZipFile file = openZipFile(); try (ZipFile file = openZipFile()) {
try {
ZipEntry entry = file.getEntry(getEntryName()); ZipEntry entry = file.getEntry(getEntryName());
return entry == null ? 0 : entry.getSize(); return entry == null ? 0 : entry.getSize();
} finally {
file.close();
} }
} catch (IOException e) { } catch (IOException e) {
return 0; return 0;
...@@ -156,8 +147,7 @@ public class FilePathZip extends FilePath { ...@@ -156,8 +147,7 @@ public class FilePathZip extends FilePath {
if (!path.endsWith("/")) { if (!path.endsWith("/")) {
path += "/"; path += "/";
} }
ZipFile file = openZipFile(); try (ZipFile file = openZipFile()) {
try {
String dirName = getEntryName(); String dirName = getEntryName();
String prefix = path.substring(0, path.length() - dirName.length()); String prefix = path.substring(0, path.length() - dirName.length());
Enumeration<? extends ZipEntry> en = file.entries(); Enumeration<? extends ZipEntry> en = file.entries();
...@@ -175,8 +165,6 @@ public class FilePathZip extends FilePath { ...@@ -175,8 +165,6 @@ public class FilePathZip extends FilePath {
list.add(getPath(prefix + name)); list.add(getPath(prefix + name));
} }
} }
} finally {
file.close();
} }
return list; return list;
} catch (IOException e) { } catch (IOException e) {
......
...@@ -15,7 +15,6 @@ import java.sql.Types; ...@@ -15,7 +15,6 @@ import java.sql.Types;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import org.h2.api.ErrorCode; import org.h2.api.ErrorCode;
import org.h2.command.Prepared; import org.h2.command.Prepared;
import org.h2.engine.Session; import org.h2.engine.Session;
...@@ -28,7 +27,6 @@ import org.h2.message.DbException; ...@@ -28,7 +27,6 @@ import org.h2.message.DbException;
import org.h2.result.Row; import org.h2.result.Row;
import org.h2.result.RowList; import org.h2.result.RowList;
import org.h2.schema.Schema; import org.h2.schema.Schema;
import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils; import org.h2.util.MathUtils;
import org.h2.util.New; import org.h2.util.New;
import org.h2.util.StatementBuilder; import org.h2.util.StatementBuilder;
...@@ -169,9 +167,8 @@ public class TableLink extends Table { ...@@ -169,9 +167,8 @@ public class TableLink extends Table {
qualifiedTableName = originalTable; qualifiedTableName = originalTable;
} }
// check if the table is accessible // check if the table is accessible
Statement stat = null;
try { try (Statement stat = conn.getConnection().createStatement()) {
stat = conn.getConnection().createStatement();
rs = stat.executeQuery("SELECT * FROM " + rs = stat.executeQuery("SELECT * FROM " +
qualifiedTableName + " T WHERE 1=0"); qualifiedTableName + " T WHERE 1=0");
if (columnList.size() == 0) { if (columnList.size() == 0) {
...@@ -197,8 +194,6 @@ public class TableLink extends Table { ...@@ -197,8 +194,6 @@ public class TableLink extends Table {
} catch (Exception e) { } catch (Exception e) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, e, throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, e,
originalTable + "(" + e.toString() + ")"); originalTable + "(" + e.toString() + ")");
} finally {
JdbcUtils.closeSilently(stat);
} }
Column[] cols = new Column[columnList.size()]; Column[] cols = new Column[columnList.size()];
columnList.toArray(cols); columnList.toArray(cols);
......
...@@ -11,7 +11,6 @@ import java.io.OutputStream; ...@@ -11,7 +11,6 @@ import java.io.OutputStream;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import org.h2.engine.Constants; import org.h2.engine.Constants;
import org.h2.engine.SysProperties; import org.h2.engine.SysProperties;
import org.h2.message.DbException; import org.h2.message.DbException;
...@@ -74,9 +73,8 @@ public class Restore extends Tool { ...@@ -74,9 +73,8 @@ public class Restore extends Tool {
private static String getOriginalDbName(String fileName, String db) private static String getOriginalDbName(String fileName, String db)
throws IOException { throws IOException {
InputStream in = null;
try { try (InputStream in = FileUtils.newInputStream(fileName)) {
in = FileUtils.newInputStream(fileName);
ZipInputStream zipIn = new ZipInputStream(in); ZipInputStream zipIn = new ZipInputStream(in);
String originalDbName = null; String originalDbName = null;
boolean multiple = false; boolean multiple = false;
...@@ -108,8 +106,6 @@ public class Restore extends Tool { ...@@ -108,8 +106,6 @@ public class Restore extends Tool {
throw new IOException("Multiple databases found, but not " + db); throw new IOException("Multiple databases found, but not " + db);
} }
return originalDbName; return originalDbName;
} finally {
IOUtils.closeSilently(in);
} }
} }
......
...@@ -9,7 +9,6 @@ import java.sql.Connection; ...@@ -9,7 +9,6 @@ import java.sql.Connection;
import java.sql.DriverManager; import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import org.h2.util.JdbcUtils; import org.h2.util.JdbcUtils;
import org.h2.util.StringUtils; import org.h2.util.StringUtils;
import org.h2.util.Tool; import org.h2.util.Tool;
...@@ -134,13 +133,10 @@ public class Script extends Tool { ...@@ -134,13 +133,10 @@ public class Script extends Tool {
*/ */
public static void process(Connection conn, public static void process(Connection conn,
String fileName, String options1, String options2) throws SQLException { String fileName, String options1, String options2) throws SQLException {
Statement stat = null;
try { try (Statement stat = conn.createStatement()) {
stat = conn.createStatement();
String sql = "SCRIPT " + options1 + " TO '" + fileName + "' " + options2; String sql = "SCRIPT " + options1 + " TO '" + fileName + "' " + options2;
stat.execute(sql); stat.execute(sql);
} finally {
JdbcUtils.closeSilently(stat);
} }
} }
......
...@@ -17,10 +17,10 @@ import java.io.PrintWriter; ...@@ -17,10 +17,10 @@ import java.io.PrintWriter;
import java.io.Writer; import java.io.Writer;
import java.util.Collections; import java.util.Collections;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Properties; import java.util.Properties;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.Vector; import java.util.Vector;
import java.util.Map.Entry;
import org.h2.store.fs.FileUtils; import org.h2.store.fs.FileUtils;
/** /**
...@@ -88,14 +88,8 @@ public class SortedProperties extends Properties { ...@@ -88,14 +88,8 @@ public class SortedProperties extends Properties {
throws IOException { throws IOException {
SortedProperties prop = new SortedProperties(); SortedProperties prop = new SortedProperties();
if (FileUtils.exists(fileName)) { if (FileUtils.exists(fileName)) {
InputStream in = null; try (InputStream in = FileUtils.newInputStream(fileName)) {
try {
in = FileUtils.newInputStream(fileName);
prop.load(in); prop.load(in);
} finally {
if (in != null) {
in.close();
}
} }
} }
return prop; return prop;
......
...@@ -282,7 +282,7 @@ public class SourceCompiler { ...@@ -282,7 +282,7 @@ public class SourceCompiler {
.getStandardFileManager(null, null, null)); .getStandardFileManager(null, null, null));
ArrayList<JavaFileObject> compilationUnits = new ArrayList<JavaFileObject>(); ArrayList<JavaFileObject> compilationUnits = new ArrayList<JavaFileObject>();
compilationUnits.add(new StringJavaFileObject(fullClassName, source)); compilationUnits.add(new StringJavaFileObject(fullClassName, source));
// can not concurrently compile // cannot concurrently compile
synchronized (JAVA_COMPILER) { synchronized (JAVA_COMPILER) {
JAVA_COMPILER.getTask(writer, fileManager, null, null, JAVA_COMPILER.getTask(writer, fileManager, null, null,
null, compilationUnits).call(); null, compilationUnits).call();
......
...@@ -478,8 +478,8 @@ public class Utils { ...@@ -478,8 +478,8 @@ public class Utils {
} }
return IOUtils.readBytesAndClose(in, 0); return IOUtils.readBytesAndClose(in, 0);
} }
ZipInputStream zipIn = new ZipInputStream(in);
try { try (ZipInputStream zipIn = new ZipInputStream(in)) {
while (true) { while (true) {
ZipEntry entry = zipIn.getNextEntry(); ZipEntry entry = zipIn.getNextEntry();
if (entry == null) { if (entry == null) {
...@@ -500,8 +500,6 @@ public class Utils { ...@@ -500,8 +500,6 @@ public class Utils {
} catch (IOException e) { } catch (IOException e) {
// if this happens we have a real problem // if this happens we have a real problem
e.printStackTrace(); e.printStackTrace();
} finally {
zipIn.close();
} }
return null; return null;
} }
......
...@@ -13,7 +13,6 @@ import java.io.InputStream; ...@@ -13,7 +13,6 @@ import java.io.InputStream;
import java.io.Reader; import java.io.Reader;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import org.h2.engine.Constants; import org.h2.engine.Constants;
import org.h2.engine.SysProperties; import org.h2.engine.SysProperties;
import org.h2.message.DbException; import org.h2.message.DbException;
...@@ -222,9 +221,8 @@ public class ValueLob extends Value { ...@@ -222,9 +221,8 @@ public class ValueLob extends Value {
private void createFromReader(char[] buff, int len, Reader in, private void createFromReader(char[] buff, int len, Reader in,
long remaining, DataHandler h) throws IOException { long remaining, DataHandler h) throws IOException {
FileStoreOutputStream out = initLarge(h); try (FileStoreOutputStream out = initLarge(h)) {
boolean compress = h.getLobCompressionAlgorithm(Value.CLOB) != null; boolean compress = h.getLobCompressionAlgorithm(Value.CLOB) != null;
try {
while (true) { while (true) {
precision += len; precision += len;
byte[] b = new String(buff, 0, len).getBytes(Constants.UTF8); byte[] b = new String(buff, 0, len).getBytes(Constants.UTF8);
...@@ -239,8 +237,6 @@ public class ValueLob extends Value { ...@@ -239,8 +237,6 @@ public class ValueLob extends Value {
break; break;
} }
} }
} finally {
out.close();
} }
} }
...@@ -421,9 +417,8 @@ public class ValueLob extends Value { ...@@ -421,9 +417,8 @@ public class ValueLob extends Value {
private void createFromStream(byte[] buff, int len, InputStream in, private void createFromStream(byte[] buff, int len, InputStream in,
long remaining, DataHandler h) throws IOException { long remaining, DataHandler h) throws IOException {
FileStoreOutputStream out = initLarge(h); try (FileStoreOutputStream out = initLarge(h)) {
boolean compress = h.getLobCompressionAlgorithm(Value.BLOB) != null; boolean compress = h.getLobCompressionAlgorithm(Value.BLOB) != null;
try {
while (true) { while (true) {
precision += len; precision += len;
out.write(buff, 0, len); out.write(buff, 0, len);
...@@ -437,8 +432,6 @@ public class ValueLob extends Value { ...@@ -437,8 +432,6 @@ public class ValueLob extends Value {
break; break;
} }
} }
} finally {
out.close();
} }
} }
......
...@@ -13,7 +13,6 @@ import java.io.InputStream; ...@@ -13,7 +13,6 @@ import java.io.InputStream;
import java.io.Reader; import java.io.Reader;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import org.h2.engine.Constants; import org.h2.engine.Constants;
import org.h2.engine.SysProperties; import org.h2.engine.SysProperties;
import org.h2.message.DbException; import org.h2.message.DbException;
...@@ -93,9 +92,9 @@ public class ValueLobDb extends Value implements Value.ValueClob, ...@@ -93,9 +92,9 @@ public class ValueLobDb extends Value implements Value.ValueClob,
this.fileName = createTempLobFileName(handler); this.fileName = createTempLobFileName(handler);
this.tempFile = this.handler.openFile(fileName, "rw", false); this.tempFile = this.handler.openFile(fileName, "rw", false);
this.tempFile.autoDelete(); this.tempFile.autoDelete();
FileStoreOutputStream out = new FileStoreOutputStream(tempFile, null, null);
long tmpPrecision = 0; long tmpPrecision = 0;
try { try (FileStoreOutputStream out = new FileStoreOutputStream(tempFile, null, null)) {
char[] buff = new char[Constants.IO_BUFFER_SIZE]; char[] buff = new char[Constants.IO_BUFFER_SIZE];
while (true) { while (true) {
int len = getBufferSize(this.handler, false, remaining); int len = getBufferSize(this.handler, false, remaining);
...@@ -107,8 +106,6 @@ public class ValueLobDb extends Value implements Value.ValueClob, ...@@ -107,8 +106,6 @@ public class ValueLobDb extends Value implements Value.ValueClob,
out.write(data); out.write(data);
tmpPrecision += len; tmpPrecision += len;
} }
} finally {
out.close();
} }
this.precision = tmpPrecision; this.precision = tmpPrecision;
} }
......
...@@ -80,13 +80,10 @@ public class FileFunctions { ...@@ -80,13 +80,10 @@ public class FileFunctions {
* @return the byte array * @return the byte array
*/ */
public static byte[] readFile(String fileName) throws IOException { public static byte[] readFile(String fileName) throws IOException {
RandomAccessFile file = new RandomAccessFile(fileName, "r"); try (RandomAccessFile file = new RandomAccessFile(fileName, "r")) {
try {
byte[] buff = new byte[(int) file.length()]; byte[] buff = new byte[(int) file.length()];
file.readFully(buff); file.readFully(buff);
return buff; return buff;
} finally {
file.close();
} }
} }
} }
...@@ -21,7 +21,6 @@ import java.util.StringTokenizer; ...@@ -21,7 +21,6 @@ import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.h2.test.TestBase; import org.h2.test.TestBase;
import org.h2.tools.Server; import org.h2.tools.Server;
import org.h2.util.JdbcUtils;
import org.h2.util.StringUtils; import org.h2.util.StringUtils;
/** /**
...@@ -186,26 +185,18 @@ class Database { ...@@ -186,26 +185,18 @@ class Database {
Connection newConn = DriverManager.getConnection(url, user, password); Connection newConn = DriverManager.getConnection(url, user, password);
if (url.startsWith("jdbc:derby:")) { if (url.startsWith("jdbc:derby:")) {
// Derby: use higher cache size // Derby: use higher cache size
Statement s = null; try (Statement s = newConn.createStatement()) {
try {
s = newConn.createStatement();
// stat.execute("CALL // stat.execute("CALL
// SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY( // SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(
// 'derby.storage.pageCacheSize', '64')"); // 'derby.storage.pageCacheSize', '64')");
// stat.execute("CALL // stat.execute("CALL
// SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY( // SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(
// 'derby.storage.pageSize', '8192')"); // 'derby.storage.pageSize', '8192')");
} finally {
JdbcUtils.closeSilently(s);
} }
} else if (url.startsWith("jdbc:hsqldb:")) { } else if (url.startsWith("jdbc:hsqldb:")) {
// HSQLDB: use a WRITE_DELAY of 1 second // HSQLDB: use a WRITE_DELAY of 1 second
Statement s = null; try (Statement s = newConn.createStatement()){
try {
s = newConn.createStatement();
s.execute("SET WRITE_DELAY 1"); s.execute("SET WRITE_DELAY 1");
} finally {
JdbcUtils.closeSilently(s);
} }
} }
return newConn; return newConn;
......
...@@ -29,9 +29,7 @@ public class Profile extends Thread { ...@@ -29,9 +29,7 @@ public class Profile extends Thread {
private BufferedWriter trace; private BufferedWriter trace;
private Profile() { private Profile() {
LineNumberReader r = null; try (LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"))) {
try {
r = new LineNumberReader(new FileReader("profile.txt"));
while (r.readLine() != null) { while (r.readLine() != null) {
// nothing - just count lines // nothing - just count lines
} }
...@@ -43,8 +41,6 @@ public class Profile extends Thread { ...@@ -43,8 +41,6 @@ public class Profile extends Thread {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
} finally {
IOUtils.closeSilently(r);
} }
} }
...@@ -195,9 +191,8 @@ public class Profile extends Thread { ...@@ -195,9 +191,8 @@ public class Profile extends Thread {
list[bigIndex] = -(big + 1); list[bigIndex] = -(big + 1);
index[i] = bigIndex; index[i] = bigIndex;
} }
LineNumberReader r = null;
try { try (LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"))) {
r = new LineNumberReader(new FileReader("profile.txt"));
for (int i = 0; i < maxIndex; i++) { for (int i = 0; i < maxIndex; i++) {
String line = r.readLine(); String line = r.readLine();
int k = list[i]; int k = list[i];
...@@ -215,8 +210,6 @@ public class Profile extends Thread { ...@@ -215,8 +210,6 @@ public class Profile extends Thread {
for (int i = 0; i < max; i++) { for (int i = 0; i < max; i++) {
print(text[i]); print(text[i]);
} }
} finally {
IOUtils.closeSilently(r);
} }
} }
......
...@@ -14,7 +14,6 @@ import java.sql.ResultSetMetaData; ...@@ -14,7 +14,6 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.sql.Timestamp; import java.sql.Timestamp;
import org.h2.api.ErrorCode; import org.h2.api.ErrorCode;
import org.h2.store.fs.FileUtils; import org.h2.store.fs.FileUtils;
import org.h2.test.TestBase; import org.h2.test.TestBase;
...@@ -714,12 +713,9 @@ public class TestLinkedTable extends TestBase { ...@@ -714,12 +713,9 @@ public class TestLinkedTable extends TestBase {
String sql = "CREATE LINKED TABLE T(NULL, " + String sql = "CREATE LINKED TABLE T(NULL, " +
"'jdbc:h2:mem:one', 'sa', 'sa', 'TEST') READONLY"; "'jdbc:h2:mem:one', 'sa', 'sa', 'TEST') READONLY";
sb.execute(sql); sb.execute(sql);
ResultSet rs = sb.executeQuery("SELECT * FROM T"); try (ResultSet rs = sb.executeQuery("SELECT * FROM T")) {
try {
assertTrue(rs.next()); assertTrue(rs.next());
assertEquals("POINT (1 1)", rs.getString("THE_GEOM")); assertEquals("POINT (1 1)", rs.getString("THE_GEOM"));
} finally {
rs.close();
} }
sb.execute("DROP TABLE T"); sb.execute("DROP TABLE T");
ca.close(); ca.close();
......
...@@ -10,10 +10,8 @@ import java.sql.DriverManager; ...@@ -10,10 +10,8 @@ import java.sql.DriverManager;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import org.h2.api.DatabaseEventListener; import org.h2.api.DatabaseEventListener;
import org.h2.test.TestBase; import org.h2.test.TestBase;
import org.h2.util.JdbcUtils;
/** /**
* Tests the DatabaseEventListener. * Tests the DatabaseEventListener.
...@@ -112,15 +110,12 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -112,15 +110,12 @@ public class TestListener extends TestBase implements DatabaseEventListener {
if (databaseUrl.toUpperCase().contains("CIPHER")) { if (databaseUrl.toUpperCase().contains("CIPHER")) {
return; return;
} }
Connection conn = null;
try { try (Connection conn = DriverManager.getConnection(databaseUrl, getUser(), getPassword())) {
conn = DriverManager.getConnection(databaseUrl, getUser(), getPassword());
conn.createStatement().execute("DROP TABLE TEST2"); conn.createStatement().execute("DROP TABLE TEST2");
conn.close(); conn.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} finally {
JdbcUtils.closeSilently(conn);
} }
} }
...@@ -134,15 +129,12 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -134,15 +129,12 @@ public class TestListener extends TestBase implements DatabaseEventListener {
if (databaseUrl.toUpperCase().contains("CIPHER")) { if (databaseUrl.toUpperCase().contains("CIPHER")) {
return; return;
} }
Connection conn = null;
try { try (Connection conn = DriverManager.getConnection(databaseUrl, getUser(), getPassword())) {
conn = DriverManager.getConnection(databaseUrl, getUser(), getPassword());
conn.createStatement().execute("CREATE TABLE IF NOT EXISTS TEST2(ID INT)"); conn.createStatement().execute("CREATE TABLE IF NOT EXISTS TEST2(ID INT)");
conn.close(); conn.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} finally {
JdbcUtils.closeSilently(conn);
} }
} }
......
...@@ -81,16 +81,13 @@ public class TestMultiThread extends TestBase implements Runnable { ...@@ -81,16 +81,13 @@ public class TestMultiThread extends TestBase implements Runnable {
Task t = new Task() { Task t = new Task() {
@Override @Override
public void call() throws Exception { public void call() throws Exception {
Connection c2 = getConnection(url); try (Connection c2 = getConnection(url)) {
Statement stat = c2.createStatement(); Statement stat = c2.createStatement();
try {
for (int i = 0; !stop; i++) { for (int i = 0; !stop; i++) {
stat.execute("create table test" + x + "_" + i); stat.execute("create table test" + x + "_" + i);
c2.getMetaData().getTables(null, null, null, null); c2.getMetaData().getTables(null, null, null, null);
stat.execute("drop table test" + x + "_" + i); stat.execute("drop table test" + x + "_" + i);
} }
} finally {
c2.close();
} }
} }
}; };
...@@ -116,17 +113,14 @@ public class TestMultiThread extends TestBase implements Runnable { ...@@ -116,17 +113,14 @@ public class TestMultiThread extends TestBase implements Runnable {
Task t = new Task() { Task t = new Task() {
@Override @Override
public void call() throws Exception { public void call() throws Exception {
Connection c2 = getConnection(url); try (Connection c2 = getConnection(url)) {
PreparedStatement p2 = c2 PreparedStatement p2 = c2
.prepareStatement("insert into test(data) values(?)"); .prepareStatement("insert into test(data) values(?)");
try {
while (!stop) { while (!stop) {
p2.setCharacterStream(1, new StringReader(new String( p2.setCharacterStream(1, new StringReader(new String(
new char[10 * 1024]))); new char[10 * 1024])));
p2.execute(); p2.execute();
} }
} finally {
c2.close();
} }
} }
}; };
......
...@@ -13,7 +13,6 @@ import java.sql.Statement; ...@@ -13,7 +13,6 @@ import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.h2.api.Trigger; import org.h2.api.Trigger;
import org.h2.test.TestBase; import org.h2.test.TestBase;
import org.h2.util.Task; import org.h2.util.Task;
...@@ -64,8 +63,7 @@ public class TestSequence extends TestBase { ...@@ -64,8 +63,7 @@ public class TestSequence extends TestBase {
tasks[i] = new Task() { tasks[i] = new Task() {
@Override @Override
public void call() throws Exception { public void call() throws Exception {
Connection conn = getConnection(url); try (Connection conn = getConnection(url)) {
try {
PreparedStatement prep = conn.prepareStatement( PreparedStatement prep = conn.prepareStatement(
"insert into test(id) values(next value for test_seq)"); "insert into test(id) values(next value for test_seq)");
PreparedStatement prep2 = conn.prepareStatement( PreparedStatement prep2 = conn.prepareStatement(
...@@ -79,8 +77,6 @@ public class TestSequence extends TestBase { ...@@ -79,8 +77,6 @@ public class TestSequence extends TestBase {
createDropTrigger(conn); createDropTrigger(conn);
} }
} }
} finally {
conn.close();
} }
} }
......
...@@ -12,23 +12,22 @@ import java.sql.Savepoint; ...@@ -12,23 +12,22 @@ import java.sql.Savepoint;
import java.sql.Statement; import java.sql.Statement;
import java.sql.Types; import java.sql.Types;
import java.util.Random; import java.util.Random;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.util.AffineTransformation;
import org.h2.api.Aggregate; import org.h2.api.Aggregate;
import org.h2.test.TestBase; import org.h2.test.TestBase;
import org.h2.tools.SimpleResultSet; import org.h2.tools.SimpleResultSet;
import org.h2.tools.SimpleRowSource; import org.h2.tools.SimpleRowSource;
import org.h2.value.DataType; import org.h2.value.DataType;
import org.h2.value.Value; import org.h2.value.Value;
import org.h2.value.ValueGeometry;
import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.util.AffineTransformation;
import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader; import com.vividsolutions.jts.io.WKTReader;
import org.h2.value.ValueGeometry;
/** /**
* Spatial datatype and index tests. * Spatial datatype and index tests.
...@@ -190,8 +189,7 @@ public class TestSpatial extends TestBase { ...@@ -190,8 +189,7 @@ public class TestSpatial extends TestBase {
private void testOverlap() throws SQLException { private void testOverlap() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("create memory table test" + stat.execute("create memory table test" +
"(id int primary key, poly geometry)"); "(id int primary key, poly geometry)");
...@@ -209,14 +207,11 @@ public class TestSpatial extends TestBase { ...@@ -209,14 +207,11 @@ public class TestSpatial extends TestBase {
assertEquals(1, rs.getInt("id")); assertEquals(1, rs.getInt("id"));
assertFalse(rs.next()); assertFalse(rs.next());
stat.execute("drop table test"); stat.execute("drop table test");
} finally {
conn.close();
} }
} }
private void testPersistentSpatialIndex() throws SQLException { private void testPersistentSpatialIndex() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("create table test" + stat.execute("create table test" +
"(id int primary key, poly geometry)"); "(id int primary key, poly geometry)");
...@@ -247,17 +242,13 @@ public class TestSpatial extends TestBase { ...@@ -247,17 +242,13 @@ public class TestSpatial extends TestBase {
assertEquals(1, rs.getInt("id")); assertEquals(1, rs.getInt("id"));
assertFalse(rs.next()); assertFalse(rs.next());
rs.close(); rs.close();
} finally {
// Close the database
conn.close();
} }
if (config.memory) { if (config.memory) {
return; return;
} }
conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery( ResultSet rs = stat.executeQuery(
"select * from test " + "select * from test " +
...@@ -266,15 +257,12 @@ public class TestSpatial extends TestBase { ...@@ -266,15 +257,12 @@ public class TestSpatial extends TestBase {
assertEquals(1, rs.getInt("id")); assertEquals(1, rs.getInt("id"));
assertFalse(rs.next()); assertFalse(rs.next());
stat.execute("drop table test"); stat.execute("drop table test");
} finally {
conn.close();
} }
} }
private void testNotOverlap() throws SQLException { private void testNotOverlap() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("create memory table test" + stat.execute("create memory table test" +
"(id int primary key, poly geometry)"); "(id int primary key, poly geometry)");
...@@ -296,8 +284,6 @@ public class TestSpatial extends TestBase { ...@@ -296,8 +284,6 @@ public class TestSpatial extends TestBase {
assertEquals(5, rs.getInt("id")); assertEquals(5, rs.getInt("id"));
assertFalse(rs.next()); assertFalse(rs.next());
stat.execute("drop table test"); stat.execute("drop table test");
} finally {
conn.close();
} }
} }
...@@ -350,14 +336,10 @@ public class TestSpatial extends TestBase { ...@@ -350,14 +336,10 @@ public class TestSpatial extends TestBase {
private void testSpatialIndexQueryMultipleTable() throws SQLException { private void testSpatialIndexQueryMultipleTable() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
createTestTable(stat); createTestTable(stat);
testRoadAndArea(stat); testRoadAndArea(stat);
} finally {
// Close the database
conn.close();
} }
deleteDb("spatial"); deleteDb("spatial");
} }
...@@ -391,9 +373,8 @@ public class TestSpatial extends TestBase { ...@@ -391,9 +373,8 @@ public class TestSpatial extends TestBase {
private void testIndexTransaction() throws SQLException { private void testIndexTransaction() throws SQLException {
// Check session management in index // Check session management in index
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
conn.setAutoCommit(false); conn.setAutoCommit(false);
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
createTestTable(stat); createTestTable(stat);
Savepoint sp = conn.setSavepoint(); Savepoint sp = conn.setSavepoint();
...@@ -429,10 +410,7 @@ public class TestSpatial extends TestBase { ...@@ -429,10 +410,7 @@ public class TestSpatial extends TestBase {
conn.rollback(sp); conn.rollback(sp);
// Check if the index is restored // Check if the index is restored
testRoadAndArea(stat); testRoadAndArea(stat);
} finally {
conn.close();
} }
} }
/** /**
...@@ -503,8 +481,7 @@ public class TestSpatial extends TestBase { ...@@ -503,8 +481,7 @@ public class TestSpatial extends TestBase {
*/ */
private void testJavaAlias() throws SQLException { private void testJavaAlias() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS T_GEOM_FROM_TEXT FOR \"" + stat.execute("CREATE ALIAS T_GEOM_FROM_TEXT FOR \"" +
TestSpatial.class.getName() + ".geomFromText\""); TestSpatial.class.getName() + ".geomFromText\"");
...@@ -518,8 +495,6 @@ public class TestSpatial extends TestBase { ...@@ -518,8 +495,6 @@ public class TestSpatial extends TestBase {
assertTrue(rs.next()); assertTrue(rs.next());
assertEquals("POLYGON ((62 48, 84 48, 84 42, 56 34, 62 48))", assertEquals("POLYGON ((62 48, 84 48, 84 42, 56 34, 62 48))",
rs.getObject(1).toString()); rs.getObject(1).toString());
} finally {
conn.close();
} }
deleteDb("spatial"); deleteDb("spatial");
} }
...@@ -529,8 +504,7 @@ public class TestSpatial extends TestBase { ...@@ -529,8 +504,7 @@ public class TestSpatial extends TestBase {
*/ */
private void testJavaAliasTableFunction() throws SQLException { private void testJavaAliasTableFunction() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS T_RANDOM_GEOM_TABLE FOR \"" + stat.execute("CREATE ALIAS T_RANDOM_GEOM_TABLE FOR \"" +
TestSpatial.class.getName() + ".getRandomGeometryTable\""); TestSpatial.class.getName() + ".getRandomGeometryTable\"");
...@@ -541,8 +515,6 @@ public class TestSpatial extends TestBase { ...@@ -541,8 +515,6 @@ public class TestSpatial extends TestBase {
ResultSet rs = stat.executeQuery("select count(*) from test"); ResultSet rs = stat.executeQuery("select count(*) from test");
assertTrue(rs.next()); assertTrue(rs.next());
assertEquals(20, rs.getInt(1)); assertEquals(20, rs.getInt(1));
} finally {
conn.close();
} }
deleteDb("spatial"); deleteDb("spatial");
} }
...@@ -696,8 +668,7 @@ public class TestSpatial extends TestBase { ...@@ -696,8 +668,7 @@ public class TestSpatial extends TestBase {
*/ */
private void testTableFunctionGeometry() throws SQLException { private void testTableFunctionGeometry() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("CREATE ALIAS POINT_TABLE FOR \"" + stat.execute("CREATE ALIAS POINT_TABLE FOR \"" +
TestSpatial.class.getName() + ".pointTable\""); TestSpatial.class.getName() + ".pointTable\"");
...@@ -709,8 +680,6 @@ public class TestSpatial extends TestBase { ...@@ -709,8 +680,6 @@ public class TestSpatial extends TestBase {
assertEquals("geometry", assertEquals("geometry",
columnMeta.getString("TYPE_NAME").toLowerCase()); columnMeta.getString("TYPE_NAME").toLowerCase());
assertFalse(columnMeta.next()); assertFalse(columnMeta.next());
} finally {
conn.close();
} }
deleteDb("spatial"); deleteDb("spatial");
} }
...@@ -732,8 +701,7 @@ public class TestSpatial extends TestBase { ...@@ -732,8 +701,7 @@ public class TestSpatial extends TestBase {
private void testAggregateWithGeometry() throws SQLException { private void testAggregateWithGeometry() throws SQLException {
deleteDb("spatialIndex"); deleteDb("spatialIndex");
Connection conn = getConnection("spatialIndex"); try (Connection conn = getConnection("spatialIndex")) {
try {
Statement st = conn.createStatement(); Statement st = conn.createStatement();
st.execute("CREATE AGGREGATE TABLE_ENVELOPE FOR \""+ st.execute("CREATE AGGREGATE TABLE_ENVELOPE FOR \""+
TableEnvelope.class.getName()+"\""); TableEnvelope.class.getName()+"\"");
...@@ -747,8 +715,6 @@ public class TestSpatial extends TestBase { ...@@ -747,8 +715,6 @@ public class TestSpatial extends TestBase {
assertTrue(new Envelope(1, 10, 1, 5).equals( assertTrue(new Envelope(1, 10, 1, 5).equals(
((Geometry) rs.getObject(1)).getEnvelopeInternal())); ((Geometry) rs.getObject(1)).getEnvelopeInternal()));
assertFalse(rs.next()); assertFalse(rs.next());
} finally {
conn.close();
} }
deleteDb("spatialIndex"); deleteDb("spatialIndex");
} }
...@@ -793,8 +759,7 @@ public class TestSpatial extends TestBase { ...@@ -793,8 +759,7 @@ public class TestSpatial extends TestBase {
private void testTableViewSpatialPredicate() throws SQLException { private void testTableViewSpatialPredicate() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("drop table if exists test"); stat.execute("drop table if exists test");
stat.execute("drop view if exists test_view"); stat.execute("drop view if exists test_view");
...@@ -819,9 +784,6 @@ public class TestSpatial extends TestBase { ...@@ -819,9 +784,6 @@ public class TestSpatial extends TestBase {
assertEquals(1, rs.getInt("id")); assertEquals(1, rs.getInt("id"));
assertFalse(rs.next()); assertFalse(rs.next());
rs.close(); rs.close();
} finally {
// Close the database
conn.close();
} }
deleteDb("spatial"); deleteDb("spatial");
} }
...@@ -831,16 +793,13 @@ public class TestSpatial extends TestBase { ...@@ -831,16 +793,13 @@ public class TestSpatial extends TestBase {
*/ */
private void testValueGeometryScript() throws SQLException { private void testValueGeometryScript() throws SQLException {
ValueGeometry valueGeometry = ValueGeometry.get("POINT(1 1 5)"); ValueGeometry valueGeometry = ValueGeometry.get("POINT(1 1 5)");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
ResultSet rs = conn.createStatement().executeQuery( ResultSet rs = conn.createStatement().executeQuery(
"SELECT " + valueGeometry.getSQL()); "SELECT " + valueGeometry.getSQL());
assertTrue(rs.next()); assertTrue(rs.next());
Object obj = rs.getObject(1); Object obj = rs.getObject(1);
ValueGeometry g = ValueGeometry.getFromGeometry(obj); ValueGeometry g = ValueGeometry.getFromGeometry(obj);
assertTrue("got: " + g + " exp: " + valueGeometry, valueGeometry.equals(g)); assertTrue("got: " + g + " exp: " + valueGeometry, valueGeometry.equals(g));
} finally {
conn.close();
} }
} }
...@@ -849,8 +808,7 @@ public class TestSpatial extends TestBase { ...@@ -849,8 +808,7 @@ public class TestSpatial extends TestBase {
* be updated. * be updated.
*/ */
private void testInPlaceUpdate() throws SQLException { private void testInPlaceUpdate() throws SQLException {
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
ResultSet rs = conn.createStatement().executeQuery( ResultSet rs = conn.createStatement().executeQuery(
"SELECT 'POINT(1 1)'::geometry"); "SELECT 'POINT(1 1)'::geometry");
assertTrue(rs.next()); assertTrue(rs.next());
...@@ -865,15 +823,12 @@ public class TestSpatial extends TestBase { ...@@ -865,15 +823,12 @@ public class TestSpatial extends TestBase {
assertEquals(1, ((Point) rs.getObject(1)).getX()); assertEquals(1, ((Point) rs.getObject(1)).getX());
assertEquals(1, ((Point) rs.getObject(1)).getY()); assertEquals(1, ((Point) rs.getObject(1)).getY());
rs.close(); rs.close();
} finally {
conn.close();
} }
} }
private void testScanIndexOnNonSpatialQuery() throws SQLException { private void testScanIndexOnNonSpatialQuery() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("drop table if exists test"); stat.execute("drop table if exists test");
stat.execute("create table test(id serial primary key, " + stat.execute("create table test(id serial primary key, " +
...@@ -883,17 +838,13 @@ public class TestSpatial extends TestBase { ...@@ -883,17 +838,13 @@ public class TestSpatial extends TestBase {
assertTrue(rs.next()); assertTrue(rs.next());
assertFalse(rs.getString(1).contains("/* PUBLIC.SPATIAL: _ROWID_ = " + assertFalse(rs.getString(1).contains("/* PUBLIC.SPATIAL: _ROWID_ = " +
"5 */")); "5 */"));
} finally {
// Close the database
conn.close();
} }
deleteDb("spatial"); deleteDb("spatial");
} }
private void testStoreCorruption() throws SQLException { private void testStoreCorruption() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("drop table if exists pt_cloud;\n" + stat.execute("drop table if exists pt_cloud;\n" +
"CREATE TABLE PT_CLOUD AS " + "CREATE TABLE PT_CLOUD AS " +
...@@ -912,17 +863,13 @@ public class TestSpatial extends TestBase { ...@@ -912,17 +863,13 @@ public class TestSpatial extends TestBase {
" system_range(1e6,1e6+50) A,system_range(6e6,6e6+50) B;\n" + " system_range(1e6,1e6+50) A,system_range(6e6,6e6+50) B;\n" +
"create spatial index pt_index on pt_cloud(the_geom);\n" + "create spatial index pt_index on pt_cloud(the_geom);\n" +
"shutdown compact;"); "shutdown compact;");
} finally {
// Close the database
conn.close();
} }
deleteDb("spatial"); deleteDb("spatial");
} }
private void testExplainSpatialIndexWithPk() throws SQLException { private void testExplainSpatialIndexWithPk() throws SQLException {
deleteDb("spatial"); deleteDb("spatial");
Connection conn = getConnection(URL); try (Connection conn = getConnection(URL)) {
try {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("drop table if exists pt_cloud;"); stat.execute("drop table if exists pt_cloud;");
stat.execute("CREATE TABLE PT_CLOUD(id serial, the_geom geometry) AS " + stat.execute("CREATE TABLE PT_CLOUD(id serial, the_geom geometry) AS " +
...@@ -939,9 +886,6 @@ public class TestSpatial extends TestBase { ...@@ -939,9 +886,6 @@ public class TestSpatial extends TestBase {
} finally { } finally {
rs.close(); rs.close();
} }
} finally {
// Close the database
conn.close();
} }
deleteDb("spatial"); deleteDb("spatial");
} }
...@@ -1189,11 +1133,8 @@ public class TestSpatial extends TestBase { ...@@ -1189,11 +1133,8 @@ public class TestSpatial extends TestBase {
"INSERT INTO PUBLIC.DUMMY_12 (\"fid\",Z_ID,GEOM) VALUES (178,-1,NULL);\n" + "INSERT INTO PUBLIC.DUMMY_12 (\"fid\",Z_ID,GEOM) VALUES (178,-1,NULL);\n" +
"INSERT INTO PUBLIC.DUMMY_12 (\"fid\",Z_ID,GEOM) VALUES (179," + "INSERT INTO PUBLIC.DUMMY_12 (\"fid\",Z_ID,GEOM) VALUES (179," +
"-1,NULL);"); "-1,NULL);");
ResultSet rs = stat.executeQuery("select * from DUMMY_12"); try (ResultSet rs = stat.executeQuery("select * from DUMMY_12")) {
try {
assertTrue(rs.next()); assertTrue(rs.next());
} finally {
rs.close();
} }
} }
......
...@@ -105,17 +105,11 @@ public class TestLimitUpdates extends TestBase { ...@@ -105,17 +105,11 @@ public class TestLimitUpdates extends TestBase {
private static void updateLimit(final Connection conn, final int value, private static void updateLimit(final Connection conn, final int value,
final int limit) throws SQLException { final int limit) throws SQLException {
PreparedStatement prep = null; try (PreparedStatement prep = conn.prepareStatement(
try { "UPDATE TEST SET VALUE_ID = ? LIMIT ?")) {
prep = conn.prepareStatement(
"UPDATE TEST SET VALUE_ID = ? LIMIT ?");
prep.setInt(1, value); prep.setInt(1, value);
prep.setInt(2, limit); prep.setInt(2, limit);
prep.execute(); prep.execute();
} finally {
if (prep != null) {
prep.close();
}
} }
} }
} }
...@@ -12,7 +12,6 @@ import java.io.IOException; ...@@ -12,7 +12,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.Date;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.sql.Connection; import java.sql.Connection;
import java.sql.Driver; import java.sql.Driver;
...@@ -23,11 +22,11 @@ import java.sql.SQLException; ...@@ -23,11 +22,11 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import org.h2.util.IOUtils; import org.h2.util.IOUtils;
import org.h2.util.New; import org.h2.util.New;
...@@ -133,12 +132,9 @@ public class TestRecover { ...@@ -133,12 +132,9 @@ public class TestRecover {
} }
ZipEntry entry = new ZipEntry(basePath + entryName); ZipEntry entry = new ZipEntry(basePath + entryName);
zipOut.putNextEntry(entry); zipOut.putNextEntry(entry);
InputStream in = null;
try { try (InputStream in = new FileInputStream(fileName)) {
in = new FileInputStream(fileName);
IOUtils.copyAndCloseInput(in, zipOut); IOUtils.copyAndCloseInput(in, zipOut);
} finally {
IOUtils.closeSilently(in);
} }
zipOut.closeEntry(); zipOut.closeEntry();
} }
......
...@@ -16,13 +16,11 @@ import java.sql.SQLException; ...@@ -16,13 +16,11 @@ import java.sql.SQLException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Random; import java.util.Random;
import org.h2.test.TestAll; import org.h2.test.TestAll;
import org.h2.test.TestBase; import org.h2.test.TestBase;
import org.h2.test.utils.SelfDestructor; import org.h2.test.utils.SelfDestructor;
import org.h2.tools.Backup; import org.h2.tools.Backup;
import org.h2.tools.DeleteDbFiles; import org.h2.tools.DeleteDbFiles;
import org.h2.util.IOUtils;
import org.h2.util.StringUtils; import org.h2.util.StringUtils;
/** /**
...@@ -188,11 +186,9 @@ public abstract class TestHalt extends TestBase { ...@@ -188,11 +186,9 @@ public abstract class TestHalt extends TestBase {
* @param e the exception or null * @param e the exception or null
*/ */
protected void traceOperation(String s, Exception e) { protected void traceOperation(String s, Exception e) {
FileWriter writer = null; File f = new File(getBaseDir() + "/" + TRACE_FILE_NAME);
try { f.getParentFile().mkdirs();
File f = new File(getBaseDir() + "/" + TRACE_FILE_NAME); try (FileWriter writer = new FileWriter(f, true)) {
f.getParentFile().mkdirs();
writer = new FileWriter(f, true);
PrintWriter w = new PrintWriter(writer); PrintWriter w = new PrintWriter(writer);
s = dateFormat.format(new Date()) + ": " + s; s = dateFormat.format(new Date()) + ": " + s;
w.println(s); w.println(s);
...@@ -201,8 +197,6 @@ public abstract class TestHalt extends TestBase { ...@@ -201,8 +197,6 @@ public abstract class TestHalt extends TestBase {
} }
} catch (IOException e2) { } catch (IOException e2) {
e2.printStackTrace(); e2.printStackTrace();
} finally {
IOUtils.closeSilently(writer);
} }
} }
......
...@@ -5,6 +5,10 @@ ...@@ -5,6 +5,10 @@
*/ */
package org.h2.test.unit; package org.h2.test.unit;
import java.sql.Connection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.h2.bnf.Bnf; import org.h2.bnf.Bnf;
import org.h2.bnf.context.DbContents; import org.h2.bnf.context.DbContents;
import org.h2.bnf.context.DbContextRule; import org.h2.bnf.context.DbContextRule;
...@@ -12,11 +16,6 @@ import org.h2.bnf.context.DbProcedure; ...@@ -12,11 +16,6 @@ import org.h2.bnf.context.DbProcedure;
import org.h2.bnf.context.DbSchema; import org.h2.bnf.context.DbSchema;
import org.h2.test.TestBase; import org.h2.test.TestBase;
import java.sql.Connection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/** /**
* Test Bnf Sql parser * Test Bnf Sql parser
* @author Nicolas Fortin * @author Nicolas Fortin
...@@ -35,18 +34,12 @@ public class TestBnf extends TestBase { ...@@ -35,18 +34,12 @@ public class TestBnf extends TestBase {
@Override @Override
public void test() throws Exception { public void test() throws Exception {
deleteDb("bnf"); deleteDb("bnf");
Connection conn = getConnection("bnf"); try (Connection conn = getConnection("bnf")) {
try {
testModes(conn); testModes(conn);
testProcedures(conn, false); testProcedures(conn, false);
} finally {
conn.close();
} }
conn = getConnection("bnf;mode=mysql"); try (Connection conn = getConnection("bnf;mode=mysql")) {
try {
testProcedures(conn, true); testProcedures(conn, true);
} finally {
conn.close();
} }
} }
......
...@@ -13,7 +13,6 @@ import java.sql.SQLException; ...@@ -13,7 +13,6 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.List; import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import org.h2.api.ErrorCode; import org.h2.api.ErrorCode;
import org.h2.jdbc.JdbcConnection; import org.h2.jdbc.JdbcConnection;
import org.h2.store.fs.FileUtils; import org.h2.store.fs.FileUtils;
...@@ -237,11 +236,8 @@ public class TestFileLockSerialized extends TestBase { ...@@ -237,11 +236,8 @@ public class TestFileLockSerialized extends TestBase {
SortedProperties p = SortedProperties.loadProperties(propFile); SortedProperties p = SortedProperties.loadProperties(propFile);
p.setProperty("changePending", "true"); p.setProperty("changePending", "true");
p.setProperty("modificationDataId", "1000"); p.setProperty("modificationDataId", "1000");
OutputStream out = FileUtils.newOutputStream(propFile, false); try (OutputStream out = FileUtils.newOutputStream(propFile, false)) {
try {
p.store(out, "test"); p.store(out, "test");
} finally {
out.close();
} }
Thread.sleep(100); Thread.sleep(100);
stat.execute("select * from test"); stat.execute("select * from test");
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论