Mercurial > hg > monetdb-java
changeset 295:003ae6d881db
Add "final" keyword to method arguments and local variables where possible.
It discovered some bugs in the MonetStatement constructor (changed the argument instead of object variable) which are fixed now.
See also https://en.wikipedia.org/wiki/Final_(Java)
author | Martin van Dinther <martin.van.dinther@monetdbsolutions.com> |
---|---|
date | Thu, 01 Aug 2019 20:18:43 +0200 (2019-08-01) |
parents | 894abb249de1 |
children | c5efd6e661e5 |
files | src/main/java/nl/cwi/monetdb/jdbc/MonetBlob.java src/main/java/nl/cwi/monetdb/jdbc/MonetCallableStatement.java src/main/java/nl/cwi/monetdb/jdbc/MonetClob.java src/main/java/nl/cwi/monetdb/jdbc/MonetConnection.java src/main/java/nl/cwi/monetdb/jdbc/MonetDataSource.java src/main/java/nl/cwi/monetdb/jdbc/MonetDatabaseMetaData.java src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java.in src/main/java/nl/cwi/monetdb/jdbc/MonetPreparedStatement.java src/main/java/nl/cwi/monetdb/jdbc/MonetSavepoint.java src/main/java/nl/cwi/monetdb/jdbc/MonetStatement.java src/main/java/nl/cwi/monetdb/jdbc/MonetWrapper.java |
diffstat | 11 files changed, 598 insertions(+), 636 deletions(-) [+] |
line wrap: on
line diff
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetBlob.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetBlob.java @@ -30,14 +30,14 @@ import java.sql.SQLFeatureNotSupportedEx public final class MonetBlob implements Blob { private byte[] buf; - protected MonetBlob(byte[] data) { + protected MonetBlob(final byte[] data) { buf = data; } - - static MonetBlob create(String in) { + + final static MonetBlob create(final String in) { // unpack the HEX (BLOB) notation to real bytes - int len = in.length() / 2; - byte[] buf = new byte[len]; + final int len = in.length() / 2; + final byte[] buf = new byte[len]; int offset; for (int i = 0; i < len; i++) { offset = 2 * i; @@ -53,7 +53,7 @@ public final class MonetBlob implements } //== begin interface Blob - + /** * This method frees the Blob object and releases the resources that * it holds. The object is invalid once the free method is called. @@ -63,17 +63,15 @@ public final class MonetBlob implements * called multiple times, the subsequent calls to free are treated * as a no-op. * - * @throws SQLException if an error occurs releasing the Blob's - * resources + * @throws SQLException if an error occurs releasing the Blob's resources */ @Override public void free() throws SQLException { buf = null; } - + /** - * Retrieves the BLOB value designated by this Blob instance as a - * stream. + * Retrieves the BLOB value designated by this Blob instance as a stream. * * @return a stream containing the BLOB data * @throws SQLException if there is an error accessing the BLOB value @@ -91,16 +89,14 @@ public final class MonetBlob implements * * @param pos the offset to the first byte of the partial value to * be retrieved. The first byte in the Blob is at position 1 - * @param length the length in bytes of the partial value to be - * retrieved - * @return InputStream through which the partial Blob value can be - * read. + * @param length the length in bytes of the partial value to be retrieved + * @return InputStream through which the partial Blob value can be read. * @throws SQLException if pos is less than 1 or if pos is * greater than the number of bytes in the Blob or if pos + * length is greater than the number of bytes in the Blob */ @Override - public InputStream getBinaryStream(long pos, long length) + public InputStream getBinaryStream(final long pos, final long length) throws SQLException { checkBufIsNotNull(); @@ -116,7 +112,7 @@ public final class MonetBlob implements /** * Retrieves all or part of the BLOB value that this Blob object - * represents, as an array of bytes. This byte array contains up to + * represents, as an array of bytes. This byte array contains up to * length consecutive bytes starting at position pos. * * @param pos the ordinal position of the first byte in the BLOB @@ -125,11 +121,10 @@ public final class MonetBlob implements * @return a byte array containing up to length consecutive bytes * from the BLOB value designated by this Blob object, * starting with the byte at position pos. - * @throws SQLException if there is an error accessing the - * BLOB value + * @throws SQLException if there is an error accessing the BLOB value */ @Override - public byte[] getBytes(long pos, int length) throws SQLException { + public byte[] getBytes(final long pos, final int length) throws SQLException { checkBufIsNotNull(); if (pos < 1 || pos > buf.length) { throw new SQLException("Invalid pos value: " + pos, "M1M05"); @@ -161,39 +156,37 @@ public final class MonetBlob implements /** * Retrieves the byte position in the BLOB value designated by this - * Blob object at which pattern begins. The search begins at - * position start. + * Blob object at which pattern begins. The search begins at position start. * * @param pattern the Blob object designating the BLOB value for * which to search * @param start the position in the BLOB value at which to begin * searching; the first position is 1 * @return the position at which the pattern begins, else -1 - * @throws SQLException if there is an error accessing the - * BLOB value + * @throws SQLException if there is an error accessing the BLOB value */ @Override - public long position(Blob pattern, long start) throws SQLException { + public long position(final Blob pattern, final long start) throws SQLException { if (pattern == null) { throw new SQLException("Missing pattern object", "M1M05"); } + // buf and input argument start will be checked in method position(byte{}, long) return position(pattern.getBytes(1L, (int)pattern.length()), start); } /** * Retrieves the byte position at which the specified byte array * pattern begins within the BLOB value that this Blob object - * represents. The search for pattern begins at position start. + * represents. The search for pattern begins at position start. * * @param pattern the byte array for which to search * @param start the position at which to begin searching; * the first position is 1 * @return the position at which the pattern appears, else -1 - * @throws SQLException if there is an error accessing the - * BLOB value + * @throws SQLException if there is an error accessing the BLOB value */ @Override - public long position(byte[] pattern, long start) throws SQLException { + public long position(final byte[] pattern, final long start) throws SQLException { checkBufIsNotNull(); if (pattern == null) { throw new SQLException("Missing pattern object", "M1M05"); @@ -230,15 +223,14 @@ public final class MonetBlob implements * * @param pos the position in the BLOB value at which to start * writing; the first position is 1 - * @return a java.io.OutputStream object to which data can be - * written + * @return a java.io.OutputStream object to which data can be written * @throws SQLException if there is an error accessing the BLOB * value or if pos is less than 1 * @throws SQLFeatureNotSupportedException if the JDBC driver does * not support this method */ @Override - public OutputStream setBinaryStream(long pos) throws SQLException { + public OutputStream setBinaryStream(final long pos) throws SQLException { throw MonetWrapper.newSQLFeatureNotSupportedException("setBinaryStream"); } @@ -247,42 +239,40 @@ public final class MonetBlob implements * object represents, starting at position pos, and returns the * number of bytes written. * - * @param pos the position in the BLOB object at which to start - * writing - * @param bytes the array of bytes to be written to the BLOB value + * @param pos the position in the BLOB object at which to start writing + * @param bytes the array of bytes to be written to the BLOB value * that this Blob object represents * @return the number of bytes written * @throws SQLException if there is an error accessing the * BLOB value or if pos is less than 1 */ @Override - public int setBytes(long pos, byte[] bytes) throws SQLException { + public int setBytes(final long pos, final byte[] bytes) throws SQLException { if (bytes == null) { throw new SQLException("Missing bytes[] object", "M1M05"); } + // buf and input argument pos will be checked in method setBytes(long, byte{}, int, int) return setBytes(pos, bytes, 1, bytes.length); } /** * Writes all or part of the given byte array to the BLOB value that - * this Blob object represents and returns the number of bytes - * written. Writing starts at position pos in the BLOB value; len - * bytes from the given byte array are written. + * this Blob object represents and returns the number of bytes written. + * Writing starts at position pos in the BLOB value; len bytes from + * the given byte array are written. * - * @param pos the position in the BLOB object at which to start - * writing - * @param bytes the array of bytes to be written to this BLOB - * object + * @param pos the position in the BLOB object at which to start writing + * @param bytes the array of bytes to be written to this BLOB object * @param offset the offset into the array bytes at which to start * reading the bytes to be set - * @param len the number of bytes to be written to the BLOB value + * @param len the number of bytes to be written to the BLOB value * from the array of bytes bytes * @return the number of bytes written * @throws SQLException if there is an error accessing the * BLOB value or if pos is less than 1 */ @Override - public int setBytes(long pos, byte[] bytes, int offset, int len) + public int setBytes(final long pos, final byte[] bytes, final int offset, final int len) throws SQLException { checkBufIsNotNull(); @@ -310,22 +300,21 @@ public final class MonetBlob implements } /** - * Truncates the BLOB value that this Blob object represents to be + * Truncates the BLOB value that this Blob object represents to be * len bytes in length. * * @param len the length, in bytes, to which the BLOB value * should be truncated - * @throws SQLException if there is an error accessing the - * BLOB value + * @throws SQLException if there is an error accessing the BLOB value */ @Override - public void truncate(long len) throws SQLException { + public void truncate(final long len) throws SQLException { checkBufIsNotNull(); if (len < 0 || len > buf.length) { throw new SQLException("Invalid len value: " + len, "M1M05"); } if (buf.length > len) { - byte[] newbuf = new byte[(int)len]; + final byte[] newbuf = new byte[(int)len]; for (int i = 0; i < len; i++) newbuf[i] = buf[i]; buf = newbuf;
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetCallableStatement.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetCallableStatement.java @@ -87,11 +87,11 @@ public class MonetCallableStatement * @throws IllegalArgumentException is one of the arguments is null or empty */ MonetCallableStatement( - MonetConnection connection, - int resultSetType, - int resultSetConcurrency, - int resultSetHoldability, - String callQuery) + final MonetConnection connection, + final int resultSetType, + final int resultSetConcurrency, + final int resultSetHoldability, + final String callQuery) throws SQLException, IllegalArgumentException { super( @@ -107,17 +107,17 @@ public class MonetCallableStatement * { [?=] call <procedure-name> [(<arg1>,<arg2>, ...)] } * and remove the JDBC escapes pairs: { and } */ - private static String removeEscapes(String query) { + final private static String removeEscapes(final String query) { if (query == null) return null; - int firstAccOpen = query.indexOf("{"); + final int firstAccOpen = query.indexOf("{"); if (firstAccOpen == -1) // nothing to remove return query; - int len = query.length(); - StringBuilder buf = new StringBuilder(len); + final int len = query.length(); + final StringBuilder buf = new StringBuilder(len); int countAccolades = 0; // simple scanner which copies all characters except the first '{' and matching '}' character // we currently do not check if 'call' appears after the first '{' and before the '}' character @@ -150,7 +150,7 @@ public class MonetCallableStatement * this will only succeed for strings like: "1", "2", "3", etc * throws SQLException if it cannot convert the string to an integer number */ - private int nameToIndex(String parameterName) throws SQLException { + final private int nameToIndex(final String parameterName) throws SQLException { if (parameterName == null) throw new SQLException("Missing parameterName value", "22002"); try {
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetClob.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetClob.java @@ -8,12 +8,9 @@ package nl.cwi.monetdb.jdbc; -import java.io.ByteArrayInputStream; import java.io.InputStream; -import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; -import java.io.Writer; import java.sql.Clob; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; @@ -31,10 +28,9 @@ import java.sql.SQLFeatureNotSupportedEx * @author Fabian Groffen */ public final class MonetClob implements Clob { - private StringBuilder buf; - protected MonetClob(String in) { + protected MonetClob(final String in) { buf = new StringBuilder(in); } @@ -71,7 +67,7 @@ public final class MonetClob implements @Override public InputStream getAsciiStream() throws SQLException { checkBufIsNotNull(); - return new ByteArrayInputStream(buf.toString().getBytes()); + return new java.io.ByteArrayInputStream(buf.toString().getBytes()); } /** @@ -101,7 +97,7 @@ public final class MonetClob implements * or if pos + length is greater than the number of characters in the Clob */ @Override - public Reader getCharacterStream(long pos, long length) throws SQLException { + public Reader getCharacterStream(final long pos, final long length) throws SQLException { // buf and input argument pos will be checked in method getSubString(long, int) if (length < 0 || length > Integer.MAX_VALUE) { throw new SQLException("Invalid length value: " + length, "M1M05"); @@ -111,7 +107,7 @@ public final class MonetClob implements /** * Retrieves a copy of the specified substring in the CLOB value - * designated by this Clob object. The substring begins at + * designated by this Clob object. The substring begins at * position pos and has up to length consecutive characters. * * @param pos the first character of the substring to be @@ -125,7 +121,7 @@ public final class MonetClob implements * @throws SQLException - if there is an error accessing the CLOB value */ @Override - public String getSubString(long pos, int length) throws SQLException { + public String getSubString(final long pos, final int length) throws SQLException { checkBufIsNotNull(); if (pos < 1 || pos > buf.length()) { throw new SQLException("Invalid pos value: " + pos, "M1M05"); @@ -156,7 +152,7 @@ public final class MonetClob implements /** * Retrieves the character position at which the specified Clob - * object searchstr appears in this Clob object. The search + * object searchstr appears in this Clob object. The search * begins at position start. * * @param searchstr the Clob object for which to search @@ -167,7 +163,7 @@ public final class MonetClob implements * @throws SQLException - if there is an error accessing the CLOB value */ @Override - public long position(Clob searchstr, long start) throws SQLException { + public long position(final Clob searchstr, final long start) throws SQLException { // buf and input argument start will be checked in method position(String, long) if (searchstr == null) { throw new SQLException("Missing searchstr object", "M1M05"); @@ -178,7 +174,7 @@ public final class MonetClob implements /** * Retrieves the character position at which the specified * substring searchstr appears in the SQL CLOB value represented - * by this Clob object. The search begins at position start. + * by this Clob object. The search begins at position start. * * @param searchstr the substring for which to search * @param start the position at which to begin searching; @@ -188,7 +184,7 @@ public final class MonetClob implements * @throws SQLException - if there is an error accessing the CLOB value */ @Override - public long position(String searchstr, long start) throws SQLException { + public long position(final String searchstr, final long start) throws SQLException { checkBufIsNotNull(); if (searchstr == null) { throw new SQLException("Missing searchstr object", "M1M05"); @@ -216,7 +212,7 @@ public final class MonetClob implements * @throws SQLFeatureNotSupportedException - if the JDBC driver does not support this method */ @Override - public OutputStream setAsciiStream(long pos) throws SQLException { + public java.io.OutputStream setAsciiStream(final long pos) throws SQLException { throw MonetWrapper.newSQLFeatureNotSupportedException("setAsciiStream"); } @@ -237,7 +233,7 @@ public final class MonetClob implements * @throws SQLFeatureNotSupportedException - if the JDBC driver does not support this method */ @Override - public Writer setCharacterStream(long pos) throws SQLException { + public java.io.Writer setCharacterStream(final long pos) throws SQLException { throw MonetWrapper.newSQLFeatureNotSupportedException("setCharacterStream"); } @@ -253,7 +249,7 @@ public final class MonetClob implements * @throws SQLException if there is an error accessing the CLOB value or if pos is less than 1 */ @Override - public int setString(long pos, String str) throws SQLException { + public int setString(final long pos, final String str) throws SQLException { // buf will be checked in method setString(long, String, int, int) if (str == null) { throw new SQLException("Missing str object", "M1M05"); @@ -275,7 +271,7 @@ public final class MonetClob implements * @throws SQLException if there is an error accessing the CLOB value or if pos is less than 1 */ @Override - public int setString(long pos, String str, int offset, int len) + public int setString(final long pos, final String str, final int offset, final int len) throws SQLException { checkBufIsNotNull(); @@ -292,7 +288,7 @@ public final class MonetClob implements throw new SQLException("Invalid len value: " + len, "M1M05"); } - int ipos = (int) pos; + final int ipos = (int) pos; if ((ipos + len) > buf.capacity()) { buf.ensureCapacity(ipos + len); } @@ -309,7 +305,7 @@ public final class MonetClob implements * CLOB value or if len is less than 0 */ @Override - public void truncate(long len) throws SQLException { + public void truncate(final long len) throws SQLException { checkBufIsNotNull(); if (len < 0 || len > buf.length()) { throw new SQLException("Invalid len value: " + len, "M1M05"); @@ -325,7 +321,7 @@ public final class MonetClob implements * * @return the String this MonetClob wraps or empty string when this MonetClob was freed. */ - public String toString() { + final public String toString() { return (buf != null) ? buf.toString() : ""; } }
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetConnection.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetConnection.java @@ -12,7 +12,6 @@ import java.io.File; import java.io.IOException; import java.net.SocketException; import java.net.SocketTimeoutException; -import java.net.UnknownHostException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -28,19 +27,12 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.WeakHashMap; import java.util.concurrent.Executor; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import nl.cwi.monetdb.jdbc.types.INET; -import nl.cwi.monetdb.jdbc.types.URL; -import nl.cwi.monetdb.mcl.MCLException; import nl.cwi.monetdb.mcl.io.BufferedMCLReader; import nl.cwi.monetdb.mcl.io.BufferedMCLWriter; import nl.cwi.monetdb.mcl.net.MapiSocket; @@ -72,7 +64,7 @@ import nl.cwi.monetdb.mcl.parser.StartOf * * @author Fabian Groffen * @author Martin van Dinther - * @version 1.3 + * @version 1.4 */ public class MonetConnection extends MonetWrapper @@ -99,7 +91,7 @@ public class MonetConnection /** The Writer to the server */ private final BufferedMCLWriter out; - /** A StartOfHeaderParser declared for reuse. */ + /** A StartOfHeaderParser declared for reuse. */ private StartOfHeaderParser sohp = new StartOfHeaderParser(); /** Whether this Connection is closed (and cannot be used anymore) */ @@ -115,15 +107,15 @@ public class MonetConnection private Map<String,Class<?>> typeMap = new HashMap<String,Class<?>>() { private static final long serialVersionUID = 1L; { - put("inet", INET.class); - put("url", URL.class); + put("inet", nl.cwi.monetdb.jdbc.types.INET.class); + put("url", nl.cwi.monetdb.jdbc.types.URL.class); } }; // See javadoc for documentation about WeakHashMap if you don't know what // it does !!!NOW!!! (only when you deal with it of course) /** A Map containing all (active) Statements created from this Connection */ - private Map<Statement,?> statements = new WeakHashMap<Statement, Object>(); + private WeakHashMap<Statement,?> statements = new WeakHashMap<Statement, Object>(); /** The number of results we receive from the server at once */ private int curReplySize = -1; // the server by default uses -1 (all) @@ -171,7 +163,7 @@ public class MonetConnection * @throws SQLException if a database error occurs * @throws IllegalArgumentException is one of the arguments is null or empty */ - MonetConnection(Properties props) + MonetConnection(final Properties props) throws SQLException, IllegalArgumentException { // for debug: System.out.println("New connection object. Received properties are: " + props.toString()); @@ -181,7 +173,7 @@ public class MonetConnection if (this.hostname != null) conn_props.setProperty("host", this.hostname); - String port_prop = props.getProperty("port"); + final String port_prop = props.getProperty("port"); if (port_prop != null) { try { this.port = Integer.parseInt(port_prop); @@ -214,11 +206,11 @@ public class MonetConnection conn_props.setProperty("debug", Boolean.toString(debug)); } - String hash = props.getProperty("hash"); + final String hash = props.getProperty("hash"); if (hash != null) conn_props.setProperty("hash", hash); - String treatBlobAsVarBinary_prop = props.getProperty("treat_blob_as_binary"); + final String treatBlobAsVarBinary_prop = props.getProperty("treat_blob_as_binary"); if (treatBlobAsVarBinary_prop != null) { treatBlobAsVarBinary = Boolean.parseBoolean(treatBlobAsVarBinary_prop); conn_props.setProperty("treat_blob_as_binary", Boolean.toString(treatBlobAsVarBinary)); @@ -226,7 +218,7 @@ public class MonetConnection typeMap.put("blob", Byte[].class); } - String treatClobAsVarChar_prop = props.getProperty("treat_clob_as_varchar"); + final String treatClobAsVarChar_prop = props.getProperty("treat_clob_as_varchar"); if (treatClobAsVarChar_prop != null) { treatClobAsVarChar = Boolean.parseBoolean(treatClobAsVarChar_prop); conn_props.setProperty("treat_clob_as_varchar", Boolean.toString(treatClobAsVarChar)); @@ -235,7 +227,7 @@ public class MonetConnection } int sockTimeout = 0; - String so_timeout_prop = props.getProperty("so_timeout"); + final String so_timeout_prop = props.getProperty("so_timeout"); if (so_timeout_prop != null) { try { sockTimeout = Integer.parseInt(so_timeout_prop); @@ -274,13 +266,14 @@ public class MonetConnection // we're debugging here... uhm, should be off in real life if (debug) { try { - String fname = props.getProperty("logfile", "monet_" + System.currentTimeMillis() + ".log"); + final String fname = props.getProperty("logfile", "monet_" + System.currentTimeMillis() + ".log"); File f = new File(fname); + int ext = fname.lastIndexOf('.'); if (ext < 0) ext = fname.length(); - String pre = fname.substring(0, ext); - String suf = fname.substring(ext); + final String pre = fname.substring(0, ext); + final String suf = fname.substring(ext); for (int i = 1; f.exists(); i++) { f = new File(pre + "-" + i + suf); @@ -293,7 +286,7 @@ public class MonetConnection } try { - List<String> warnings = server.connect(hostname, port, username, password); + final java.util.List<String> warnings = server.connect(hostname, port, username, password); for (String warning : warnings) { addWarning(warning, "01M02"); } @@ -305,18 +298,18 @@ public class MonetConnection in = server.getReader(); out = server.getWriter(); - String error = in.waitForPrompt(); + final String error = in.waitForPrompt(); if (error != null) throw new SQLNonTransientConnectionException((error.length() > 6) ? error.substring(6) : error, "08001"); - } catch (UnknownHostException e) { + } catch (java.net.UnknownHostException e) { throw new SQLNonTransientConnectionException("Unknown Host (" + hostname + "): " + e.getMessage(), "08006"); } catch (IOException e) { throw new SQLNonTransientConnectionException("Unable to connect (" + hostname + ":" + port + "): " + e.getMessage(), "08006"); } catch (MCLParseException e) { throw new SQLNonTransientConnectionException(e.getMessage(), "08001"); - } catch (MCLException e) { - String[] connex = e.getMessage().split("\n"); - SQLException sqle = new SQLNonTransientConnectionException(connex[0], "08001", e); + } catch (nl.cwi.monetdb.mcl.MCLException e) { + final String[] connex = e.getMessage().split("\n"); + final SQLException sqle = new SQLNonTransientConnectionException(connex[0], "08001", e); for (int i = 1; i < connex.length; i++) { sqle.setNextException(new SQLNonTransientConnectionException(connex[1], "08001")); } @@ -355,7 +348,7 @@ public class MonetConnection setAutoCommit(true); // set our time zone on the server - Calendar cal = Calendar.getInstance(); + final Calendar cal = Calendar.getInstance(); int offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET); offset /= (60 * 1000); // milliseconds to minutes String tz = offset < 0 ? "-" : "+"; @@ -459,7 +452,7 @@ public class MonetConnection * @throws SQLException if a database access error occurs */ @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + public Statement createStatement(final int resultSetType, final int resultSetConcurrency) throws SQLException { return createStatement(resultSetType, resultSetConcurrency, MonetResultSet.DEF_HOLDABILITY); } @@ -487,9 +480,9 @@ public class MonetConnection * concurrency, and holdability */ @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + public Statement createStatement(final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException { try { - Statement ret = new MonetStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); + final Statement ret = new MonetStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); // store it in the map for when we close... statements.put(ret, null); return ret; @@ -648,7 +641,7 @@ public class MonetConnection * @return the native form of this statement */ @Override - public String nativeSQL(String sql) { + public String nativeSQL(final String sql) { /* there is currently no way to get the native MonetDB rewritten SQL string back, so just return the original string */ /* in future we may replace/remove the escape sequences { <escape-type> ...} before sending it to the server */ return sql; @@ -672,10 +665,9 @@ public class MonetConnection * Typically this statement is specified using JDBC call escape syntax. * @return a new default CallableStatement object containing the pre-compiled SQL statement * @throws SQLException - if a database access error occurs or this method is called on a closed connection - * @throws SQLFeatureNotSupportedException - if the JDBC driver does not support this method. */ @Override - public CallableStatement prepareCall(String sql) throws SQLException { + public CallableStatement prepareCall(final String sql) throws SQLException { return prepareCall(sql, MonetResultSet.DEF_RESULTSETTYPE, MonetResultSet.DEF_CONCURRENCY, MonetResultSet.DEF_HOLDABILITY); } @@ -692,11 +684,9 @@ public class MonetConnection * will produce ResultSet objects with the given type and concurrency * @throws SQLException - if a database access error occurs, this method is called on a closed connection or * the given parameters are not ResultSet constants indicating type and concurrency - * @throws SQLFeatureNotSupportedException - if the JDBC driver does not support this method or - * this method is not supported for the specified result set type and result set concurrency. */ @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency) throws SQLException { return prepareCall(sql, resultSetType, resultSetConcurrency, MonetResultSet.DEF_HOLDABILITY); } @@ -712,15 +702,13 @@ public class MonetConnection * @return a new CallableStatement object, containing the pre-compiled SQL statement, that will generate ResultSet objects with the given type, concurrency, and holdability * @throws SQLException - if a database access error occurs, this method is called on a closed connection or * the given parameters are not ResultSet constants indicating type, concurrency, and holdability - * @throws SQLFeatureNotSupportedException - if the JDBC driver does not support this method or - * this method is not supported for the specified result set type, result set holdability and result set concurrency. */ @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) + public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException { try { - CallableStatement ret = new MonetCallableStatement( + final CallableStatement ret = new MonetCallableStatement( this, resultSetType, resultSetConcurrency, @@ -764,7 +752,7 @@ public class MonetConnection * @throws SQLException if a database access error occurs */ @Override - public PreparedStatement prepareStatement(String sql) throws SQLException { + public PreparedStatement prepareStatement(final String sql) throws SQLException { return prepareStatement(sql, MonetResultSet.DEF_RESULTSETTYPE, MonetResultSet.DEF_CONCURRENCY, MonetResultSet.DEF_HOLDABILITY); } @@ -789,7 +777,7 @@ public class MonetConnection * type and concurrency */ @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency) throws SQLException { return prepareStatement(sql, resultSetType, resultSetConcurrency, MonetResultSet.DEF_HOLDABILITY); } @@ -820,11 +808,11 @@ public class MonetConnection * concurrency, and holdability */ @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) + public PreparedStatement prepareStatement(final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException { try { - PreparedStatement ret = new MonetPreparedStatement( + final PreparedStatement ret = new MonetPreparedStatement( this, resultSetType, resultSetConcurrency, @@ -874,7 +862,7 @@ public class MonetConnection * whether auto-generated keys should be returned */ @Override - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + public PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) throws SQLException { if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS && autoGeneratedKeys != Statement.NO_GENERATED_KEYS) throw new SQLException("Invalid argument, expected RETURN_GENERATED_KEYS or NO_GENERATED_KEYS", "M1M05"); @@ -908,7 +896,7 @@ public class MonetConnection * @throws SQLFeatureNotSupportedException - if the JDBC driver does not support this method */ @Override - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + public PreparedStatement prepareStatement(final String sql, final int[] columnIndexes) throws SQLException { throw newSQLFeatureNotSupportedException("prepareStatement(String sql, int[] columnIndexes)"); } @@ -937,7 +925,7 @@ public class MonetConnection * @throws SQLFeatureNotSupportedException - if the JDBC driver does not support this method */ @Override - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + public PreparedStatement prepareStatement(final String sql, final String[] columnNames) throws SQLException { throw newSQLFeatureNotSupportedException("prepareStatement(String sql, String[] columnNames)"); } @@ -952,11 +940,11 @@ public class MonetConnection * transaction */ @Override - public void releaseSavepoint(Savepoint savepoint) throws SQLException { + public void releaseSavepoint(final Savepoint savepoint) throws SQLException { if (!(savepoint instanceof MonetSavepoint)) throw new SQLException("This driver can only handle savepoints it created itself", "M0M06"); - MonetSavepoint sp = (MonetSavepoint)savepoint; + final MonetSavepoint sp = (MonetSavepoint)savepoint; // note: can't use sendIndependentCommand here because we need // to process the auto_commit state the server gives @@ -990,11 +978,11 @@ public class MonetConnection * object is currently in auto-commit mode */ @Override - public void rollback(Savepoint savepoint) throws SQLException { + public void rollback(final Savepoint savepoint) throws SQLException { if (!(savepoint instanceof MonetSavepoint)) throw new SQLException("This driver can only handle savepoints it created itself", "M0M06"); - MonetSavepoint sp = (MonetSavepoint)savepoint; + final MonetSavepoint sp = (MonetSavepoint)savepoint; // note: can't use sendIndependentCommand here because we need // to process the auto_commit state the server gives @@ -1026,7 +1014,7 @@ public class MonetConnection * @see #getAutoCommit() */ @Override - public void setAutoCommit(boolean autoCommit) throws SQLException { + public void setAutoCommit(final boolean autoCommit) throws SQLException { if (this.autoCommit != autoCommit) { sendControlCommand("auto_commit " + (autoCommit ? "1" : "0")); this.autoCommit = autoCommit; @@ -1039,7 +1027,7 @@ public class MonetConnection * does not support catalogs, it will silently ignore this request. */ @Override - public void setCatalog(String catalog) { + public void setCatalog(final String catalog) { // silently ignore this request as MonetDB does not support catalogs } @@ -1056,7 +1044,7 @@ public class MonetConnection * @see #getHoldability() */ @Override - public void setHoldability(int holdability) throws SQLException { + public void setHoldability(final int holdability) throws SQLException { // we only support ResultSet.HOLD_CURSORS_OVER_COMMIT if (holdability != ResultSet.HOLD_CURSORS_OVER_COMMIT) throw newSQLFeatureNotSupportedException("setHoldability(CLOSE_CURSORS_AT_COMMIT)"); @@ -1073,7 +1061,7 @@ public class MonetConnection * method is called during a transaction. */ @Override - public void setReadOnly(boolean readOnly) throws SQLException { + public void setReadOnly(final boolean readOnly) throws SQLException { if (readOnly == true) addWarning("cannot setReadOnly(true): read-only Connection mode not supported", "01M08"); } @@ -1089,7 +1077,7 @@ public class MonetConnection @Override public Savepoint setSavepoint() throws SQLException { // create a new Savepoint object - MonetSavepoint sp = new MonetSavepoint(); + final MonetSavepoint sp = new MonetSavepoint(); // note: can't use sendIndependentCommand here because we need // to process the auto_commit state the server gives @@ -1107,9 +1095,9 @@ public class MonetConnection * object is currently in auto-commit mode */ @Override - public Savepoint setSavepoint(String name) throws SQLException { + public Savepoint setSavepoint(final String name) throws SQLException { // create a new Savepoint object - MonetSavepoint sp; + final MonetSavepoint sp; try { sp = new MonetSavepoint(name); } catch (IllegalArgumentException e) { @@ -1134,7 +1122,7 @@ public class MonetConnection * Connection.TRANSACTION_SERIALIZABLE. */ @Override - public void setTransactionIsolation(int level) { + public void setTransactionIsolation(final int level) { if (level != TRANSACTION_SERIALIZABLE) { addWarning("MonetDB only supports fully serializable " + "transactions, continuing with transaction level " + @@ -1151,7 +1139,7 @@ public class MonetConnection * this Connection object's default type map */ @Override - public void setTypeMap(Map<String, Class<?>> map) { + public void setTypeMap(final Map<String, Class<?>> map) { typeMap = map; } @@ -1196,7 +1184,7 @@ public class MonetConnection * @since 1.6 */ @Override - public java.sql.Array createArrayOf(String typeName, Object[] elements) throws SQLException { + public java.sql.Array createArrayOf(final String typeName, final Object[] elements) throws SQLException { throw newSQLFeatureNotSupportedException("createArrayOf"); } @@ -1230,8 +1218,7 @@ public class MonetConnection */ @Override public java.sql.Blob createBlob() throws SQLException { - byte[] buf = new byte[1]; - return new MonetBlob(buf); + return new MonetBlob(new byte[1]); } /** @@ -1307,7 +1294,7 @@ public class MonetConnection * @since 1.6 */ @Override - public boolean isValid(int timeout) throws SQLException { + public boolean isValid(final int timeout) throws SQLException { if (timeout < 0) throw new SQLException("timeout is less than 0", "M1M05"); if (closed) @@ -1320,7 +1307,7 @@ public class MonetConnection try { stmt = createStatement(); if (stmt != null) { - int original_timeout = stmt.getQueryTimeout(); + final int original_timeout = stmt.getQueryTimeout(); if (timeout > 0 && original_timeout != timeout) { // we need to change the requested timeout for this test query stmt.setQueryTimeout(timeout); @@ -1376,7 +1363,7 @@ public class MonetConnection * @since 1.6 */ @Override - public String getClientInfo(String name) throws SQLException { + public String getClientInfo(final String name) throws SQLException { if (name == null || name.isEmpty()) return null; return conn_props.getProperty(name); @@ -1437,7 +1424,7 @@ public class MonetConnection * @since 1.6 */ @Override - public void setClientInfo(String name, String value) throws SQLClientInfoException { + public void setClientInfo(final String name, final String value) throws SQLClientInfoException { if (name == null || name.isEmpty()) { addWarning("setClientInfo: missing property name", "01M07"); return; @@ -1465,7 +1452,6 @@ public class MonetConnection } else { addWarning("setClientInfo: " + name + "is not a recognised property", "01M07"); } - return; } /** @@ -1492,11 +1478,10 @@ public class MonetConnection * @since 1.6 */ @Override - public void setClientInfo(Properties props) throws SQLClientInfoException { + public void setClientInfo(final Properties props) throws SQLClientInfoException { if (props != null) { for (Entry<Object, Object> entry : props.entrySet()) { - setClientInfo(entry.getKey().toString(), - entry.getValue().toString()); + setClientInfo(entry.getKey().toString(), entry.getValue().toString()); } } } @@ -1513,7 +1498,7 @@ public class MonetConnection * @since 1.7 */ @Override - public void setSchema(String schema) throws SQLException { + public void setSchema(final String schema) throws SQLException { if (closed) throw new SQLException("Cannot call on closed Connection", "M1M20"); if (schema == null || schema.isEmpty()) @@ -1597,7 +1582,7 @@ public class MonetConnection * @since 1.7 */ @Override - public void abort(Executor executor) throws SQLException { + public void abort(final Executor executor) throws SQLException { if (closed) return; if (executor == null) @@ -1627,7 +1612,7 @@ public class MonetConnection * @since 1.7 */ @Override - public void setNetworkTimeout(Executor executor, int millis) throws SQLException { + public void setNetworkTimeout(final Executor executor, final int millis) throws SQLException { if (closed) throw new SQLException("Cannot call on closed Connection", "M1M20"); if (executor == null) @@ -1674,10 +1659,7 @@ public class MonetConnection * Defined as public because it is called from: MonetDatabaseMetaData.java getURL() */ String getJDBCURL() { - String language = ""; - if (lang == LANG_MAL) - language = "?language=mal"; - return MonetDriver.MONETURL + hostname + ":" + port + "/" + database + language; + return MonetDriver.MONETURL + hostname + ":" + port + "/" + database + (lang == LANG_MAL ? "?language=mal" : ""); } /** @@ -1729,7 +1711,7 @@ public class MonetConnection /** * Internal utility method to query the server to find out if it has the system table sys.<tablename>. */ - private boolean existsSysTable(String tablename) { + private boolean existsSysTable(final String tablename) { boolean exists = false; Statement stmt = null; ResultSet rs = null; @@ -1769,9 +1751,9 @@ public class MonetConnection * @param command the exact string to send to MonetDB * @throws SQLException if an IO exception or a database error occurs */ - private void sendTransactionCommand(String command) throws SQLException { + private void sendTransactionCommand(final String command) throws SQLException { // create a container for the result - ResponseList l = new ResponseList(0, 0, ResultSet.FETCH_FORWARD, ResultSet.CONCUR_READ_ONLY); + final ResponseList l = new ResponseList(0, 0, ResultSet.FETCH_FORWARD, ResultSet.CONCUR_READ_ONLY); // send the appropriate query string to the database try { l.processQuery(command); @@ -1814,16 +1796,15 @@ public class MonetConnection * @param usequeryTempl send the command using a queryTempl? else it is send using commandTempl * @throws SQLException if an IO exception or a database error occurs */ - private void sendCommand(String command, boolean usequeryTempl) throws SQLException { - String cmd = usequeryTempl ? - (queryTempl[0] == null ? "" : queryTempl[0]) + command + (queryTempl[1] == null ? "" : queryTempl[1]) - : - (commandTempl[0] == null ? "" : commandTempl[0]) + command + (commandTempl[1] == null ? "" : commandTempl[1]); + private void sendCommand(final String command, final boolean usequeryTempl) throws SQLException { + final String cmd = usequeryTempl + ? (queryTempl[0] == null ? "" : queryTempl[0]) + command + (queryTempl[1] == null ? "" : queryTempl[1]) + : (commandTempl[0] == null ? "" : commandTempl[0]) + command + (commandTempl[1] == null ? "" : commandTempl[1]); synchronized (server) { try { out.writeLine(cmd); - String error = in.waitForPrompt(); + final String error = in.waitForPrompt(); if (error != null) throw new SQLException(error.substring(6), error.substring(0, 5)); } catch (SocketTimeoutException e) { @@ -1843,8 +1824,8 @@ public class MonetConnection * * @param reason the warning message */ - void addWarning(String reason, String sqlstate) { - SQLWarning warng = new SQLWarning(reason, sqlstate); + private final void addWarning(final String reason, final String sqlstate) { + final SQLWarning warng = new SQLWarning(reason, sqlstate); if (warnings == null) { warnings = warng; } else { @@ -1939,7 +1920,7 @@ public class MonetConnection /** The Connection that we should use when requesting a new block */ private final MonetConnection.ResponseList parent; /** Whether the fetchSize was explitly set by the user */ - private boolean cacheSizeSetExplicitly = false; + private final boolean cacheSizeSetExplicitly; /** Whether we should send an Xclose command to the server * if we close this Response */ private boolean destroyOnClose; @@ -1947,7 +1928,7 @@ public class MonetConnection private int blockOffset = 0; /** A parser for header lines */ - HeaderLineParser hlp; + private final HeaderLineParser hlp; /** A boolean array telling whether the headers are set or not */ private final boolean[] isSet; @@ -1970,12 +1951,12 @@ public class MonetConnection * @param seq the query sequence number */ ResultSetResponse( - int id, - int tuplecount, - int columncount, - int rowcount, - MonetConnection.ResponseList parent, - int seq) + final int id, + final int tuplecount, + final int columncount, + final int rowcount, + final MonetConnection.ResponseList parent, + final int seq) throws SQLException { isSet = new boolean[4]; @@ -2026,7 +2007,7 @@ public class MonetConnection */ // {{{ addLine @Override - public String addLine(String tmpLine, int linetype) { + public String addLine(final String tmpLine, final int linetype) { if (isSet[LENS] && isSet[TYPES] && isSet[TABLES] && isSet[NAMES]) { return resultBlocks[0].addLine(tmpLine, linetype); } @@ -2086,9 +2067,9 @@ public class MonetConnection * @param stop where the relevant data stops * @return an array of Strings */ - private final String[] getValues(char[] chrLine, int start, int stop) { + private final String[] getValues(final char[] chrLine, int start, final int stop) { int elem = 0; - String[] values = new String[columncount]; + final String[] values = new String[columncount]; for (int i = start; i < stop; i++) { if (chrLine[i] == '\t' && chrLine[i - 1] == ',') { @@ -2110,8 +2091,8 @@ public class MonetConnection * @param offset the offset number of rows for this block * @param rr the DataBlockResponse to add */ - void addDataBlockResponse(int offset, DataBlockResponse rr) { - int block = (offset - blockOffset) / cacheSize; + void addDataBlockResponse(final int offset, final DataBlockResponse rr) { + final int block = (offset - blockOffset) / cacheSize; resultBlocks[block] = rr; } @@ -2124,13 +2105,13 @@ public class MonetConnection */ @Override public void complete() throws SQLException { - String error = ""; - if (!isSet[NAMES]) error = "name header missing\n"; - if (!isSet[TYPES]) error += "type header missing\n"; - if (!isSet[TABLES]) error += "table name header missing\n"; - if (!isSet[LENS]) error += "column width header missing\n"; - if (!error.isEmpty()) - throw new SQLException(error, "M0M10"); + final StringBuilder err = new StringBuilder(99); + if (!isSet[NAMES]) err.append("name header missing\n"); + if (!isSet[TYPES]) err.append("type header missing\n"); + if (!isSet[TABLES]) err.append("table name header missing\n"); + if (!isSet[LENS]) err.append("column width header missing\n"); + if (err.length() > 0) + throw new SQLException(err.toString(), "M0M10"); } /** @@ -2216,7 +2197,7 @@ public class MonetConnection * is out of the scope of the result set * @throws SQLException if an database error occurs */ - String getLine(int row) throws SQLException { + String getLine(final int row) throws SQLException { if (row >= tuplecount || row < 0) return null; @@ -2345,14 +2326,14 @@ public class MonetConnection /** The counter which keeps the current position in the data array */ private int pos; /** Whether we can discard lines as soon as we have read them */ - private boolean forwardOnly; + private final boolean forwardOnly; /** * Constructs a DataBlockResponse object * @param size the size of the data array to create * @param forward whether this is a forward only result */ - DataBlockResponse(int size, boolean forward) { + DataBlockResponse(final int size, final boolean forward) { pos = -1; data = new String[size]; forwardOnly = forward; @@ -2370,7 +2351,7 @@ public class MonetConnection * or additional lines are not allowed. */ @Override - public String addLine(String line, int linetype) { + public String addLine(final String line, final int linetype) { if (linetype != BufferedMCLReader.RESULT) return "protocol violation: unexpected line in data block: " + line; // add to the backing array @@ -2403,8 +2384,9 @@ public class MonetConnection @Override public void complete() throws SQLException { if ((pos + 1) != data.length) - throw new SQLException("Inconsistent state detected! Current block capacity: " - + data.length + ", block usage: " + (pos + 1) + ". Did MonetDB send what it promised to?", "M0M10"); + throw new SQLException("Inconsistent state detected! Current block capacity: " + + data.length + ", block usage: " + (pos + 1) + + ". Did MonetDB send what it promised to?", "M0M10"); } /** @@ -2414,7 +2396,8 @@ public class MonetConnection @Override public void close() { // feed all rows to the garbage collector - for (int i = 0; i < data.length; i++) data[i] = null; + for (int i = 0; i < data.length; i++) + data[i] = null; } /** @@ -2425,9 +2408,9 @@ public class MonetConnection * @param line the row to retrieve * @return the requested row as String */ - String getRow(int line) { + String getRow(final int line) { if (forwardOnly) { - String ret = data[line]; + final String ret = data[line]; data[line] = null; return ret; } else { @@ -2450,14 +2433,14 @@ public class MonetConnection public final int count; public final String lastid; - public UpdateResponse(int cnt, String id) { + public UpdateResponse(final int cnt, final String id) { // fill the blank finals this.count = cnt; this.lastid = id; } @Override - public String addLine(String line, int linetype) { + public String addLine(final String line, final int linetype) { return "Header lines are not supported for an UpdateResponse"; } @@ -2492,7 +2475,7 @@ public class MonetConnection public final int state = Statement.SUCCESS_NO_INFO; @Override - public String addLine(String line, int linetype) { + public String addLine(final String line, final int linetype) { return "Header lines are not supported for a SchemaResponse"; } @@ -2522,7 +2505,7 @@ public class MonetConnection class AutoCommitResponse extends SchemaResponse { public final boolean autocommit; - public AutoCommitResponse(boolean ac) { + public AutoCommitResponse(final boolean ac) { // fill the blank final this.autocommit = ac; } @@ -2548,10 +2531,10 @@ public class MonetConnection private final int seqnr; /** A list of the Responses associated with the query, * in the right order */ - private List<Response> responses; + private final ArrayList<Response> responses; /** A map of ResultSetResponses, used for additional * DataBlockResponse mapping */ - private Map<Integer, ResultSetResponse> rsresponses; + private HashMap<Integer, ResultSetResponse> rsresponses; /** The current header returned by getNextResponse() */ private int curResponse; @@ -2567,10 +2550,10 @@ public class MonetConnection * @param rsconcur the concurrency of result sets to produce */ ResponseList( - int cachesize, - int maxrows, - int rstype, - int rsconcur + final int cachesize, + final int maxrows, + final int rstype, + final int rsconcur ) throws SQLException { this.cachesize = cachesize; this.maxrows = maxrows; @@ -2591,7 +2574,7 @@ public class MonetConnection if (rstype == ResultSet.TYPE_FORWARD_ONLY) { // free resources if we're running forward only if (curResponse >= 0 && curResponse < responses.size()) { - Response tmp = responses.get(curResponse); + final Response tmp = responses.get(curResponse); if (tmp != null) tmp.close(); responses.set(curResponse, null); @@ -2613,10 +2596,10 @@ public class MonetConnection * * @param i the index position of the header to close */ - void closeResponse(int i) { + void closeResponse(final int i) { if (i < 0 || i >= responses.size()) return; - Response tmp = responses.set(i, null); + final Response tmp = responses.set(i, null); if (tmp != null) tmp.close(); } @@ -2666,7 +2649,7 @@ public class MonetConnection * * @throws SQLException if a database error occurs */ - void processQuery(String query) throws SQLException { + void processQuery(final String query) throws SQLException { executeQuery(queryTempl, query); } @@ -2678,7 +2661,7 @@ public class MonetConnection * @throws SQLException if a database error occurs */ @SuppressWarnings("fallthrough") - void executeQuery(String[] templ, String query) + void executeQuery(final String[] templ, final String query) throws SQLException { String error = null; @@ -2728,10 +2711,10 @@ public class MonetConnection throw new MCLParseException("Q_PARSE header not allowed here", 1); case StartOfHeaderParser.Q_TABLE: case StartOfHeaderParser.Q_PREPARE: { - int id = sohp.getNextAsInt(); + final int id = sohp.getNextAsInt(); int tuplecount = sohp.getNextAsInt(); - int columncount = sohp.getNextAsInt(); - int rowcount = sohp.getNextAsInt(); + final int columncount = sohp.getNextAsInt(); + final int rowcount = sohp.getNextAsInt(); // enforce the maxrows setting if (maxrows != 0 && tuplecount > maxrows) tuplecount = maxrows; @@ -2752,7 +2735,7 @@ public class MonetConnection res = new SchemaResponse(); break; case StartOfHeaderParser.Q_TRANS: - boolean ac = sohp.getNextAsString().equals("t") ? true : false; + final boolean ac = sohp.getNextAsString().equals("t") ? true : false; if (autoCommit && ac) { addWarning("Server enabled auto commit mode " + "while local state already was auto commit.", "01M11"); @@ -2762,16 +2745,16 @@ public class MonetConnection break; case StartOfHeaderParser.Q_BLOCK: { // a new block of results for a response... - int id = sohp.getNextAsInt(); + final int id = sohp.getNextAsInt(); sohp.getNextAsInt(); // columncount - int rowcount = sohp.getNextAsInt(); - int offset = sohp.getNextAsInt(); - ResultSetResponse t = rsresponses.get(Integer.valueOf(id)); + final int rowcount = sohp.getNextAsInt(); + final int offset = sohp.getNextAsInt(); + final ResultSetResponse t = (rsresponses != null) ? rsresponses.get(Integer.valueOf(id)) : null; if (t == null) { error = "M0M12!no ResultSetResponse with id " + id + " found"; break; } - DataBlockResponse r = new DataBlockResponse(rowcount, t.getRSType() == ResultSet.TYPE_FORWARD_ONLY); + final DataBlockResponse r = new DataBlockResponse(rowcount, t.getRSType() == ResultSet.TYPE_FORWARD_ONLY); t.addDataBlockResponse(offset, r); res = r; } break; @@ -2849,9 +2832,9 @@ public class MonetConnection if (error != null) { SQLException ret = null; - String[] errors = error.split("\n"); + final String[] errors = error.split("\n"); for (int i = 0; i < errors.length; i++) { - SQLException newErr; + final SQLException newErr; if (errors[i].length() >= 6) { newErr = new SQLException(errors[i].substring(6), errors[i].substring(0, 5)); } else {
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetDataSource.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetDataSource.java @@ -14,7 +14,6 @@ import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import javax.sql.DataSource; import java.util.Properties; -import java.util.logging.Logger; /** * A DataSource suitable for the MonetDB database. @@ -28,9 +27,12 @@ import java.util.logging.Logger; * Additionally, pooled connections can be used when using a DataSource. * * @author Fabian Groffen - * @version 0.1 + * @version 0.2 */ -public class MonetDataSource extends MonetWrapper implements DataSource { +public final class MonetDataSource + extends MonetWrapper + implements DataSource +{ private String description; private int loginTimeout = 0; private String user; @@ -81,13 +83,13 @@ public class MonetDataSource extends Mon * @throws SQLException if connecting to the database fails */ @Override - public Connection getConnection(String username, String password) + public Connection getConnection(final String username, final String password) throws SQLException { if (loginTimeout > 0) { /// could enable Socket.setSoTimeout(int timeout) here... } - Properties props = new Properties(); + final Properties props = new Properties(); props.put("user", username); props.put("password", password); @@ -113,7 +115,7 @@ public class MonetDataSource extends Mon * @param seconds the number of seconds to wait before aborting the connect */ @Override - public void setLoginTimeout(int seconds) { + public void setLoginTimeout(final int seconds) { loginTimeout = seconds; } @@ -134,7 +136,7 @@ public class MonetDataSource extends Mon * @param out a PrintWriter - ignored */ @Override - public void setLogWriter(PrintWriter out) { + public void setLogWriter(final PrintWriter out) { } /** @@ -143,7 +145,7 @@ public class MonetDataSource extends Mon * * @param password the password */ - public void setPassword(String password) { + public void setPassword(final String password) { this.password = password; } @@ -161,7 +163,7 @@ public class MonetDataSource extends Mon * * @param user the username */ - public void setUser(String user) { + public void setUser(final String user) { this.user = user; } @@ -179,7 +181,7 @@ public class MonetDataSource extends Mon * * @param url the connection URL */ - public void setDatabaseName(String url) { + public void setDatabaseName(final String url) { this.url = url; } @@ -197,7 +199,7 @@ public class MonetDataSource extends Mon * * @param description the description */ - public void setDescription(String description) { + public void setDescription(final String description) { this.description = description; } @@ -214,7 +216,7 @@ public class MonetDataSource extends Mon * not use java.util.logging */ @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException { + public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw newSQLFeatureNotSupportedException("getParentLogger"); } }
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetDatabaseMetaData.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetDatabaseMetaData.java @@ -17,15 +17,16 @@ import java.sql.ResultSetMetaData; import java.sql.RowIdLifetime; import java.sql.Types; -import java.util.ArrayList; - /** * A DatabaseMetaData object suitable for the MonetDB database. * * @author Fabian Groffen, Martin van Dinther * @version 0.7 */ -public class MonetDatabaseMetaData extends MonetWrapper implements DatabaseMetaData { +public class MonetDatabaseMetaData + extends MonetWrapper + implements DatabaseMetaData +{ private final Connection con; // Internal cache for 3 server environment values @@ -33,7 +34,7 @@ public class MonetDatabaseMetaData exten private String env_monet_version; private String env_max_clients; - public MonetDatabaseMetaData(Connection parent) { + public MonetDatabaseMetaData(final Connection parent) { con = parent; } @@ -84,14 +85,13 @@ public class MonetDatabaseMetaData exten /** - * Internal utility method to create a Statement object, execute a query and return the ResulSet object. + * Internal utility method to create a Statement object, execute a query and return the ResulSet object which allows scrolling. * As the Statement object is created internally (the caller does not see it and thus can not close it), * we set it to close (and free server resources) when the ResultSet object is closed by the caller. */ - private ResultSet executeMetaDataQuery(String query) throws SQLException { - Statement stmt = null; + private ResultSet executeMetaDataQuery(final String query) throws SQLException { + final Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = null; - stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); if (stmt != null) { // for debug: System.out.println("SQL (len " + query.length() + "): " + query); rs = stmt.executeQuery(query); @@ -410,7 +410,7 @@ public class MonetDatabaseMetaData exten */ @Override public String getSQLKeywords() { - String keywords = getConcatenatedStringFromQuery("SELECT \"keyword\" FROM \"sys\".\"keywords\" ORDER BY 1"); + final String keywords = getConcatenatedStringFromQuery("SELECT \"keyword\" FROM \"sys\".\"keywords\" ORDER BY 1"); /* An old MonetDB server (pre Jul2015 release) will not have a table sys.keywords and return an empty String */ return (keywords.isEmpty()) ? @@ -442,8 +442,8 @@ public class MonetDatabaseMetaData exten * args: query: SQL SELECT query. Only the output of the first column is concatenated. * @return a String of query result values concatenated into one string, and values separated by comma's */ - private String getConcatenatedStringFromQuery(String query) { - StringBuilder sb = new StringBuilder(1024); + private String getConcatenatedStringFromQuery(final String query) { + final StringBuilder sb = new StringBuilder(1024); Statement st = null; ResultSet rs = null; try { @@ -489,7 +489,7 @@ public class MonetDatabaseMetaData exten @Override public String getNumericFunctions() { - String match = + final String match = "('tinyint', 'smallint', 'int', 'bigint', 'hugeint', 'decimal', 'double', 'real') )" + " AND \"type\" = 1" + // only scalar functions // exclude functions which belong to the 'str' module @@ -500,11 +500,11 @@ public class MonetDatabaseMetaData exten @Override public String getStringFunctions() { - String match = + final String match = "('char', 'varchar', 'clob', 'json') )" + // include functions which belong to the 'str' module " OR \"mod\" = 'str')"; - String unionPart = + final String unionPart = // add system functions which are not listed in sys.functions but implemented in the SQL parser (see sql/server/sql_parser.y) " UNION SELECT 'position'"; return getConcatenatedStringFromQuery(FunctionsSelect + FunctionsWhere + match + OrFunctionsMaxMin + unionPart + FunctionsOrderBy1); @@ -514,7 +514,7 @@ public class MonetDatabaseMetaData exten public String getSystemFunctions() { // Note: As of Apr2019 (11.33.3) release the system table systemfunctions is replaced by a view which queries functions.system // TODO: Replace join to sys.systemfunctions with " AND \"system\" " but only if the server-version is >= 11.33.3 - String wherePart = + final String wherePart = "\"id\" NOT IN (SELECT \"func_id\" FROM \"sys\".\"args\" WHERE \"number\" = 1)" + // without any args " AND \"id\" IN (SELECT \"function_id\" FROM \"sys\".\"systemfunctions\")" + // only functions marked as system " AND \"type\" = 1" + // only scalar functions @@ -533,9 +533,9 @@ public class MonetDatabaseMetaData exten @Override public String getTimeDateFunctions() { - String wherePart = + final String wherePart = "\"mod\" IN ('mtime','timestamp') OR \"name\" IN ('localtime','localtimestamp','date_trunc')"; - String unionPart = + final String unionPart = // add time date functions which are not listed in sys.functions but implemented in the SQL parser (see sql/server/sql_parser.y) " UNION SELECT 'extract'" + " UNION SELECT 'now'"; @@ -638,7 +638,7 @@ public class MonetDatabaseMetaData exten * @return true if so; false otherwise */ @Override - public boolean supportsConvert(int fromType, int toType) { + public boolean supportsConvert(final int fromType, final int toType) { switch (fromType) { case Types.BOOLEAN: switch (toType) { @@ -1627,7 +1627,7 @@ public class MonetDatabaseMetaData exten * @see Connection */ @Override - public boolean supportsTransactionIsolationLevel(int level) { + public boolean supportsTransactionIsolationLevel(final int level) { return level == Connection.TRANSACTION_SERIALIZABLE; } @@ -1726,13 +1726,13 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getProcedures( - String catalog, - String schemaPattern, - String procedureNamePattern + final String catalog, + final String schemaPattern, + final String procedureNamePattern ) throws SQLException { - boolean useCommentsTable = ((MonetConnection)con).commentsTableExists(); - StringBuilder query = new StringBuilder(980); + final boolean useCommentsTable = ((MonetConnection)con).commentsTableExists(); + final StringBuilder query = new StringBuilder(980); query.append("SELECT cast(null as char(1)) AS \"PROCEDURE_CAT\", " + "\"schemas\".\"name\" AS \"PROCEDURE_SCHEM\", " + "\"functions\".\"name\" AS \"PROCEDURE_NAME\", " + @@ -1839,12 +1839,12 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getProcedureColumns( - String catalog, - String schemaPattern, - String procedureNamePattern, - String columnNamePattern + final String catalog, + final String schemaPattern, + final String procedureNamePattern, + final String columnNamePattern ) throws SQLException { - StringBuilder query = new StringBuilder(2900); + final StringBuilder query = new StringBuilder(2900); query.append("SELECT cast(null as char(1)) AS \"PROCEDURE_CAT\", " + "\"schemas\".\"name\" AS \"PROCEDURE_SCHEM\", " + "\"functions\".\"name\" AS \"PROCEDURE_NAME\", " + @@ -1907,7 +1907,7 @@ public class MonetDatabaseMetaData exten * @param in the string to match * @return the SQL match part string */ - private static final String composeMatchPart(String in) { + private static final String composeMatchPart(final String in) { if (in == null) return "IS NULL"; @@ -1917,7 +1917,7 @@ public class MonetDatabaseMetaData exten sql = "LIKE '"; // all slashes and single quotes in input are escaped with a slash. - String escaped = in.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'"); + final String escaped = in.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'"); return sql + escaped + "'"; } @@ -1974,20 +1974,20 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getTables( - String catalog, - String schemaPattern, - String tableNamePattern, - String types[] + final String catalog, + final String schemaPattern, + final String tableNamePattern, + final String types[] ) throws SQLException { // as of Jul2015 release the sys.tables.type values (0 through 6) is extended with new values 10, 11, 20, and 30 (for system and temp tables/views). // as of Jul2015 release we also have a new table: sys.table_types with names for the new table types // for correct behavior we need to know if the server is using the old (pre Jul2015) or new sys.tables.type values - boolean preJul2015 = ("11.19.15".compareTo(getDatabaseProductVersion()) >= 0); + final boolean preJul2015 = ("11.19.15".compareTo(getDatabaseProductVersion()) >= 0); /* for debug: System.out.println("getDatabaseProductVersion() is " + getDatabaseProductVersion() + " preJul2015 is " + preJul2015); */ - boolean useCommentsTable = ((MonetConnection)con).commentsTableExists(); - StringBuilder query = new StringBuilder(1600); + final boolean useCommentsTable = ((MonetConnection)con).commentsTableExists(); + final StringBuilder query = new StringBuilder(1600); if (preJul2015 && types != null && types.length > 0) { // we need to filter on the constructed "TABLE_TYPE" expression, this is only possible when we use a subquery in the FROM query.append("SELECT * FROM ("); @@ -2083,10 +2083,10 @@ public class MonetDatabaseMetaData exten * @throws SQLException if a database error occurs */ @Override - public ResultSet getSchemas(String catalog, String schemaPattern) + public ResultSet getSchemas(final String catalog, final String schemaPattern) throws SQLException { - StringBuilder query = new StringBuilder(170); + final StringBuilder query = new StringBuilder(170); query.append("SELECT \"name\" AS \"TABLE_SCHEM\", " + "cast(null as char(1)) AS \"TABLE_CATALOG\" " + "FROM \"sys\".\"schemas\""); @@ -2144,19 +2144,18 @@ public class MonetDatabaseMetaData exten @Override public ResultSet getTableTypes() throws SQLException { // as of Jul2015 release we have a new table: sys.table_types with more table types - String query = "SELECT \"table_type_name\" AS \"TABLE_TYPE\" FROM \"sys\".\"table_types\" ORDER BY 1"; // For old (pre jul2015) servers fall back to old behavior. - boolean preJul2015 = ("11.19.15".compareTo(getDatabaseProductVersion()) >= 0); - if (preJul2015) { - query = "SELECT 'SESSION TABLE' AS \"TABLE_TYPE\" UNION ALL " + - "SELECT 'SESSION VIEW' UNION ALL " + - "SELECT 'SYSTEM SESSION TABLE' UNION ALL " + - "SELECT 'SYSTEM SESSION VIEW' UNION ALL " + - "SELECT 'SYSTEM TABLE' UNION ALL " + - "SELECT 'SYSTEM VIEW' UNION ALL " + - "SELECT 'TABLE' UNION ALL " + - "SELECT 'VIEW' ORDER BY 1"; - } + final boolean preJul2015 = ("11.19.15".compareTo(getDatabaseProductVersion()) >= 0); + final String query = preJul2015 + ? "SELECT 'SESSION TABLE' AS \"TABLE_TYPE\" UNION ALL " + + "SELECT 'SESSION VIEW' UNION ALL " + + "SELECT 'SYSTEM SESSION TABLE' UNION ALL " + + "SELECT 'SYSTEM SESSION VIEW' UNION ALL " + + "SELECT 'SYSTEM TABLE' UNION ALL " + + "SELECT 'SYSTEM VIEW' UNION ALL " + + "SELECT 'TABLE' UNION ALL " + + "SELECT 'VIEW' ORDER BY 1" + : "SELECT \"table_type_name\" AS \"TABLE_TYPE\" FROM \"sys\".\"table_types\" ORDER BY 1"; return executeMetaDataQuery(query); } @@ -2234,14 +2233,14 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getColumns( - String catalog, - String schemaPattern, - String tableNamePattern, - String columnNamePattern + final String catalog, + final String schemaPattern, + final String tableNamePattern, + final String columnNamePattern ) throws SQLException { - boolean useCommentsTable = ((MonetConnection)con).commentsTableExists(); - StringBuilder query = new StringBuilder(2450); + final boolean useCommentsTable = ((MonetConnection)con).commentsTableExists(); + final StringBuilder query = new StringBuilder(2450); query.append("SELECT cast(null as char(1)) AS \"TABLE_CAT\", " + "\"schemas\".\"name\" AS \"TABLE_SCHEM\", " + "\"tables\".\"name\" AS \"TABLE_NAME\", " + @@ -2332,14 +2331,14 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getColumnPrivileges( - String catalog, - String schemaPattern, - String tableNamePattern, - String columnNamePattern + final String catalog, + final String schemaPattern, + final String tableNamePattern, + final String columnNamePattern ) throws SQLException { - boolean usePrivilege_codesTable = ((MonetConnection)con).privilege_codesTableExists(); - StringBuilder query = new StringBuilder(1100); + final boolean usePrivilege_codesTable = ((MonetConnection)con).privilege_codesTableExists(); + final StringBuilder query = new StringBuilder(1100); query.append("SELECT cast(null as char(1)) AS \"TABLE_CAT\", " + "\"schemas\".\"name\" AS \"TABLE_SCHEM\", " + "\"tables\".\"name\" AS \"TABLE_NAME\", " + @@ -2431,13 +2430,13 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getTablePrivileges( - String catalog, - String schemaPattern, - String tableNamePattern + final String catalog, + final String schemaPattern, + final String tableNamePattern ) throws SQLException { - boolean usePrivilege_codesTable = ((MonetConnection)con).privilege_codesTableExists(); - StringBuilder query = new StringBuilder(1000); + final boolean usePrivilege_codesTable = ((MonetConnection)con).privilege_codesTableExists(); + final StringBuilder query = new StringBuilder(1000); query.append("SELECT cast(null as char(1)) AS \"TABLE_CAT\", " + "\"schemas\".\"name\" AS \"TABLE_SCHEM\", " + "\"tables\".\"name\" AS \"TABLE_NAME\", " + @@ -2530,14 +2529,14 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getBestRowIdentifier( - String catalog, - String schema, - String table, - int scope, - boolean nullable + final String catalog, + final String schema, + final String table, + final int scope, + final boolean nullable ) throws SQLException { - StringBuilder query = new StringBuilder(1500); + final StringBuilder query = new StringBuilder(1500); query.append("SELECT cast(").append(DatabaseMetaData.bestRowSession).append(" AS smallint) AS \"SCOPE\", " + "\"columns\".\"name\" AS \"COLUMN_NAME\", " + "cast(").append(MonetDriver.getSQLTypeMap("\"columns\".\"type\"")).append(" AS int) AS \"DATA_TYPE\", " + @@ -2615,13 +2614,13 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getVersionColumns( - String catalog, - String schema, - String table + final String catalog, + final String schema, + final String table ) throws SQLException { // MonetDB currently does not have columns which update themselves, so return an empty ResultSet - String query = + final String query = "SELECT cast(0 as smallint) AS \"SCOPE\", " + "cast(null as char(1)) AS \"COLUMN_NAME\", " + "cast(0 as int) AS \"DATA_TYPE\", " + @@ -2658,12 +2657,12 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getPrimaryKeys( - String catalog, - String schema, - String table + final String catalog, + final String schema, + final String table ) throws SQLException { - StringBuilder query = new StringBuilder(600); + final StringBuilder query = new StringBuilder(600); query.append("SELECT cast(null AS char(1)) AS \"TABLE_CAT\", " + "\"schemas\".\"name\" AS \"TABLE_SCHEM\", " + "\"tables\".\"name\" AS \"TABLE_NAME\", " + @@ -2793,10 +2792,13 @@ public class MonetDatabaseMetaData exten * @throws SQLException if a database error occurs */ @Override - public ResultSet getImportedKeys(String catalog, String schema, String table) - throws SQLException + public ResultSet getImportedKeys( + final String catalog, + final String schema, + final String table + ) throws SQLException { - StringBuilder query = new StringBuilder(keyQuery.length() + 250); + final StringBuilder query = new StringBuilder(keyQuery.length() + 250); query.append(keyQuery); if (catalog != null && !catalog.isEmpty()) { @@ -2878,10 +2880,13 @@ public class MonetDatabaseMetaData exten * @throws SQLException if a database error occurs */ @Override - public ResultSet getExportedKeys(String catalog, String schema, String table) - throws SQLException + public ResultSet getExportedKeys( + final String catalog, + final String schema, + final String table + ) throws SQLException { - StringBuilder query = new StringBuilder(keyQuery.length() + 250); + final StringBuilder query = new StringBuilder(keyQuery.length() + 250); query.append(keyQuery); if (catalog != null && !catalog.isEmpty()) { @@ -2971,15 +2976,15 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getCrossReference( - String pcatalog, - String pschema, - String ptable, - String fcatalog, - String fschema, - String ftable + final String pcatalog, + final String pschema, + final String ptable, + final String fcatalog, + final String fschema, + final String ftable ) throws SQLException { - StringBuilder query = new StringBuilder(keyQuery.length() + 350); + final StringBuilder query = new StringBuilder(keyQuery.length() + 350); query.append(keyQuery); if ((pcatalog != null && !pcatalog.isEmpty()) @@ -3061,7 +3066,7 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getTypeInfo() throws SQLException { - StringBuilder query = new StringBuilder(2300); + final StringBuilder query = new StringBuilder(2300); query.append("SELECT \"sqlname\" AS \"TYPE_NAME\", " + "cast(").append(MonetDriver.getSQLTypeMap("\"sqlname\"")).append(" AS int) AS \"DATA_TYPE\", " + "\"digits\" AS \"PRECISION\", " + // note that when radix is 2 the precision shows the number of bits @@ -3148,11 +3153,11 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getIndexInfo( - String catalog, - String schema, - String table, - boolean unique, - boolean approximate + final String catalog, + final String schema, + final String table, + final boolean unique, + final boolean approximate ) throws SQLException { String table_row_count = "0"; @@ -3178,7 +3183,7 @@ public class MonetDatabaseMetaData exten } } - StringBuilder query = new StringBuilder(1250); + final StringBuilder query = new StringBuilder(1250); query.append( "SELECT cast(null AS char(1)) AS \"TABLE_CAT\", " + "\"schemas\".\"name\" AS \"TABLE_SCHEM\", " + @@ -3236,7 +3241,7 @@ public class MonetDatabaseMetaData exten * @throws SQLException - if a database access error occurs */ @Override - public boolean supportsResultSetType(int type) throws SQLException { + public boolean supportsResultSetType(final int type) throws SQLException { // The only type we don't support return type != ResultSet.TYPE_SCROLL_SENSITIVE; } @@ -3252,7 +3257,7 @@ public class MonetDatabaseMetaData exten * @throws SQLException - if a database access error occurs */ @Override - public boolean supportsResultSetConcurrency(int type, int concurrency) + public boolean supportsResultSetConcurrency(final int type, final int concurrency) throws SQLException { // These combinations are not supported! @@ -3270,47 +3275,47 @@ public class MonetDatabaseMetaData exten /* lots of unsupported stuff... (no updatable ResultSet!) */ @Override - public boolean ownUpdatesAreVisible(int type) { + public boolean ownUpdatesAreVisible(final int type) { return false; } @Override - public boolean ownDeletesAreVisible(int type) { + public boolean ownDeletesAreVisible(final int type) { return false; } @Override - public boolean ownInsertsAreVisible(int type) { + public boolean ownInsertsAreVisible(final int type) { return false; } @Override - public boolean othersUpdatesAreVisible(int type) { + public boolean othersUpdatesAreVisible(final int type) { return false; } @Override - public boolean othersDeletesAreVisible(int i) { + public boolean othersDeletesAreVisible(final int i) { return false; } @Override - public boolean othersInsertsAreVisible(int type) { + public boolean othersInsertsAreVisible(final int type) { return false; } @Override - public boolean updatesAreDetected(int type) { + public boolean updatesAreDetected(final int type) { return false; } @Override - public boolean deletesAreDetected(int i) { + public boolean deletesAreDetected(final int i) { return false; } @Override - public boolean insertsAreDetected(int type) { + public boolean insertsAreDetected(final int type) { return false; } @@ -3345,13 +3350,13 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getUDTs( - String catalog, - String schemaPattern, - String typeNamePattern, - int[] types + final String catalog, + final String schemaPattern, + final String typeNamePattern, + final int[] types ) throws SQLException { - StringBuilder query = new StringBuilder(990); + final StringBuilder query = new StringBuilder(990); if (types != null && types.length > 0) { query.append("SELECT * FROM ("); } @@ -3414,11 +3419,11 @@ public class MonetDatabaseMetaData exten } /* I don't find these in the spec!?! */ - public boolean rowChangesAreDetected(int type) { + public boolean rowChangesAreDetected(final int type) { return false; } - public boolean rowChangesAreVisible(int type) { + public boolean rowChangesAreVisible(final int type) { return false; } @@ -3512,12 +3517,12 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getSuperTypes( - String catalog, - String schemaPattern, - String typeNamePattern + final String catalog, + final String schemaPattern, + final String typeNamePattern ) throws SQLException { - String query = + final String query = "SELECT cast(null as char(1)) AS \"TYPE_CAT\", '' AS \"TYPE_SCHEM\", '' AS \"TYPE_NAME\", " + "cast(null as char(1)) AS \"SUPERTYPE_CAT\", '' AS \"SUPERTYPE_SCHEM\", '' AS \"SUPERTYPE_NAME\" " + "WHERE 1 = 0"; @@ -3557,12 +3562,12 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getSuperTables( - String catalog, - String schemaPattern, - String tableNamePattern + final String catalog, + final String schemaPattern, + final String tableNamePattern ) throws SQLException { - String query = + final String query = "SELECT cast(null as char(1)) AS \"TABLE_CAT\", " + "'' AS \"TABLE_SCHEM\", '' AS \"TABLE_NAME\", '' AS \"SUPERTABLE_NAME\" " + "WHERE 1 = 0"; @@ -3641,13 +3646,13 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getAttributes( - String catalog, - String schemaPattern, - String typeNamePattern, - String attributeNamePattern + final String catalog, + final String schemaPattern, + final String typeNamePattern, + final String attributeNamePattern ) throws SQLException { - String query = + final String query = "SELECT cast(null as char(1)) AS \"TYPE_CAT\", '' AS \"TYPE_SCHEM\", '' AS \"TYPE_NAME\", " + "'' AS \"ATTR_NAME\", cast(0 as int) AS \"DATA_TYPE\", '' AS \"ATTR_TYPE_NAME\", cast(0 as int) AS \"ATTR_SIZE\", " + "cast(0 as int) AS \"DECIMAL_DIGITS\", cast(0 as int) AS \"NUM_PREC_RADIX\", cast(0 as int) AS \"NULLABLE\", " + @@ -3671,7 +3676,7 @@ public class MonetDatabaseMetaData exten * @see Connection */ @Override - public boolean supportsResultSetHoldability(int holdability) { + public boolean supportsResultSetHoldability(final int holdability) { // we don't close ResultSets at commit; and we don't do updateable // result sets, so comes closest to hold cursors over commit return holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT; @@ -3881,7 +3886,7 @@ public class MonetDatabaseMetaData exten @Override public ResultSet getClientInfoProperties() throws SQLException { // for a list of connection properties see also MonetConnection.java constructor MonetConnection(Properties props) - String query = + final String query = "SELECT 'host' AS \"NAME\", cast(1024 as int) AS \"MAX_LEN\", 'localhost' AS \"DEFAULT_VALUE\", 'DSN or IP-address of machine running MonetDB' AS \"DESCRIPTION\" UNION ALL " + "SELECT 'port', 5, '50000', 'communication port number of MonetDB server process' UNION ALL " + "SELECT 'user', 1024, '', 'user name to login to MonetDB server' UNION ALL " + @@ -3943,13 +3948,13 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getFunctions( - String catalog, - String schemaPattern, - String functionNamePattern) - throws SQLException + final String catalog, + final String schemaPattern, + final String functionNamePattern + ) throws SQLException { - boolean useCommentsTable = ((MonetConnection)con).commentsTableExists(); - StringBuilder query = new StringBuilder(800); + final boolean useCommentsTable = ((MonetConnection)con).commentsTableExists(); + final StringBuilder query = new StringBuilder(800); query.append("SELECT cast(null as char(1)) AS \"FUNCTION_CAT\", " + "\"schemas\".\"name\" AS \"FUNCTION_SCHEM\", " + "\"functions\".\"name\" AS \"FUNCTION_NAME\", ") @@ -4051,13 +4056,13 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getFunctionColumns( - String catalog, - String schemaPattern, - String functionNamePattern, - String columnNamePattern) - throws SQLException + final String catalog, + final String schemaPattern, + final String functionNamePattern, + final String columnNamePattern + ) throws SQLException { - StringBuilder query = new StringBuilder(2600); + final StringBuilder query = new StringBuilder(2600); query.append("SELECT cast(null as char(1)) AS \"FUNCTION_CAT\", " + "\"schemas\".\"name\" AS \"FUNCTION_SCHEM\", " + "\"functions\".\"name\" AS \"FUNCTION_NAME\", " + @@ -4152,14 +4157,14 @@ public class MonetDatabaseMetaData exten */ @Override public ResultSet getPseudoColumns( - String catalog, - String schemaPattern, - String tableNamePattern, - String columnNamePattern) - throws SQLException + final String catalog, + final String schemaPattern, + final String tableNamePattern, + final String columnNamePattern + ) throws SQLException { // MonetDB currently does not support pseudo or hidden columns, so return an empty ResultSet - String query = + final String query = "SELECT cast(null as char(1)) AS \"TABLE_CAT\", " + "'' AS \"TABLE_SCHEM\", " + "'' AS \"TABLE_NAME\", " +
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java.in +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java.in @@ -9,20 +9,15 @@ package nl.cwi.monetdb.jdbc; import java.net.URI; -import java.net.URISyntaxException; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; -import java.sql.SQLNonTransientConnectionException; import java.sql.Types; -import java.util.ArrayList; -import java.util.List; import java.util.Map.Entry; import java.util.Properties; -import java.util.logging.Logger; /** * A Driver suitable for the MonetDB database. @@ -56,9 +51,6 @@ final public class MonetDriver implement /** Version suffix string */ private static final String DRIVERVERSIONSUFFIX = "@JDBC_VER_SUFFIX@ based on MCL v@MCL_MAJOR@.@MCL_MINOR@"; - // We're not fully compliant, but what we support is compliant - /** Whether this driver is JDBC compliant or not */ - private static final boolean MONETJDBCCOMPLIANT = false; /** MonetDB default port to connect to */ private static final String PORT = "@JDBC_DEF_PORT@"; @@ -85,7 +77,7 @@ final public class MonetDriver implement * @return true if this driver understands the given URL; false otherwise */ @Override - public boolean acceptsURL(String url) { + public boolean acceptsURL(final String url) { return url != null && url.startsWith(MONETURL); } @@ -111,14 +103,14 @@ final public class MonetDriver implement * @throws SQLException if a database access error occurs */ @Override - public Connection connect(String url, Properties info) + public Connection connect(final String url, Properties info) throws SQLException { // url should be of style jdbc:monetdb://<host>/<database> if (!acceptsURL(url)) return null; - Properties props = new Properties(); + final Properties props = new Properties(); // set the optional properties and their defaults here props.put("port", PORT); props.put("debug", "false"); @@ -130,14 +122,14 @@ final public class MonetDriver implement info = props; // remove leading "jdbc:" so the rest is a valid hierarchical URI - URI uri; + final URI uri; try { uri = new URI(url.substring(5)); - } catch (URISyntaxException e) { + } catch (java.net.URISyntaxException e) { return null; } - String uri_host = uri.getHost(); + final String uri_host = uri.getHost(); if (uri_host == null) return null; info.put("host", uri_host); @@ -154,11 +146,11 @@ final public class MonetDriver implement info.put("database", uri_path); } - String uri_query = uri.getQuery(); + final String uri_query = uri.getQuery(); if (uri_query != null) { int pos; // handle additional connection properties separated by the & character - String args[] = uri_query.split("&"); + final String args[] = uri_query.split("&"); for (int i = 0; i < args.length; i++) { pos = args[i].indexOf('='); if (pos > 0) @@ -208,14 +200,14 @@ final public class MonetDriver implement * are required. */ @Override - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { + public DriverPropertyInfo[] getPropertyInfo(final String url, final Properties info) { if (!acceptsURL(url)) return null; - String[] boolean_choices = new String[] { "true", "false" }; - String[] language_choices = new String[] { "sql", "mal" }; - String[] hash_choices = new String[] { "SHA512", "SHA384", "SHA256", "SHA1", "MD5" }; - DriverPropertyInfo[] dpi = new DriverPropertyInfo[9]; // we currently support 9 connection properties + final String[] boolean_choices = new String[] { "true", "false" }; + final String[] language_choices = new String[] { "sql", "mal" }; + final String[] hash_choices = new String[] { "SHA512", "SHA384", "SHA256", "SHA1", "MD5" }; + final DriverPropertyInfo[] dpi = new DriverPropertyInfo[9]; // we currently support 9 connection properties DriverPropertyInfo prop = new DriverPropertyInfo("user", info != null ? info.getProperty("user") : null); prop.required = true; @@ -298,7 +290,8 @@ final public class MonetDriver implement */ @Override public boolean jdbcCompliant() { - return MONETJDBCCOMPLIANT; + // We're not fully JDBC compliant, but what we support is compliant + return false; } /** @@ -315,7 +308,7 @@ final public class MonetDriver implement * @since 1.7 */ @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException { + public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw MonetWrapper.newSQLFeatureNotSupportedException("getParentLogger"); } @@ -325,7 +318,7 @@ final public class MonetDriver implement /** A static Map containing the mapping between MonetDB types and Java SQL types */ /* use SELECT sqlname, * FROM sys.types order by 1, id; to view all MonetDB types */ /* see http://docs.oracle.com/javase/7/docs/api/java/sql/Types.html to view all supported java SQL types */ - private static java.util.Map<String, Integer> typeMap = new java.util.HashMap<String, Integer>(); + private static final java.util.Map<String, Integer> typeMap = new java.util.HashMap<String, Integer>(); static { // fill the typeMap once // typeMap.put("any", Integer.valueOf(Types.???)); @@ -371,9 +364,9 @@ final public class MonetDriver implement * @return the matching java.sql.Types constant or * java.sql.Types.OTHER if nothing matched the given type name */ - static int getJdbcSQLType(String type) { + static final int getJdbcSQLType(final String type) { // find the column type name in the typeMap - Integer tp = typeMap.get(type); + final Integer tp = typeMap.get(type); if (tp != null) { return tp.intValue(); } @@ -394,10 +387,10 @@ final public class MonetDriver implement * @return a SQL CASE statement */ private static String TypeMapppingSQL = null; // cache to optimise getSQLTypeMap() - static String getSQLTypeMap(String column) { + static final String getSQLTypeMap(final String column) { if (TypeMapppingSQL == null) { // first time, compose TypeMappping SQL string - StringBuilder val = new StringBuilder((typeMap.size() * (7 + 7 + 7 + 4)) + 14); + final StringBuilder val = new StringBuilder((typeMap.size() * (7 + 7 + 7 + 4)) + 14); for (Entry<String, Integer> entry : typeMap.entrySet()) { val.append(" WHEN '").append(entry.getKey()).append("' THEN ").append(entry.getValue().toString()); } @@ -410,18 +403,18 @@ final public class MonetDriver implement /** * Returns a touched up identifying version string of this driver. - * + * It is made public as it is called from nl/cwi/monetdb/client/JdbcClient.java * @return the version string */ - public static String getDriverVersion() { + public static final String getDriverVersion() { return DRIVERMAJOR + "." + DRIVERMINOR + " (" + DRIVERVERSIONSUFFIX + ")"; } - static int getDriverMajorVersion() { + static final int getDriverMajorVersion() { return DRIVERMAJOR; } - static int getDriverMinorVersion() { + static final int getDriverMinorVersion() { return DRIVERMINOR; } }
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetPreparedStatement.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetPreparedStatement.java @@ -9,11 +9,10 @@ package nl.cwi.monetdb.jdbc; import java.io.InputStream; +import java.io.IOException; import java.io.Reader; -import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; -import java.math.RoundingMode; import java.net.URL; import java.nio.CharBuffer; import java.sql.Array; @@ -107,11 +106,11 @@ public class MonetPreparedStatement * @throws IllegalArgumentException is one of the arguments is null or empty */ MonetPreparedStatement( - MonetConnection connection, - int resultSetType, - int resultSetConcurrency, - int resultSetHoldability, - String prepareQuery) + final MonetConnection connection, + final int resultSetType, + final int resultSetConcurrency, + final int resultSetHoldability, + final String prepareQuery) throws SQLException, IllegalArgumentException { super( @@ -140,15 +139,15 @@ public class MonetPreparedStatement values = new String[size]; // fill the arrays - ResultSet rs = super.getResultSet(); + final ResultSet rs = super.getResultSet(); if (rs != null) { // System.out.println("After super.getResultSet();"); - int type_colnr = rs.findColumn("type"); - int digits_colnr = rs.findColumn("digits"); - int scale_colnr = rs.findColumn("scale"); - int schema_colnr = rs.findColumn("schema"); - int table_colnr = rs.findColumn("table"); - int column_colnr = rs.findColumn("column"); + final int type_colnr = rs.findColumn("type"); + final int digits_colnr = rs.findColumn("digits"); + final int scale_colnr = rs.findColumn("scale"); + final int schema_colnr = rs.findColumn("schema"); + final int table_colnr = rs.findColumn("table"); + final int column_colnr = rs.findColumn("column"); for (int i = 0; rs.next(); i++) { monetdbType[i] = rs.getString(type_colnr); javaType[i] = MonetDriver.getJdbcSQLType(monetdbType[i]); @@ -232,7 +231,7 @@ public class MonetPreparedStatement /** override the addBatch from the Statement to throw an SQLException */ @Override - public void addBatch(String q) throws SQLException { + public void addBatch(final String q) throws SQLException { throw new SQLException("This method is not available in a PreparedStatement!", "M1M05"); } @@ -276,7 +275,7 @@ public class MonetPreparedStatement /** override the execute from the Statement to throw an SQLException */ @Override - public boolean execute(String q) throws SQLException { + public boolean execute(final String q) throws SQLException { throw new SQLException("This method is not available in a PreparedStatement!", "M1M05"); } @@ -297,9 +296,9 @@ public class MonetPreparedStatement return getResultSet(); } - /** override the executeQuery from the Statement to throw an SQLException*/ + /** override the executeQuery from the Statement to throw an SQLException */ @Override - public ResultSet executeQuery(String q) throws SQLException { + public ResultSet executeQuery(final String q) throws SQLException { throw new SQLException("This method is not available in a PreparedStatement!", "M1M05"); } @@ -321,9 +320,9 @@ public class MonetPreparedStatement return getUpdateCount(); } - /** override the executeUpdate from the Statement to throw an SQLException*/ + /** override the executeUpdate from the Statement to throw an SQLException */ @Override - public int executeUpdate(String q) throws SQLException { + public int executeUpdate(final String q) throws SQLException { throw new SQLException("This method is not available in a PreparedStatement!", "M1M05"); } @@ -331,7 +330,7 @@ public class MonetPreparedStatement * Returns the index (0..size-1) in the backing arrays for the given * resultset column number or an SQLException when not found */ - private int getColumnIdx(int colnr) throws SQLException { + private final int getColumnIdx(final int colnr) throws SQLException { int curcol = 0; for (int i = 0; i < size; i++) { /* when column[i] == null it is a parameter, when column[i] != null it is a result column of the prepared query */ @@ -347,7 +346,7 @@ public class MonetPreparedStatement * Returns the index (0..size-1) in the backing arrays for the given * parameter number or an SQLException when not found */ - private int getParamIdx(int paramnr) throws SQLException { + private final int getParamIdx(final int paramnr) throws SQLException { int curparam = 0; for (int i = 0; i < size; i++) { /* when column[i] == null it is a parameter, when column[i] != null it is a result column of the prepared query */ @@ -410,7 +409,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public boolean isAutoIncrement(int column) throws SQLException { + public boolean isAutoIncrement(final int column) throws SQLException { /* TODO: in MonetDB only numeric (int, decimal) columns could be autoincrement/serial * This however requires an expensive dbmd.getColumns(null, schema, table, column) * query call to pull the IS_AUTOINCREMENT value for this column. @@ -427,14 +426,14 @@ public class MonetPreparedStatement * @return false */ @Override - public boolean isCaseSensitive(int column) throws SQLException { + public boolean isCaseSensitive(final int column) throws SQLException { switch (getColumnType(column)) { case Types.CHAR: case Types.LONGVARCHAR: // MonetDB doesn't use type LONGVARCHAR, it's here for completeness case Types.CLOB: return true; case Types.VARCHAR: - String monettype = getColumnTypeName(column); + final String monettype = getColumnTypeName(column); if (monettype != null) { // data of type inet or uuid is not case sensitive if ("inet".equals(monettype) @@ -457,7 +456,7 @@ public class MonetPreparedStatement * @return true */ @Override - public boolean isSearchable(int column) { + public boolean isSearchable(final int column) { return true; } @@ -472,7 +471,7 @@ public class MonetPreparedStatement * @return false */ @Override - public boolean isCurrency(int column) { + public boolean isCurrency(final int column) { return false; } @@ -485,7 +484,7 @@ public class MonetPreparedStatement * @return true if so; false otherwise */ @Override - public boolean isSigned(int column) throws SQLException { + public boolean isSigned(final int column) throws SQLException { // we can hardcode this, based on the colum type switch (getColumnType(column)) { case Types.NUMERIC: @@ -498,7 +497,7 @@ public class MonetPreparedStatement case Types.DOUBLE: return true; case Types.BIGINT: - String monettype = getColumnTypeName(column); + final String monettype = getColumnTypeName(column); if (monettype != null) { if ("oid".equals(monettype) || "ptr".equals(monettype)) @@ -525,7 +524,7 @@ public class MonetPreparedStatement * @throws SQLException if there is no such column */ @Override - public int getColumnDisplaySize(int column) throws SQLException { + public int getColumnDisplaySize(final int column) throws SQLException { try { return digits[getColumnIdx(column)]; } catch (IndexOutOfBoundsException e) { @@ -541,7 +540,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public String getSchemaName(int column) throws SQLException { + public String getSchemaName(final int column) throws SQLException { try { return schema[getColumnIdx(column)]; } catch (IndexOutOfBoundsException e) { @@ -556,7 +555,7 @@ public class MonetPreparedStatement * @return table name or "" if not applicable */ @Override - public String getTableName(int column) throws SQLException { + public String getTableName(final int column) throws SQLException { try { return table[getColumnIdx(column)]; } catch (IndexOutOfBoundsException e) { @@ -575,7 +574,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public int getPrecision(int column) throws SQLException { + public int getPrecision(final int column) throws SQLException { try { return digits[getColumnIdx(column)]; } catch (IndexOutOfBoundsException e) { @@ -594,7 +593,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public int getScale(int column) throws SQLException { + public int getScale(final int column) throws SQLException { try { return scale[getColumnIdx(column)]; } catch (IndexOutOfBoundsException e) { @@ -613,7 +612,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public int isNullable(int column) throws SQLException { + public int isNullable(final int column) throws SQLException { return columnNullableUnknown; } @@ -626,7 +625,7 @@ public class MonetPreparedStatement * column appears or "" if not applicable */ @Override - public String getCatalogName(int column) throws SQLException { + public String getCatalogName(final int column) throws SQLException { return null; // MonetDB does NOT support catalogs } @@ -639,7 +638,7 @@ public class MonetPreparedStatement * @return true if so; false otherwise */ @Override - public boolean isReadOnly(int column) { + public boolean isReadOnly(final int column) { return true; } @@ -651,7 +650,7 @@ public class MonetPreparedStatement * @return true if so; false otherwise */ @Override - public boolean isWritable(int column) { + public boolean isWritable(final int column) { return false; } @@ -663,7 +662,7 @@ public class MonetPreparedStatement * @return true if so; false otherwise */ @Override - public boolean isDefinitelyWritable(int column) { + public boolean isDefinitelyWritable(final int column) { return false; } @@ -683,10 +682,10 @@ public class MonetPreparedStatement * @throws SQLException if there is no such column */ @Override - public String getColumnClassName(int column) throws SQLException { - String typeName = getColumnTypeName(column); - Map<String,Class<?>> map = getConnection().getTypeMap(); - Class<?> c; + public String getColumnClassName(final int column) throws SQLException { + final String typeName = getColumnTypeName(column); + final Map<String,Class<?>> map = getConnection().getTypeMap(); + final Class<?> c; if (map.containsKey(typeName)) { c = (Class)map.get(typeName); } else { @@ -705,7 +704,7 @@ public class MonetPreparedStatement * @throws SQLException if there is no such column */ @Override - public String getColumnLabel(int column) throws SQLException { + public String getColumnLabel(final int column) throws SQLException { return getColumnName(column); } @@ -717,7 +716,7 @@ public class MonetPreparedStatement * @throws SQLException if there is no such column */ @Override - public String getColumnName(int colnr) throws SQLException { + public String getColumnName(final int colnr) throws SQLException { try { return column[getColumnIdx(colnr)]; } catch (IndexOutOfBoundsException e) { @@ -733,7 +732,7 @@ public class MonetPreparedStatement * @throws SQLException if there is no such column */ @Override - public int getColumnType(int column) throws SQLException { + public int getColumnType(final int column) throws SQLException { try { return javaType[getColumnIdx(column)]; } catch (IndexOutOfBoundsException e) { @@ -751,7 +750,7 @@ public class MonetPreparedStatement * @throws SQLException if there is no such column */ @Override - public String getColumnTypeName(int column) throws SQLException { + public String getColumnTypeName(final int column) throws SQLException { try { return monetdbType[getColumnIdx(column)]; } catch (IndexOutOfBoundsException e) { @@ -808,7 +807,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public int isNullable(int param) throws SQLException { + public int isNullable(final int param) throws SQLException { return ParameterMetaData.parameterNullableUnknown; } @@ -821,7 +820,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public boolean isSigned(int param) throws SQLException { + public boolean isSigned(final int param) throws SQLException { // we can hardcode this, based on the colum type switch (getParameterType(param)) { case Types.NUMERIC: @@ -834,7 +833,7 @@ public class MonetPreparedStatement case Types.DOUBLE: return true; case Types.BIGINT: - String monettype = getParameterTypeName(param); + final String monettype = getParameterTypeName(param); if (monettype != null) { if ("oid".equals(monettype) || "ptr".equals(monettype)) @@ -860,7 +859,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public int getPrecision(int param) throws SQLException { + public int getPrecision(final int param) throws SQLException { try { return digits[getParamIdx(param)]; } catch (IndexOutOfBoundsException e) { @@ -877,7 +876,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public int getScale(int param) throws SQLException { + public int getScale(final int param) throws SQLException { try { return scale[getParamIdx(param)]; } catch (IndexOutOfBoundsException e) { @@ -893,7 +892,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public int getParameterType(int param) throws SQLException { + public int getParameterType(final int param) throws SQLException { try { return javaType[getParamIdx(param)]; } catch (IndexOutOfBoundsException e) { @@ -912,7 +911,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public String getParameterTypeName(int param) throws SQLException { + public String getParameterTypeName(final int param) throws SQLException { try { return monetdbType[getParamIdx(param)]; } catch (IndexOutOfBoundsException e) { @@ -934,10 +933,10 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public String getParameterClassName(int param) throws SQLException { - String typeName = getParameterTypeName(param); - Map<String,Class<?>> map = getConnection().getTypeMap(); - Class<?> c; + public String getParameterClassName(final int param) throws SQLException { + final String typeName = getParameterTypeName(param); + final Map<String,Class<?>> map = getConnection().getTypeMap(); + final Class<?> c; if (map.containsKey(typeName)) { c = (Class)map.get(typeName); } else { @@ -959,7 +958,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public int getParameterMode(int param) throws SQLException { + public int getParameterMode(final int param) throws SQLException { return ParameterMetaData.parameterModeIn; } }; @@ -977,7 +976,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setArray(int parameterIndex, Array x) throws SQLException { + public void setArray(final int parameterIndex, final Array x) throws SQLException { throw newSQLFeatureNotSupportedException("setArray"); } @@ -999,7 +998,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setAsciiStream(int parameterIndex, InputStream x) + public void setAsciiStream(final int parameterIndex, final InputStream x) throws SQLException { throw newSQLFeatureNotSupportedException("setAsciiStream"); @@ -1024,7 +1023,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setAsciiStream(int parameterIndex, InputStream x, int length) + public void setAsciiStream(final int parameterIndex, final InputStream x, final int length) throws SQLException { throw newSQLFeatureNotSupportedException("setAsciiStream"); @@ -1050,7 +1049,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setAsciiStream(int parameterIndex, InputStream x, long length) + public void setAsciiStream(final int parameterIndex, final InputStream x, final long length) throws SQLException { throw newSQLFeatureNotSupportedException("setAsciiStream"); @@ -1066,12 +1065,12 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { + public void setBigDecimal(final int parameterIndex, BigDecimal x) throws SQLException { // get array position - int i = getParamIdx(parameterIndex); + final int i = getParamIdx(parameterIndex); // round to the scale of the DB: - x = x.setScale(scale[i], RoundingMode.HALF_UP); + x = x.setScale(scale[i], java.math.RoundingMode.HALF_UP); // if precision is now greater than that of the db, throw an error: if (x.precision() > digits[i]) { @@ -1083,7 +1082,7 @@ public class MonetPreparedStatement // this to the exact number "0".) Also strip off trailing // numbers that are inherent to the double representation. String xStr = x.toPlainString(); - int dot = xStr.indexOf('.'); + final int dot = xStr.indexOf('.'); if (dot >= 0) xStr = xStr.substring(0, Math.min(xStr.length(), dot + 1 + scale[i])); while (xStr.startsWith("0") && xStr.length() > 1) @@ -1108,7 +1107,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setBinaryStream(int parameterIndex, InputStream x) + public void setBinaryStream(final int parameterIndex, final InputStream x) throws SQLException { throw newSQLFeatureNotSupportedException("setBinaryStream"); @@ -1132,7 +1131,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setBinaryStream(int parameterIndex, InputStream x, int length) + public void setBinaryStream(final int parameterIndex, final InputStream x, final int length) throws SQLException { throw newSQLFeatureNotSupportedException("setBinaryStream"); @@ -1156,7 +1155,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setBinaryStream(int parameterIndex, InputStream x, long length) + public void setBinaryStream(final int parameterIndex, final InputStream x, final long length) throws SQLException { throw newSQLFeatureNotSupportedException("setBinaryStream"); @@ -1173,7 +1172,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setBlob(int parameterIndex, InputStream x) throws SQLException { + public void setBlob(final int parameterIndex, final InputStream x) throws SQLException { throw newSQLFeatureNotSupportedException("setBlob"); } @@ -1188,7 +1187,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setBlob(int parameterIndex, Blob x) throws SQLException { + public void setBlob(final int parameterIndex, final Blob x) throws SQLException { throw newSQLFeatureNotSupportedException("setBlob"); } @@ -1212,7 +1211,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setBlob(int parameterIndex, InputStream is, long length) throws SQLException { + public void setBlob(final int parameterIndex, final InputStream is, final long length) throws SQLException { throw newSQLFeatureNotSupportedException("setBlob"); } @@ -1226,7 +1225,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setBoolean(int parameterIndex, boolean x) throws SQLException { + public void setBoolean(final int parameterIndex, final boolean x) throws SQLException { setValue(parameterIndex, Boolean.toString(x)); } @@ -1239,7 +1238,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setByte(int parameterIndex, byte x) throws SQLException { + public void setByte(final int parameterIndex, final byte x) throws SQLException { setValue(parameterIndex, Byte.toString(x)); } @@ -1255,13 +1254,13 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setBytes(int parameterIndex, byte[] x) throws SQLException { + public void setBytes(final int parameterIndex, final byte[] x) throws SQLException { if (x == null) { setNull(parameterIndex, -1); return; } - StringBuilder hex = new StringBuilder(x.length * 2); + final StringBuilder hex = new StringBuilder(x.length * 2); byte b; for (int i = 0; i < x.length; i++) { b = x[i]; @@ -1289,9 +1288,9 @@ public class MonetPreparedStatement */ @Override public void setCharacterStream( - int parameterIndex, - Reader reader, - int length) + final int parameterIndex, + final Reader reader, + final int length) throws SQLException { if (reader == null) { @@ -1299,7 +1298,7 @@ public class MonetPreparedStatement return; } - CharBuffer tmp = CharBuffer.allocate(length); + final CharBuffer tmp = CharBuffer.allocate(length); try { reader.read(tmp); } catch (IOException e) { @@ -1324,7 +1323,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setCharacterStream(int parameterIndex, Reader reader) + public void setCharacterStream(final int parameterIndex, final Reader reader) throws SQLException { setCharacterStream(parameterIndex, reader, 0); @@ -1348,9 +1347,9 @@ public class MonetPreparedStatement */ @Override public void setCharacterStream( - int parameterIndex, - Reader reader, - long length) + final int parameterIndex, + final Reader reader, + final long length) throws SQLException { // given the implementation of the int-version, downcast is ok @@ -1366,7 +1365,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setClob(int parameterIndex, Clob x) throws SQLException { + public void setClob(final int parameterIndex, final Clob x) throws SQLException { if (x == null) { setNull(parameterIndex, -1); return; @@ -1388,14 +1387,14 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setClob(int parameterIndex, Reader reader) throws SQLException { + public void setClob(final int parameterIndex, final Reader reader) throws SQLException { if (reader == null) { setNull(parameterIndex, -1); return; } // Some buffer. Size of 8192 is default for BufferedReader, so... - char[] arr = new char[8192]; - StringBuilder buf = new StringBuilder(8192 * 8); + final char[] arr = new char[8192]; + final StringBuilder buf = new StringBuilder(8192 * 8); int numChars; try { while ((numChars = reader.read(arr, 0, arr.length)) > 0) { @@ -1425,14 +1424,14 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { + public void setClob(final int parameterIndex, final Reader reader, final long length) throws SQLException { if (reader == null || length < 0) { setNull(parameterIndex, -1); return; } // simply serialise the CLOB into a variable for now... far from // efficient, but might work for a few cases... - CharBuffer buf = CharBuffer.allocate((int)length); // have to down cast :( + final CharBuffer buf = CharBuffer.allocate((int)length); // have to down cast :( try { reader.read(buf); } catch (IOException e) { @@ -1454,7 +1453,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setDate(int parameterIndex, java.sql.Date x) + public void setDate(final int parameterIndex, final java.sql.Date x) throws SQLException { setDate(parameterIndex, x, null); @@ -1475,7 +1474,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) + public void setDate(final int parameterIndex, final java.sql.Date x, final Calendar cal) throws SQLException { if (x == null) { @@ -1504,7 +1503,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setDouble(int parameterIndex, double x) throws SQLException { + public void setDouble(final int parameterIndex, final double x) throws SQLException { setValue(parameterIndex, Double.toString(x)); } @@ -1517,7 +1516,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setFloat(int parameterIndex, float x) throws SQLException { + public void setFloat(final int parameterIndex, final float x) throws SQLException { setValue(parameterIndex, Float.toString(x)); } @@ -1530,7 +1529,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setInt(int parameterIndex, int x) throws SQLException { + public void setInt(final int parameterIndex, final int x) throws SQLException { setValue(parameterIndex, Integer.toString(x)); } @@ -1543,7 +1542,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setLong(int parameterIndex, long x) throws SQLException { + public void setLong(final int parameterIndex, final long x) throws SQLException { setValue(parameterIndex, Long.toString(x)); } @@ -1558,7 +1557,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { + public void setNCharacterStream(final int parameterIndex, final Reader value) throws SQLException { setCharacterStream(parameterIndex, value, 0); } @@ -1574,7 +1573,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setNCharacterStream(int parameterIndex, Reader value, long length) + public void setNCharacterStream(final int parameterIndex, final Reader value, final long length) throws SQLException { setCharacterStream(parameterIndex, value, length); @@ -1592,7 +1591,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setNClob(int parameterIndex, Reader value) throws SQLException { + public void setNClob(final int parameterIndex, final Reader value) throws SQLException { throw newSQLFeatureNotSupportedException("setNClob"); } @@ -1608,7 +1607,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setNClob(int parameterIndex, NClob value) throws SQLException { + public void setNClob(final int parameterIndex, final NClob value) throws SQLException { throw newSQLFeatureNotSupportedException("setNClob"); } @@ -1632,7 +1631,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setNClob(int parameterIndex, Reader r, long length) throws SQLException { + public void setNClob(final int parameterIndex, final Reader r, final long length) throws SQLException { throw newSQLFeatureNotSupportedException("setNClob"); } @@ -1647,7 +1646,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setNString(int parameterIndex, String value) throws SQLException { + public void setNString(final int parameterIndex, final String value) throws SQLException { setString(parameterIndex, value); } @@ -1661,7 +1660,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setNull(int parameterIndex, int sqlType) throws SQLException { + public void setNull(final int parameterIndex, final int sqlType) throws SQLException { // we discard the given type here, the backend converts the // value NULL to whatever it needs for the column setValue(parameterIndex, "NULL"); @@ -1691,7 +1690,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setNull(int parameterIndex, int sqlType, String typeName) + public void setNull(final int parameterIndex, final int sqlType, final String typeName) throws SQLException { // MonetDB/SQL's NULL needs no type @@ -1726,7 +1725,7 @@ public class MonetPreparedStatement * the given object is ambiguous */ @Override - public void setObject(int parameterIndex, Object x) throws SQLException { + public void setObject(final int parameterIndex, final Object x) throws SQLException { setObject(parameterIndex, x, javaType[getParamIdx(parameterIndex)], 0); } @@ -1742,7 +1741,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setObject(int parameterIndex, Object x, int targetSqlType) + public void setObject(final int parameterIndex, final Object x, final int targetSqlType) throws SQLException { setObject(parameterIndex, x, targetSqlType, 0); @@ -1785,10 +1784,10 @@ public class MonetPreparedStatement */ @Override public void setObject( - int parameterIndex, - Object x, - int targetSqlType, - int scale) + final int parameterIndex, + final Object x, + final int targetSqlType, + final int scale) throws SQLException { if (x == null) { @@ -1807,7 +1806,7 @@ public class MonetPreparedStatement x instanceof Float || x instanceof Double) { - Number num = (Number)x; + final Number num = (Number)x; switch (targetSqlType) { case Types.TINYINT: setByte(parameterIndex, num.byteValue()); @@ -1860,7 +1859,7 @@ public class MonetPreparedStatement throw new SQLException("Conversion not allowed", "M1M05"); } } else if (x instanceof Boolean) { - boolean val = ((Boolean)x).booleanValue(); + final boolean val = ((Boolean)x).booleanValue(); switch (targetSqlType) { case Types.TINYINT: setByte(parameterIndex, (byte)(val ? 1 : 0)); @@ -1884,7 +1883,7 @@ public class MonetPreparedStatement case Types.DECIMAL: case Types.NUMERIC: { - BigDecimal dec; + final BigDecimal dec; try { dec = new BigDecimal(val ? 1.0 : 0.0); } catch (NumberFormatException e) { @@ -1906,7 +1905,7 @@ public class MonetPreparedStatement throw new SQLException("Conversion not allowed", "M1M05"); } } else if (x instanceof BigInteger) { - BigInteger num = (BigInteger)x; + final BigInteger num = (BigInteger)x; switch (targetSqlType) { case Types.BIGINT: setLong(parameterIndex, num.longValue()); @@ -1914,7 +1913,7 @@ public class MonetPreparedStatement case Types.DECIMAL: case Types.NUMERIC: { - BigDecimal dec; + final BigDecimal dec; try { dec = new BigDecimal(num); } catch (NumberFormatException e) { @@ -2004,9 +2003,9 @@ public class MonetPreparedStatement } } else if (x instanceof Array) { setArray(parameterIndex, (Array)x); - } else if (x instanceof Blob || x instanceof MonetBlob) { + } else if (x instanceof MonetBlob || x instanceof Blob) { setBlob(parameterIndex, (Blob)x); - } else if (x instanceof Clob || x instanceof MonetClob) { + } else if (x instanceof MonetClob || x instanceof Clob) { setClob(parameterIndex, (Clob)x); } else if (x instanceof Struct) { // I have no idea how to do this... @@ -2024,10 +2023,10 @@ public class MonetPreparedStatement } else if (x instanceof SQLXML) { setSQLXML(parameterIndex, (SQLXML)x); } else if (x instanceof SQLData) { // not in JDBC4.1??? - SQLData sx = (SQLData)x; + final SQLData sx = (SQLData)x; final int paramnr = parameterIndex; final String sqltype = sx.getSQLTypeName(); - SQLOutput out = new SQLOutput() { + final SQLOutput out = new SQLOutput() { @Override public void writeString(String x) throws SQLException { // special situation, this is when a string @@ -2188,7 +2187,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setRef(int parameterIndex, Ref x) throws SQLException { + public void setRef(final int parameterIndex, final Ref x) throws SQLException { throw newSQLFeatureNotSupportedException("setRef"); } @@ -2204,7 +2203,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setRowId(int parameterIndex, RowId x) throws SQLException { + public void setRowId(final int parameterIndex, final RowId x) throws SQLException { throw newSQLFeatureNotSupportedException("setRowId"); } @@ -2217,7 +2216,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setShort(int parameterIndex, short x) throws SQLException { + public void setShort(final int parameterIndex, final short x) throws SQLException { setValue(parameterIndex, Short.toString(x)); } @@ -2232,18 +2231,18 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setString(int parameterIndex, String x) throws SQLException { + public void setString(final int parameterIndex, final String x) throws SQLException { if (x == null) { setNull(parameterIndex, -1); return; } - int paramIdx = getParamIdx(parameterIndex); // this will throw a SQLException if parameter can not be found + final int paramIdx = getParamIdx(parameterIndex); // this will throw a SQLException if parameter can not be found /* depending on the parameter data type (as expected by MonetDB) we may need to add the data type as cast prefix to the parameter value */ - int paramJdbcType = javaType[paramIdx]; - String paramMonetdbType = monetdbType[paramIdx]; + final int paramJdbcType = javaType[paramIdx]; + final String paramMonetdbType = monetdbType[paramIdx]; switch (paramJdbcType) { case Types.CHAR: @@ -2311,8 +2310,7 @@ public class MonetPreparedStatement break; } /* in specific cases prefix the string with: inet or json or url or uuid */ - setValue(parameterIndex, - castprefix + "'" + x.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'") + "'"); + setValue(parameterIndex, castprefix + "'" + x.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'") + "'"); break; } case Types.TINYINT: @@ -2379,7 +2377,7 @@ public class MonetPreparedStatement case Types.BLOB: // check if the string x contains pairs of hex chars to prevent // failing exec #(..., ...) calls which destroy the prepared statement, see bug 6351 - int xlen = x.length(); + final int xlen = x.length(); for (int i = 0; i < xlen; i++) { char c = x.charAt(i); if (c < '0' || c > '9') { @@ -2410,7 +2408,7 @@ public class MonetPreparedStatement * not support this method */ @Override - public void setSQLXML(int parameterIndex, SQLXML x) throws SQLException { + public void setSQLXML(final int parameterIndex, final SQLXML x) throws SQLException { throw newSQLFeatureNotSupportedException("setSQLXML"); } @@ -2424,7 +2422,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setTime(int parameterIndex, Time x) throws SQLException { + public void setTime(final int parameterIndex, final Time x) throws SQLException { setTime(parameterIndex, x, null); } @@ -2444,7 +2442,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setTime(int parameterIndex, Time x, Calendar cal) + public void setTime(final int parameterIndex, final Time x, final Calendar cal) throws SQLException { if (x == null) { @@ -2452,8 +2450,8 @@ public class MonetPreparedStatement return; } - String MonetDBType = monetdbType[getParamIdx(parameterIndex)]; - boolean hasTimeZone = ("timetz".equals(MonetDBType) || "timestamptz".equals(MonetDBType)); + final String MonetDBType = monetdbType[getParamIdx(parameterIndex)]; + final boolean hasTimeZone = ("timetz".equals(MonetDBType) || "timestamptz".equals(MonetDBType)); if (hasTimeZone) { // timezone shouldn't matter, since the server is timezone // aware in this case @@ -2461,9 +2459,8 @@ public class MonetPreparedStatement // first time usage, create and keep the mTimeZ object for next usage mTimeZ = new SimpleDateFormat("HH:mm:ss.SSSZ"); } - String RFC822 = mTimeZ.format(x); - setValue(parameterIndex, "timetz '" + - RFC822.substring(0, 15) + ":" + RFC822.substring(15) + "'"); + final String RFC822 = mTimeZ.format(x); + setValue(parameterIndex, "timetz '" + RFC822.substring(0, 15) + ":" + RFC822.substring(15) + "'"); } else { // server is not timezone aware for this field, and no // calendar given, since we told the server our timezone at @@ -2492,7 +2489,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setTimestamp(int parameterIndex, Timestamp x) + public void setTimestamp(final int parameterIndex, final Timestamp x) throws SQLException { setTimestamp(parameterIndex, x, null); @@ -2515,7 +2512,7 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) + public void setTimestamp(final int parameterIndex, final Timestamp x, final Calendar cal) throws SQLException { if (x == null) { @@ -2523,8 +2520,8 @@ public class MonetPreparedStatement return; } - String MonetDBType = monetdbType[getParamIdx(parameterIndex)]; - boolean hasTimeZone = ("timestamptz".equals(MonetDBType) || "timetz".equals(MonetDBType)); + final String MonetDBType = monetdbType[getParamIdx(parameterIndex)]; + final boolean hasTimeZone = ("timestamptz".equals(MonetDBType) || "timetz".equals(MonetDBType)); if (hasTimeZone) { // timezone shouldn't matter, since the server is timezone // aware in this case @@ -2532,9 +2529,8 @@ public class MonetPreparedStatement // first time usage, create and keep the mTimestampZ object for next usage mTimestampZ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); } - String RFC822 = mTimestampZ.format(x); - setValue(parameterIndex, "timestamptz '" + - RFC822.substring(0, 26) + ":" + RFC822.substring(26) + "'"); + final String RFC822 = mTimestampZ.format(x); + setValue(parameterIndex, "timestamptz '" + RFC822.substring(0, 26) + ":" + RFC822.substring(26) + "'"); } else { // server is not timezone aware for this field, and no // calendar given, since we told the server our timezone at @@ -2576,7 +2572,7 @@ public class MonetPreparedStatement */ @Override @Deprecated - public void setUnicodeStream(int parameterIndex, InputStream x, int length) + public void setUnicodeStream(final int parameterIndex, final InputStream x, final int length) throws SQLException { throw newSQLFeatureNotSupportedException("setUnicodeStream"); @@ -2592,16 +2588,14 @@ public class MonetPreparedStatement * @throws SQLException if a database access error occurs */ @Override - public void setURL(int parameterIndex, URL x) throws SQLException { + public void setURL(final int parameterIndex, final URL x) throws SQLException { if (x == null) { setNull(parameterIndex, -1); return; } - String val = x.toString(); - setValue(parameterIndex, - "url '" + val.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'") + "'" - ); + final String val = x.toString(); + setValue(parameterIndex, "url '" + val.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'") + "'"); } /** @@ -2649,7 +2643,7 @@ public class MonetPreparedStatement * @param val the exact String representation to set * @throws SQLException if the given index is out of bounds */ - private void setValue(int parameterIndex, String val) throws SQLException { + private final void setValue(final int parameterIndex, final String val) throws SQLException { values[getParamIdx(parameterIndex)] = (val == null ? "NULL" : val); } @@ -2662,8 +2656,8 @@ public class MonetPreparedStatement * @return the simple SQL string for the prepare query * @throws SQLException if not all columns are set */ - private String transform() throws SQLException { - StringBuilder buf = new StringBuilder(8 + 12 * size); + private final String transform() throws SQLException { + final StringBuilder buf = new StringBuilder(8 + 12 * size); buf.append("exec ").append(id).append('('); // check if all columns are set and do a replace int col = 0; @@ -2691,7 +2685,7 @@ public class MonetPreparedStatement * @param paramIdx the parameter index number * @return a new created SQLDataException object with SQLState 22010 */ - private static final SQLDataException newSQLInvalidParameterIndexException(int paramIdx) { + private static final SQLDataException newSQLInvalidParameterIndexException(final int paramIdx) { return new SQLDataException("Invalid Parameter Index number: " + paramIdx, "22010"); } }
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetSavepoint.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetSavepoint.java @@ -9,7 +9,6 @@ package nl.cwi.monetdb.jdbc; import java.sql.SQLException; -import java.sql.Savepoint; import java.util.concurrent.atomic.AtomicInteger; /** @@ -32,9 +31,9 @@ import java.util.concurrent.atomic.Atomi * @author Fabian Groffen * @version 1.0 */ -public final class MonetSavepoint implements Savepoint { +public final class MonetSavepoint implements java.sql.Savepoint { /** The id of the last created Savepoint */ - private static AtomicInteger highestId = new AtomicInteger(0); + private static final AtomicInteger highestId = new AtomicInteger(0); /** The name of this Savepoint */ private final String name; @@ -44,7 +43,7 @@ public final class MonetSavepoint implem /** * Creates a named MonetSavepoint object */ - public MonetSavepoint(String name) throws IllegalArgumentException { + public MonetSavepoint(final String name) throws IllegalArgumentException { if (name == null || name.isEmpty()) throw new IllegalArgumentException("missing savepoint name string"); @@ -100,7 +99,7 @@ public final class MonetSavepoint implem * * @return the numeric ID of this savepoint */ - int getId() { + final int getId() { return id; } @@ -111,7 +110,7 @@ public final class MonetSavepoint implem * * @return the unique savepoint name */ - String getName() { + final String getName() { return "MonetDBSP" + id; } @@ -126,7 +125,7 @@ public final class MonetSavepoint implem * @return the next int which is guaranteed to be higher than the one * at the last call to this method. */ - private static int getNextId() { + private static final int getNextId() { return highestId.incrementAndGet(); }
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetStatement.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetStatement.java @@ -17,7 +17,6 @@ import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLWarning; import java.util.ArrayList; -import java.util.List; import java.util.concurrent.locks.ReentrantLock; /** @@ -95,10 +94,10 @@ public class MonetStatement * @throws IllegalArgumentException is one of the arguments null or empty */ MonetStatement( - MonetConnection connection, - int resultSetType, - int resultSetConcurrency, - int resultSetHoldability) + final MonetConnection connection, + final int resultSetType, + final int resultSetConcurrency, + final int resultSetHoldability) throws SQLException, IllegalArgumentException { if (connection == null) @@ -111,15 +110,15 @@ public class MonetStatement this.resultSetConcurrency = resultSetConcurrency; // check our limits, and generate warnings as appropriate - if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) { + if (this.resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) { addWarning("No concurrency mode other then read only is supported, continuing with concurrency level READ_ONLY", "01M13"); - resultSetConcurrency = ResultSet.CONCUR_READ_ONLY; + this.resultSetConcurrency = ResultSet.CONCUR_READ_ONLY; } // check type for supported mode - if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE) { + if (this.resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE) { addWarning("Change sensitive scrolling ResultSet objects are not supported, continuing with a change non-sensitive scrollable cursor.", "01M14"); - resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE; + this.resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE; } // check type for supported holdability @@ -139,7 +138,7 @@ public class MonetStatement * @throws SQLException so the PreparedStatement can throw this exception */ @Override - public void addBatch(String sql) throws SQLException { + public void addBatch(final String sql) throws SQLException { if (batch == null) { // create the ArrayList at first time use batch = new ArrayList<String>(); @@ -208,14 +207,14 @@ public class MonetStatement } batchLock.lock(); try { - int[] counts = new int[batch.size()]; + final int[] counts = new int[batch.size()]; + final String sep = connection.queryTempl[2]; + final int sepLen = sep.length(); + final BatchUpdateException e = new BatchUpdateException("Error(s) occurred while executing the batch, see next SQLExceptions for details", "22000", counts); + final StringBuilder tmpBatch = new StringBuilder(MapiSocket.BLOCK); int offset = 0; boolean first = true; boolean error = false; - String sep = connection.queryTempl[2]; - int sepLen = sep.length(); - BatchUpdateException e = new BatchUpdateException("Error(s) occurred while executing the batch, see next SQLExceptions for details", "22000", counts); - StringBuilder tmpBatch = new StringBuilder(MapiSocket.BLOCK); for (int i = 0; i < batch.size(); i++) { String tmp = batch.get(i); @@ -260,18 +259,20 @@ public class MonetStatement } private boolean internalBatch( - StringBuilder batch, - int[] counts, + final StringBuilder batch, + final int[] counts, int offset, - int max, - BatchUpdateException e) + final int max, + final BatchUpdateException e) throws BatchUpdateException { try { boolean type = internalExecute(batch.toString()); int count = -1; + if (!type) count = getUpdateCount(); + do { if (offset >= max) throw new SQLException("Overflow: don't use multi statements when batching (" + max + ")", "M1M16"); @@ -362,7 +363,7 @@ public class MonetStatement * @throws SQLException if a database access error occurs */ @Override - public boolean execute(String sql) throws SQLException { + public boolean execute(final String sql) throws SQLException { return internalExecute(sql); } @@ -397,7 +398,7 @@ public class MonetStatement * Statement.NO_GENERATED_KEYS. */ @Override - public boolean execute(String sql, int autoGeneratedKeys) + public boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException { if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS && @@ -445,7 +446,7 @@ public class MonetStatement * valid column indexes */ @Override - public boolean execute(String sql, int[] columnIndexes) + public boolean execute(final String sql, final int[] columnIndexes) throws SQLException { addWarning("execute: generated keys for fixed set of columns not supported", "01M18"); @@ -489,7 +490,7 @@ public class MonetStatement * not valid column names */ @Override - public boolean execute(String sql, String[] columnNames) + public boolean execute(final String sql, final String[] columnNames) throws SQLException { addWarning("execute: generated keys for fixed set of columns not supported", "01M18"); @@ -509,7 +510,7 @@ public class MonetStatement * it is an update count or there are no results * @throws SQLException if a database access error occurs */ - private boolean internalExecute(String sql) throws SQLException { + private boolean internalExecute(final String sql) throws SQLException { // close previous query, if not closed already if (lastResponseList != null) { lastResponseList.close(); @@ -521,7 +522,7 @@ public class MonetStatement Statement st = null; try { st = connection.createStatement(); - String callstmt = "CALL \"sys\".\"settimeout\"(" + queryTimeout + ")"; + final String callstmt = "CALL \"sys\".\"settimeout\"(" + queryTimeout + ")"; // for debug: System.out.println("Before: " + callstmt); st.execute(callstmt); // for debug: System.out.println("After : " + callstmt); @@ -562,7 +563,7 @@ public class MonetStatement * statement produces anything other than a single ResultSet object */ @Override - public ResultSet executeQuery(String sql) throws SQLException { + public ResultSet executeQuery(final String sql) throws SQLException { if (execute(sql) != true) throw new SQLException("Query did not produce a result set", "M1M19"); @@ -582,7 +583,7 @@ public class MonetStatement * statement produces a ResultSet object */ @Override - public int executeUpdate(String sql) throws SQLException { + public int executeUpdate(final String sql) throws SQLException { if (execute(sql) != false) throw new SQLException("Query produced a result set", "M1M17"); @@ -608,7 +609,7 @@ public class MonetStatement * given constant is not one of those allowed */ @Override - public int executeUpdate(String sql, int autoGeneratedKeys) + public int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException { if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS && @@ -646,7 +647,7 @@ public class MonetStatement * whose elements are valid column indexes */ @Override - public int executeUpdate(String sql, int[] columnIndexes) + public int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException { addWarning("executeUpdate: generated keys for fixed set of columns not supported", "01M18"); @@ -677,7 +678,7 @@ public class MonetStatement * whose elements are valid column names */ @Override - public int executeUpdate(String sql, String[] columnNames) + public int executeUpdate(final String sql, final String[] columnNames) throws SQLException { addWarning("executeUpdate: generated keys for fixed set of columns not supported", "01M18"); @@ -734,8 +735,8 @@ public class MonetStatement */ @Override public ResultSet getGeneratedKeys() throws SQLException { - String[] columns, types; - String[][] results; + final String[] columns, types; + final String[][] results; columns = new String[1]; types = new String[1]; @@ -746,7 +747,7 @@ public class MonetStatement types[0] = "BIGINT"; if (header != null && header instanceof MonetConnection.UpdateResponse) { - String lastid = ((MonetConnection.UpdateResponse)header).lastid; + final String lastid = ((MonetConnection.UpdateResponse)header).lastid; if (lastid.equals("-1")) { results = new String[0][1]; } else { @@ -833,7 +834,7 @@ public class MonetStatement * @throws SQLException if a database access error occurs */ @Override - public boolean getMoreResults(int current) throws SQLException { + public boolean getMoreResults(final int current) throws SQLException { // protect against people calling this on an unitialised state if (lastResponseList == null) { header = null; @@ -990,7 +991,7 @@ public class MonetStatement * @throws SQLException if a database access error occurs */ @Override - public void setCursorName(String name) throws SQLException { + public void setCursorName(final String name) throws SQLException { addWarning("setCursorName: positioned updates/deletes not supported", "01M21"); } @@ -1012,7 +1013,7 @@ public class MonetStatement * @throws SQLException if a database access error occurs */ @Override - public void setEscapeProcessing(boolean enable) throws SQLException { + public void setEscapeProcessing(final boolean enable) throws SQLException { if (enable) addWarning("setEscapeProcessing: JDBC escape syntax is not supported by this driver", "01M22"); } @@ -1032,7 +1033,7 @@ public class MonetStatement * ResultSet.FETCH_REVERSE, or ResultSet.FETCH_UNKNOWN */ @Override - public void setFetchDirection(int direction) throws SQLException { + public void setFetchDirection(final int direction) throws SQLException { if (direction == ResultSet.FETCH_FORWARD || direction == ResultSet.FETCH_REVERSE || direction == ResultSet.FETCH_UNKNOWN) @@ -1054,7 +1055,7 @@ public class MonetStatement * is not satisfied. */ @Override - public void setFetchSize(int rows) throws SQLException { + public void setFetchSize(final int rows) throws SQLException { if (rows >= 0 && !(getMaxRows() != 0 && rows > getMaxRows())) { fetchSize = rows; } else { @@ -1081,7 +1082,7 @@ public class MonetStatement * @see #getMaxFieldSize() */ @Override - public void setMaxFieldSize(int max) throws SQLException { + public void setMaxFieldSize(final int max) throws SQLException { if (max < 0) throw new SQLException("Illegal max value: " + max, "M1M05"); if (max > 0) @@ -1098,7 +1099,7 @@ public class MonetStatement * @see #getMaxRows() */ @Override - public void setMaxRows(int max) throws SQLException { + public void setMaxRows(final int max) throws SQLException { if (max < 0) throw new SQLException("Illegal max value: " + max, "M1M05"); maxRows = max; @@ -1115,7 +1116,7 @@ public class MonetStatement * condition seconds >= 0 is not satisfied */ @Override - public void setQueryTimeout(int seconds) throws SQLException { + public void setQueryTimeout(final int seconds) throws SQLException { if (seconds < 0) throw new SQLException("Illegal timeout value: " + seconds, "M1M05"); queryTimeout = seconds; @@ -1155,7 +1156,7 @@ public class MonetStatement * and that the statement not be pooled if false */ @Override - public void setPoolable(boolean poolable) { + public void setPoolable(final boolean poolable) { this.poolable = poolable; } @@ -1211,7 +1212,7 @@ public class MonetStatement * * @param reason the warning message */ - private void addWarning(String reason, String sqlstate) { + private void addWarning(final String reason, final String sqlstate) { SQLWarning warng = new SQLWarning(reason, sqlstate); if (warnings == null) { warnings = warng; @@ -1252,10 +1253,10 @@ final class MonetVirtualResultSet extend private boolean closed; MonetVirtualResultSet( - Statement statement, - String[] columns, - String[] types, - String[][] results + final Statement statement, + final String[] columns, + final String[] types, + final String[][] results ) throws IllegalArgumentException { super(statement, columns, types, results.length); this.results = results;
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetWrapper.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetWrapper.java @@ -45,7 +45,7 @@ public class MonetWrapper implements jav * @since 1.6 */ @Override - public boolean isWrapperFor(Class<?> iface) throws SQLException { + public boolean isWrapperFor(final Class<?> iface) throws SQLException { return iface != null && iface.isAssignableFrom(getClass()); } @@ -70,7 +70,7 @@ public class MonetWrapper implements jav */ @Override @SuppressWarnings("unchecked") - public <T> T unwrap(Class<T> iface) throws SQLException { + public <T> T unwrap(final Class<T> iface) throws SQLException { if (isWrapperFor(iface)) { return (T) this; } @@ -85,7 +85,7 @@ public class MonetWrapper implements jav * @param name the method name * @return a new created SQLFeatureNotSupportedException object with SQLState 0A000 */ - static final SQLFeatureNotSupportedException newSQLFeatureNotSupportedException(String name) { + static final SQLFeatureNotSupportedException newSQLFeatureNotSupportedException(final String name) { return new SQLFeatureNotSupportedException("Method " + name + " not implemented", "0A000"); } }