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

use try-with-resources where feasible

上级 6a89e09b
......@@ -466,8 +466,7 @@ public class ScriptCommand extends ScriptBase {
switch (v.getType()) {
case Value.BLOB: {
byte[] bytes = new byte[lobBlockSize];
InputStream input = v.getInputStream();
try {
try (InputStream input = v.getInputStream()) {
for (int i = 0;; i++) {
StringBuilder buff = new StringBuilder(lobBlockSize * 2);
buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(" + id +
......@@ -480,15 +479,13 @@ public class ScriptCommand extends ScriptBase {
String sql = buff.toString();
add(sql, true);
}
} finally {
IOUtils.closeSilently(input);
}
break;
}
case Value.CLOB: {
char[] chars = new char[lobBlockSize];
Reader reader = v.getReader();
try {
try (Reader reader = v.getReader()) {
for (int i = 0;; i++) {
StringBuilder buff = new StringBuilder(lobBlockSize * 2);
buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(" + id + ", " + i + ", ");
......@@ -501,8 +498,6 @@ public class ScriptCommand extends ScriptBase {
String sql = buff.toString();
add(sql, true);
}
} finally {
IOUtils.closeSilently(reader);
}
break;
}
......
......@@ -46,8 +46,7 @@ public class ConditionInSelect extends Condition {
if (!query.hasOrder()) {
query.setDistinct(true);
}
LocalResult rows = query.query(0);
try {
try (LocalResult rows = query.query(0)) {
Value l = left.getValue(session);
if (rows.getRowCount() == 0) {
return ValueBoolean.get(all);
......@@ -73,8 +72,6 @@ public class ConditionInSelect extends Condition {
return ValueNull.INSTANCE;
}
return ValueBoolean.get(false);
} finally {
rows.close();
}
}
......
......@@ -1636,12 +1636,9 @@ public class Function extends Expression implements FunctionCall {
String fileName = v1.getString();
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
InputStream in = v0.getInputStream();
try {
try (InputStream in = v0.getInputStream()) {
result = ValueLong.get(IOUtils.copyAndClose(in,
fileOutputStream));
} finally {
in.close();
}
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
......
......@@ -33,8 +33,7 @@ public class Subquery extends Expression {
@Override
public Value getValue(Session session) {
query.setSession(session);
ResultInterface result = query.query(2);
try {
try (ResultInterface result = query.query(2)) {
int rowcount = result.getRowCount();
if (rowcount > 1) {
throw DbException.get(ErrorCode.SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW);
......@@ -52,8 +51,6 @@ public class Subquery extends Expression {
}
}
return v;
} finally {
result.close();
}
}
......
......@@ -16,13 +16,12 @@ import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.engine.Constants;
import org.h2.message.DbException;
import org.h2.message.TraceObject;
import org.h2.util.Task;
import org.h2.util.IOUtils;
import org.h2.util.Task;
import org.h2.value.Value;
/**
......@@ -89,12 +88,9 @@ public class JdbcBlob extends TraceObject implements Blob {
}
checkClosed();
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = value.getInputStream();
try {
try (InputStream in = value.getInputStream()) {
IOUtils.skipFully(in, pos - 1);
IOUtils.copy(in, out, length);
} finally {
in.close();
}
return out.toByteArray();
} catch (Exception e) {
......
......@@ -17,7 +17,6 @@ import java.io.Writer;
import java.sql.Clob;
import java.sql.NClob;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.engine.Constants;
import org.h2.message.DbException;
......@@ -189,12 +188,9 @@ public class JdbcClob extends TraceObject implements NClob
}
StringWriter writer = new StringWriter(
Math.min(Constants.IO_BUFFER_SIZE, length));
Reader reader = value.getReader();
try {
try (Reader reader = value.getReader()) {
IOUtils.skipFully(reader, pos - 1);
IOUtils.copyAndCloseInput(reader, writer, length);
} finally {
reader.close();
}
return writer.toString();
} catch (Exception e) {
......
......@@ -17,14 +17,11 @@ import javax.sql.XAConnection;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.h2.api.ErrorCode;
import org.h2.jdbc.JdbcConnection;
import org.h2.util.JdbcUtils;
import org.h2.util.New;
import org.h2.message.DbException;
import org.h2.message.TraceObject;
import org.h2.util.New;
/**
......@@ -193,9 +190,7 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
public Xid[] recover(int flag) throws XAException {
debugCodeCall("recover", quoteFlags(flag));
checkOpen();
Statement stat = null;
try {
stat = physicalConn.createStatement();
try (Statement stat = physicalConn.createStatement()) {
ResultSet rs = stat.executeQuery("SELECT * FROM " +
"INFORMATION_SCHEMA.IN_DOUBT ORDER BY TRANSACTION");
ArrayList<Xid> list = New.arrayList();
......@@ -216,8 +211,6 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
XAException xa = new XAException(XAException.XAER_RMERR);
xa.initCause(e);
throw xa;
} finally {
JdbcUtils.closeSilently(stat);
}
}
......@@ -236,15 +229,12 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
if (!currentTransaction.equals(xid)) {
throw new XAException(XAException.XAER_INVAL);
}
Statement stat = null;
try {
stat = physicalConn.createStatement();
try (Statement stat = physicalConn.createStatement()) {
stat.execute("PREPARE COMMIT " + JdbcXid.toString(xid));
prepared = true;
} catch (SQLException e) {
throw convertException(e);
} finally {
JdbcUtils.closeSilently(stat);
}
return XA_OK;
}
......@@ -275,12 +265,8 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
}
try {
if (prepared) {
Statement stat = null;
try {
stat = physicalConn.createStatement();
try (Statement stat = physicalConn.createStatement()) {
stat.execute("ROLLBACK TRANSACTION " + JdbcXid.toString(xid));
} finally {
JdbcUtils.closeSilently(stat);
}
prepared = false;
} else {
......@@ -355,20 +341,19 @@ public class JdbcXAConnection extends TraceObject implements XAConnection,
if (isDebugEnabled()) {
debugCode("commit("+JdbcXid.toString(xid)+", "+onePhase+");");
}
Statement stat = null;
try {
if (onePhase) {
physicalConn.commit();
} else {
stat = physicalConn.createStatement();
try (Statement stat = physicalConn.createStatement()) {
stat.execute("COMMIT TRANSACTION " + JdbcXid.toString(xid));
prepared = false;
}
}
physicalConn.setAutoCommit(true);
} catch (SQLException e) {
throw convertException(e);
} finally {
JdbcUtils.closeSilently(stat);
}
currentTransaction = null;
}
......
......@@ -24,7 +24,7 @@ import org.h2.value.ValueArray;
* 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.
*/
public class LocalResult implements ResultInterface, ResultTarget {
public class LocalResult implements ResultInterface, ResultTarget, AutoCloseable {
private int maxMemoryRows;
private Session session;
......
......@@ -11,7 +11,7 @@ import org.h2.value.Value;
* The result interface is used by the LocalResult and ResultRemote class.
* 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
......
......@@ -92,9 +92,8 @@ public class TcpServer implements Service {
Connection conn = Driver.load().connect("jdbc:h2:" +
getManagementDbName(port), prop);
managementDb = conn;
Statement stat = null;
try {
stat = conn.createStatement();
try (Statement stat = conn.createStatement()) {
stat.execute("CREATE ALIAS IF NOT EXISTS STOP_SERVER FOR \"" +
TcpServer.class.getName() + ".stopServer\"");
stat.execute("CREATE TABLE IF NOT EXISTS SESSIONS" +
......@@ -104,8 +103,6 @@ public class TcpServer implements Service {
"INSERT INTO SESSIONS VALUES(?, ?, ?, NOW())");
managementDbRemove = conn.prepareStatement(
"DELETE FROM SESSIONS WHERE ID=?");
} finally {
JdbcUtils.closeSilently(stat);
}
SERVERS.put(port, this);
}
......
......@@ -28,7 +28,6 @@ import java.sql.Types;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import org.h2.command.CommandInterface;
import org.h2.engine.ConnectionInfo;
import org.h2.engine.SysProperties;
......@@ -37,7 +36,6 @@ import org.h2.jdbc.JdbcPreparedStatement;
import org.h2.jdbc.JdbcStatement;
import org.h2.message.DbException;
import org.h2.mvstore.DataUtils;
import org.h2.util.IOUtils;
import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils;
import org.h2.util.ScriptReader;
......@@ -827,10 +825,8 @@ public class PgServerThread implements Runnable {
}
private static void installPgCatalog(Statement stat) throws SQLException {
Reader r = null;
try {
r = new InputStreamReader(new ByteArrayInputStream(Utils
.getResource("/org/h2/server/pg/pg_catalog.sql")));
try (Reader r = new InputStreamReader(new ByteArrayInputStream(Utils
.getResource("/org/h2/server/pg/pg_catalog.sql")))) {
ScriptReader reader = new ScriptReader(r);
while (true) {
String sql = reader.readStatement();
......@@ -842,8 +838,6 @@ public class PgServerThread implements Runnable {
reader.close();
} catch (IOException e) {
throw DbException.convertIOException(e, "Can not read pg_catalog resource");
} finally {
IOUtils.closeSilently(r);
}
}
......
......@@ -32,7 +32,6 @@ import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import org.h2.api.ErrorCode;
import org.h2.bnf.Bnf;
import org.h2.bnf.context.DbColumn;
......@@ -660,10 +659,9 @@ public class WebApp {
treeIndex = addColumns(mainSchema, view, buff,
treeIndex, notManyTables, columnsBuffer);
if (schema.getContents().isH2()) {
PreparedStatement prep = null;
try {
prep = conn.prepareStatement("SELECT * FROM " +
"INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=?");
try (PreparedStatement prep = conn.prepareStatement("SELECT * FROM " +
"INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=?")) {
prep.setString(1, view.getName());
ResultSet rs = prep.executeQuery();
if (rs.next()) {
......@@ -675,8 +673,6 @@ public class WebApp {
treeIndex++;
}
rs.close();
} finally {
JdbcUtils.closeSilently(prep);
}
}
buff.append("addTable('" +
......@@ -717,9 +713,7 @@ public class WebApp {
treeIndex = addTablesAndViews(schema, false, buff, treeIndex);
}
if (isH2) {
Statement stat = null;
try {
stat = conn.createStatement();
try (Statement stat = conn.createStatement()) {
ResultSet rs = stat.executeQuery("SELECT * FROM " +
"INFORMATION_SCHEMA.SEQUENCES ORDER BY SEQUENCE_NAME");
for (int i = 0; rs.next(); i++) {
......@@ -773,8 +767,6 @@ public class WebApp {
}
}
rs.close();
} finally {
JdbcUtils.closeSilently(stat);
}
}
DatabaseMetaData meta = session.getMetaData();
......
......@@ -5,12 +5,10 @@
*/
package org.h2.store;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.h2.api.ErrorCode;
import org.h2.engine.Constants;
import org.h2.message.DbException;
......@@ -51,23 +49,13 @@ public class FileLister {
message).getSQLException();
}
} else if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) {
FileChannel f = null;
try {
f = FilePath.get(fileName).open("r");
try (FileChannel f = FilePath.get(fileName).open("r")) {
java.nio.channels.FileLock lock = f.tryLock(0, Long.MAX_VALUE, true);
lock.release();
} catch (Exception e) {
throw DbException.get(
ErrorCode.CANNOT_CHANGE_SETTING_WHEN_OPEN_1, e,
message).getSQLException();
} finally {
if (f != null) {
try {
f.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
......
......@@ -210,11 +210,8 @@ public class FileLock implements Runnable {
*/
public Properties save() {
try {
OutputStream out = FileUtils.newOutputStream(fileName, false);
try {
try (OutputStream out = FileUtils.newOutputStream(fileName, false)) {
properties.store(out, MAGIC);
} finally {
out.close();
}
lastWrite = FileUtils.lastModified(fileName);
if (trace.isDebugEnabled()) {
......
......@@ -55,11 +55,8 @@ public class FilePathZip extends FilePath {
if (entryName.length() == 0) {
return true;
}
ZipFile file = openZipFile();
try {
try (ZipFile file = openZipFile()) {
return file.getEntry(entryName) != null;
} finally {
file.close();
}
} catch (IOException e) {
return false;
......@@ -95,8 +92,7 @@ public class FilePathZip extends FilePath {
if (entryName.length() == 0) {
return true;
}
ZipFile file = openZipFile();
try {
try (ZipFile file = openZipFile()) {
Enumeration<? extends ZipEntry> en = file.entries();
while (en.hasMoreElements()) {
ZipEntry entry = en.nextElement();
......@@ -111,8 +107,6 @@ public class FilePathZip extends FilePath {
}
}
}
} finally {
file.close();
}
return false;
} catch (IOException e) {
......@@ -133,12 +127,9 @@ public class FilePathZip extends FilePath {
@Override
public long size() {
try {
ZipFile file = openZipFile();
try {
try (ZipFile file = openZipFile()) {
ZipEntry entry = file.getEntry(getEntryName());
return entry == null ? 0 : entry.getSize();
} finally {
file.close();
}
} catch (IOException e) {
return 0;
......@@ -156,8 +147,7 @@ public class FilePathZip extends FilePath {
if (!path.endsWith("/")) {
path += "/";
}
ZipFile file = openZipFile();
try {
try (ZipFile file = openZipFile()) {
String dirName = getEntryName();
String prefix = path.substring(0, path.length() - dirName.length());
Enumeration<? extends ZipEntry> en = file.entries();
......@@ -175,8 +165,6 @@ public class FilePathZip extends FilePath {
list.add(getPath(prefix + name));
}
}
} finally {
file.close();
}
return list;
} catch (IOException e) {
......
......@@ -15,7 +15,6 @@ import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.h2.api.ErrorCode;
import org.h2.command.Prepared;
import org.h2.engine.Session;
......@@ -28,7 +27,6 @@ import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.RowList;
import org.h2.schema.Schema;
import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
......@@ -169,9 +167,8 @@ public class TableLink extends Table {
qualifiedTableName = originalTable;
}
// check if the table is accessible
Statement stat = null;
try {
stat = conn.getConnection().createStatement();
try (Statement stat = conn.getConnection().createStatement()) {
rs = stat.executeQuery("SELECT * FROM " +
qualifiedTableName + " T WHERE 1=0");
if (columnList.size() == 0) {
......@@ -197,8 +194,6 @@ public class TableLink extends Table {
} catch (Exception e) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, e,
originalTable + "(" + e.toString() + ")");
} finally {
JdbcUtils.closeSilently(stat);
}
Column[] cols = new Column[columnList.size()];
columnList.toArray(cols);
......
......@@ -11,7 +11,6 @@ import java.io.OutputStream;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
......@@ -74,9 +73,8 @@ public class Restore extends Tool {
private static String getOriginalDbName(String fileName, String db)
throws IOException {
InputStream in = null;
try {
in = FileUtils.newInputStream(fileName);
try (InputStream in = FileUtils.newInputStream(fileName)) {
ZipInputStream zipIn = new ZipInputStream(in);
String originalDbName = null;
boolean multiple = false;
......@@ -108,8 +106,6 @@ public class Restore extends Tool {
throw new IOException("Multiple databases found, but not " + db);
}
return originalDbName;
} finally {
IOUtils.closeSilently(in);
}
}
......
......@@ -9,7 +9,6 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.util.JdbcUtils;
import org.h2.util.StringUtils;
import org.h2.util.Tool;
......@@ -134,13 +133,10 @@ public class Script extends Tool {
*/
public static void process(Connection conn,
String fileName, String options1, String options2) throws SQLException {
Statement stat = null;
try {
stat = conn.createStatement();
try (Statement stat = conn.createStatement()) {
String sql = "SCRIPT " + options1 + " TO '" + fileName + "' " + options2;
stat.execute(sql);
} finally {
JdbcUtils.closeSilently(stat);
}
}
......
......@@ -17,10 +17,10 @@ import java.io.PrintWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
import java.util.Vector;
import java.util.Map.Entry;
import org.h2.store.fs.FileUtils;
/**
......@@ -88,14 +88,8 @@ public class SortedProperties extends Properties {
throws IOException {
SortedProperties prop = new SortedProperties();
if (FileUtils.exists(fileName)) {
InputStream in = null;
try {
in = FileUtils.newInputStream(fileName);
try (InputStream in = FileUtils.newInputStream(fileName)) {
prop.load(in);
} finally {
if (in != null) {
in.close();
}
}
}
return prop;
......
......@@ -282,7 +282,7 @@ public class SourceCompiler {
.getStandardFileManager(null, null, null));
ArrayList<JavaFileObject> compilationUnits = new ArrayList<JavaFileObject>();
compilationUnits.add(new StringJavaFileObject(fullClassName, source));
// can not concurrently compile
// cannot concurrently compile
synchronized (JAVA_COMPILER) {
JAVA_COMPILER.getTask(writer, fileManager, null, null,
null, compilationUnits).call();
......
......@@ -478,8 +478,8 @@ public class Utils {
}
return IOUtils.readBytesAndClose(in, 0);
}
ZipInputStream zipIn = new ZipInputStream(in);
try {
try (ZipInputStream zipIn = new ZipInputStream(in)) {
while (true) {
ZipEntry entry = zipIn.getNextEntry();
if (entry == null) {
......@@ -500,8 +500,6 @@ public class Utils {
} catch (IOException e) {
// if this happens we have a real problem
e.printStackTrace();
} finally {
zipIn.close();
}
return null;
}
......
......@@ -13,7 +13,6 @@ import java.io.InputStream;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
......@@ -222,9 +221,8 @@ public class ValueLob extends Value {
private void createFromReader(char[] buff, int len, Reader in,
long remaining, DataHandler h) throws IOException {
FileStoreOutputStream out = initLarge(h);
try (FileStoreOutputStream out = initLarge(h)) {
boolean compress = h.getLobCompressionAlgorithm(Value.CLOB) != null;
try {
while (true) {
precision += len;
byte[] b = new String(buff, 0, len).getBytes(Constants.UTF8);
......@@ -239,8 +237,6 @@ public class ValueLob extends Value {
break;
}
}
} finally {
out.close();
}
}
......@@ -421,9 +417,8 @@ public class ValueLob extends Value {
private void createFromStream(byte[] buff, int len, InputStream in,
long remaining, DataHandler h) throws IOException {
FileStoreOutputStream out = initLarge(h);
try (FileStoreOutputStream out = initLarge(h)) {
boolean compress = h.getLobCompressionAlgorithm(Value.BLOB) != null;
try {
while (true) {
precision += len;
out.write(buff, 0, len);
......@@ -437,8 +432,6 @@ public class ValueLob extends Value {
break;
}
}
} finally {
out.close();
}
}
......
......@@ -13,7 +13,6 @@ import java.io.InputStream;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
......@@ -93,9 +92,9 @@ public class ValueLobDb extends Value implements Value.ValueClob,
this.fileName = createTempLobFileName(handler);
this.tempFile = this.handler.openFile(fileName, "rw", false);
this.tempFile.autoDelete();
FileStoreOutputStream out = new FileStoreOutputStream(tempFile, null, null);
long tmpPrecision = 0;
try {
try (FileStoreOutputStream out = new FileStoreOutputStream(tempFile, null, null)) {
char[] buff = new char[Constants.IO_BUFFER_SIZE];
while (true) {
int len = getBufferSize(this.handler, false, remaining);
......@@ -107,8 +106,6 @@ public class ValueLobDb extends Value implements Value.ValueClob,
out.write(data);
tmpPrecision += len;
}
} finally {
out.close();
}
this.precision = tmpPrecision;
}
......
......@@ -80,13 +80,10 @@ public class FileFunctions {
* @return the byte array
*/
public static byte[] readFile(String fileName) throws IOException {
RandomAccessFile file = new RandomAccessFile(fileName, "r");
try {
try (RandomAccessFile file = new RandomAccessFile(fileName, "r")) {
byte[] buff = new byte[(int) file.length()];
file.readFully(buff);
return buff;
} finally {
file.close();
}
}
}
......@@ -21,7 +21,6 @@ import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicInteger;
import org.h2.test.TestBase;
import org.h2.tools.Server;
import org.h2.util.JdbcUtils;
import org.h2.util.StringUtils;
/**
......@@ -186,26 +185,18 @@ class Database {
Connection newConn = DriverManager.getConnection(url, user, password);
if (url.startsWith("jdbc:derby:")) {
// Derby: use higher cache size
Statement s = null;
try {
s = newConn.createStatement();
try (Statement s = newConn.createStatement()) {
// stat.execute("CALL
// SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(
// 'derby.storage.pageCacheSize', '64')");
// stat.execute("CALL
// SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(
// 'derby.storage.pageSize', '8192')");
} finally {
JdbcUtils.closeSilently(s);
}
} else if (url.startsWith("jdbc:hsqldb:")) {
// HSQLDB: use a WRITE_DELAY of 1 second
Statement s = null;
try {
s = newConn.createStatement();
try (Statement s = newConn.createStatement()){
s.execute("SET WRITE_DELAY 1");
} finally {
JdbcUtils.closeSilently(s);
}
}
return newConn;
......
......@@ -29,9 +29,7 @@ public class Profile extends Thread {
private BufferedWriter trace;
private Profile() {
LineNumberReader r = null;
try {
r = new LineNumberReader(new FileReader("profile.txt"));
try (LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"))) {
while (r.readLine() != null) {
// nothing - just count lines
}
......@@ -43,8 +41,6 @@ public class Profile extends Thread {
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
IOUtils.closeSilently(r);
}
}
......@@ -195,9 +191,8 @@ public class Profile extends Thread {
list[bigIndex] = -(big + 1);
index[i] = bigIndex;
}
LineNumberReader r = null;
try {
r = new LineNumberReader(new FileReader("profile.txt"));
try (LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"))) {
for (int i = 0; i < maxIndex; i++) {
String line = r.readLine();
int k = list[i];
......@@ -215,8 +210,6 @@ public class Profile extends Thread {
for (int i = 0; i < max; i++) {
print(text[i]);
}
} finally {
IOUtils.closeSilently(r);
}
}
......
......@@ -14,7 +14,6 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import org.h2.api.ErrorCode;
import org.h2.store.fs.FileUtils;
import org.h2.test.TestBase;
......@@ -714,12 +713,9 @@ public class TestLinkedTable extends TestBase {
String sql = "CREATE LINKED TABLE T(NULL, " +
"'jdbc:h2:mem:one', 'sa', 'sa', 'TEST') READONLY";
sb.execute(sql);
ResultSet rs = sb.executeQuery("SELECT * FROM T");
try {
try (ResultSet rs = sb.executeQuery("SELECT * FROM T")) {
assertTrue(rs.next());
assertEquals("POINT (1 1)", rs.getString("THE_GEOM"));
} finally {
rs.close();
}
sb.execute("DROP TABLE T");
ca.close();
......
......@@ -10,10 +10,8 @@ import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.api.DatabaseEventListener;
import org.h2.test.TestBase;
import org.h2.util.JdbcUtils;
/**
* Tests the DatabaseEventListener.
......@@ -112,15 +110,12 @@ public class TestListener extends TestBase implements DatabaseEventListener {
if (databaseUrl.toUpperCase().contains("CIPHER")) {
return;
}
Connection conn = null;
try {
conn = DriverManager.getConnection(databaseUrl, getUser(), getPassword());
try (Connection conn = DriverManager.getConnection(databaseUrl, getUser(), getPassword())) {
conn.createStatement().execute("DROP TABLE TEST2");
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.closeSilently(conn);
}
}
......@@ -134,15 +129,12 @@ public class TestListener extends TestBase implements DatabaseEventListener {
if (databaseUrl.toUpperCase().contains("CIPHER")) {
return;
}
Connection conn = null;
try {
conn = DriverManager.getConnection(databaseUrl, getUser(), getPassword());
try (Connection conn = DriverManager.getConnection(databaseUrl, getUser(), getPassword())) {
conn.createStatement().execute("CREATE TABLE IF NOT EXISTS TEST2(ID INT)");
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.closeSilently(conn);
}
}
......
......@@ -81,16 +81,13 @@ public class TestMultiThread extends TestBase implements Runnable {
Task t = new Task() {
@Override
public void call() throws Exception {
Connection c2 = getConnection(url);
try (Connection c2 = getConnection(url)) {
Statement stat = c2.createStatement();
try {
for (int i = 0; !stop; i++) {
stat.execute("create table test" + x + "_" + i);
c2.getMetaData().getTables(null, null, null, null);
stat.execute("drop table test" + x + "_" + i);
}
} finally {
c2.close();
}
}
};
......@@ -116,17 +113,14 @@ public class TestMultiThread extends TestBase implements Runnable {
Task t = new Task() {
@Override
public void call() throws Exception {
Connection c2 = getConnection(url);
try (Connection c2 = getConnection(url)) {
PreparedStatement p2 = c2
.prepareStatement("insert into test(data) values(?)");
try {
while (!stop) {
p2.setCharacterStream(1, new StringReader(new String(
new char[10 * 1024])));
p2.execute();
}
} finally {
c2.close();
}
}
};
......
......@@ -13,7 +13,6 @@ import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.h2.api.Trigger;
import org.h2.test.TestBase;
import org.h2.util.Task;
......@@ -64,8 +63,7 @@ public class TestSequence extends TestBase {
tasks[i] = new Task() {
@Override
public void call() throws Exception {
Connection conn = getConnection(url);
try {
try (Connection conn = getConnection(url)) {
PreparedStatement prep = conn.prepareStatement(
"insert into test(id) values(next value for test_seq)");
PreparedStatement prep2 = conn.prepareStatement(
......@@ -79,8 +77,6 @@ public class TestSequence extends TestBase {
createDropTrigger(conn);
}
}
} finally {
conn.close();
}
}
......
......@@ -105,17 +105,11 @@ public class TestLimitUpdates extends TestBase {
private static void updateLimit(final Connection conn, final int value,
final int limit) throws SQLException {
PreparedStatement prep = null;
try {
prep = conn.prepareStatement(
"UPDATE TEST SET VALUE_ID = ? LIMIT ?");
try (PreparedStatement prep = conn.prepareStatement(
"UPDATE TEST SET VALUE_ID = ? LIMIT ?")) {
prep.setInt(1, value);
prep.setInt(2, limit);
prep.execute();
} finally {
if (prep != null) {
prep.close();
}
}
}
}
......@@ -12,7 +12,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.Driver;
......@@ -23,11 +22,11 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.h2.util.IOUtils;
import org.h2.util.New;
......@@ -133,12 +132,9 @@ public class TestRecover {
}
ZipEntry entry = new ZipEntry(basePath + entryName);
zipOut.putNextEntry(entry);
InputStream in = null;
try {
in = new FileInputStream(fileName);
try (InputStream in = new FileInputStream(fileName)) {
IOUtils.copyAndCloseInput(in, zipOut);
} finally {
IOUtils.closeSilently(in);
}
zipOut.closeEntry();
}
......
......@@ -16,13 +16,11 @@ import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import org.h2.test.TestAll;
import org.h2.test.TestBase;
import org.h2.test.utils.SelfDestructor;
import org.h2.tools.Backup;
import org.h2.tools.DeleteDbFiles;
import org.h2.util.IOUtils;
import org.h2.util.StringUtils;
/**
......@@ -188,11 +186,9 @@ public abstract class TestHalt extends TestBase {
* @param e the exception or null
*/
protected void traceOperation(String s, Exception e) {
FileWriter writer = null;
try {
File f = new File(getBaseDir() + "/" + TRACE_FILE_NAME);
f.getParentFile().mkdirs();
writer = new FileWriter(f, true);
try (FileWriter writer = new FileWriter(f, true)) {
PrintWriter w = new PrintWriter(writer);
s = dateFormat.format(new Date()) + ": " + s;
w.println(s);
......@@ -201,8 +197,6 @@ public abstract class TestHalt extends TestBase {
}
} catch (IOException e2) {
e2.printStackTrace();
} finally {
IOUtils.closeSilently(writer);
}
}
......
......@@ -5,6 +5,10 @@
*/
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.context.DbContents;
import org.h2.bnf.context.DbContextRule;
......@@ -12,11 +16,6 @@ import org.h2.bnf.context.DbProcedure;
import org.h2.bnf.context.DbSchema;
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
* @author Nicolas Fortin
......@@ -35,18 +34,12 @@ public class TestBnf extends TestBase {
@Override
public void test() throws Exception {
deleteDb("bnf");
Connection conn = getConnection("bnf");
try {
try (Connection conn = getConnection("bnf")) {
testModes(conn);
testProcedures(conn, false);
} finally {
conn.close();
}
conn = getConnection("bnf;mode=mysql");
try {
try (Connection conn = getConnection("bnf;mode=mysql")) {
testProcedures(conn, true);
} finally {
conn.close();
}
}
......
......@@ -13,7 +13,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.h2.api.ErrorCode;
import org.h2.jdbc.JdbcConnection;
import org.h2.store.fs.FileUtils;
......@@ -237,11 +236,8 @@ public class TestFileLockSerialized extends TestBase {
SortedProperties p = SortedProperties.loadProperties(propFile);
p.setProperty("changePending", "true");
p.setProperty("modificationDataId", "1000");
OutputStream out = FileUtils.newOutputStream(propFile, false);
try {
try (OutputStream out = FileUtils.newOutputStream(propFile, false)) {
p.store(out, "test");
} finally {
out.close();
}
Thread.sleep(100);
stat.execute("select * from test");
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论