repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbClob.java
MariaDbClob.getSubString
public String getSubString(long pos, int length) throws SQLException { if (pos < 1) { throw ExceptionMapper.getSqlException("position must be >= 1"); } if (length < 0) { throw ExceptionMapper.getSqlException("length must be > 0"); } try { String val = toString(); return val.substring((int) pos - 1, Math.min((int) pos - 1 + length, val.length())); } catch (Exception e) { throw new SQLException(e); } }
java
public String getSubString(long pos, int length) throws SQLException { if (pos < 1) { throw ExceptionMapper.getSqlException("position must be >= 1"); } if (length < 0) { throw ExceptionMapper.getSqlException("length must be > 0"); } try { String val = toString(); return val.substring((int) pos - 1, Math.min((int) pos - 1 + length, val.length())); } catch (Exception e) { throw new SQLException(e); } }
[ "public", "String", "getSubString", "(", "long", "pos", ",", "int", "length", ")", "throws", "SQLException", "{", "if", "(", "pos", "<", "1", ")", "{", "throw", "ExceptionMapper", ".", "getSqlException", "(", "\"position must be >= 1\"", ")", ";", "}", "if",...
Get sub string. @param pos position @param length length of sub string @return substring @throws SQLException if pos is less than 1 or length is less than 0
[ "Get", "sub", "string", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbClob.java#L118-L134
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbClob.java
MariaDbClob.getCharacterStream
public Reader getCharacterStream(long pos, long length) throws SQLException { String val = toString(); if (val.length() < (int) pos - 1 + length) { throw ExceptionMapper .getSqlException("pos + length is greater than the number of characters in the Clob"); } String sub = val.substring((int) pos - 1, (int) pos - 1 + (int) length); return new StringReader(sub); }
java
public Reader getCharacterStream(long pos, long length) throws SQLException { String val = toString(); if (val.length() < (int) pos - 1 + length) { throw ExceptionMapper .getSqlException("pos + length is greater than the number of characters in the Clob"); } String sub = val.substring((int) pos - 1, (int) pos - 1 + (int) length); return new StringReader(sub); }
[ "public", "Reader", "getCharacterStream", "(", "long", "pos", ",", "long", "length", ")", "throws", "SQLException", "{", "String", "val", "=", "toString", "(", ")", ";", "if", "(", "val", ".", "length", "(", ")", "<", "(", "int", ")", "pos", "-", "1"...
Returns a Reader object that contains a partial Clob value, starting with the character specified by pos, which is length characters in length. @param pos the offset to the first character of the partial value to be retrieved. The first character in the Clob is at position 1. @param length the length in characters of the partial value to be retrieved. @return Reader through which the partial Clob value can be read. @throws SQLException if pos is less than 1 or if pos is greater than the number of characters in the Clob or if pos + length is greater than the number of characters in the Clob
[ "Returns", "a", "Reader", "object", "that", "contains", "a", "partial", "Clob", "value", "starting", "with", "the", "character", "specified", "by", "pos", "which", "is", "length", "characters", "in", "length", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbClob.java#L152-L160
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbClob.java
MariaDbClob.setCharacterStream
public Writer setCharacterStream(long pos) throws SQLException { int bytePosition = utf8Position((int) pos - 1); OutputStream stream = setBinaryStream(bytePosition + 1); return new OutputStreamWriter(stream, StandardCharsets.UTF_8); }
java
public Writer setCharacterStream(long pos) throws SQLException { int bytePosition = utf8Position((int) pos - 1); OutputStream stream = setBinaryStream(bytePosition + 1); return new OutputStreamWriter(stream, StandardCharsets.UTF_8); }
[ "public", "Writer", "setCharacterStream", "(", "long", "pos", ")", "throws", "SQLException", "{", "int", "bytePosition", "=", "utf8Position", "(", "(", "int", ")", "pos", "-", "1", ")", ";", "OutputStream", "stream", "=", "setBinaryStream", "(", "bytePosition"...
Set character stream. @param pos position @return writer @throws SQLException if position is invalid
[ "Set", "character", "stream", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbClob.java#L169-L173
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbClob.java
MariaDbClob.utf8Position
private int utf8Position(int charPosition) { int pos = offset; for (int i = 0; i < charPosition; i++) { int byteValue = data[pos] & 0xff; if (byteValue < 0x80) { pos += 1; } else if (byteValue < 0xC2) { throw new UncheckedIOException("invalid UTF8", new CharacterCodingException()); } else if (byteValue < 0xE0) { pos += 2; } else if (byteValue < 0xF0) { pos += 3; } else if (byteValue < 0xF8) { pos += 4; } else { throw new UncheckedIOException("invalid UTF8", new CharacterCodingException()); } } return pos; }
java
private int utf8Position(int charPosition) { int pos = offset; for (int i = 0; i < charPosition; i++) { int byteValue = data[pos] & 0xff; if (byteValue < 0x80) { pos += 1; } else if (byteValue < 0xC2) { throw new UncheckedIOException("invalid UTF8", new CharacterCodingException()); } else if (byteValue < 0xE0) { pos += 2; } else if (byteValue < 0xF0) { pos += 3; } else if (byteValue < 0xF8) { pos += 4; } else { throw new UncheckedIOException("invalid UTF8", new CharacterCodingException()); } } return pos; }
[ "private", "int", "utf8Position", "(", "int", "charPosition", ")", "{", "int", "pos", "=", "offset", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "charPosition", ";", "i", "++", ")", "{", "int", "byteValue", "=", "data", "[", "pos", "]", ...
Convert character position into byte position in UTF8 byte array. @param charPosition charPosition @return byte position
[ "Convert", "character", "position", "into", "byte", "position", "in", "UTF8", "byte", "array", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbClob.java#L193-L212
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbClob.java
MariaDbClob.setString
public int setString(long pos, String str) throws SQLException { int bytePosition = utf8Position((int) pos - 1); super.setBytes(bytePosition + 1 - offset, str.getBytes(StandardCharsets.UTF_8)); return str.length(); }
java
public int setString(long pos, String str) throws SQLException { int bytePosition = utf8Position((int) pos - 1); super.setBytes(bytePosition + 1 - offset, str.getBytes(StandardCharsets.UTF_8)); return str.length(); }
[ "public", "int", "setString", "(", "long", "pos", ",", "String", "str", ")", "throws", "SQLException", "{", "int", "bytePosition", "=", "utf8Position", "(", "(", "int", ")", "pos", "-", "1", ")", ";", "super", ".", "setBytes", "(", "bytePosition", "+", ...
Set String. @param pos position @param str string @return string length @throws SQLException if UTF-8 conversion failed
[ "Set", "String", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbClob.java#L222-L226
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbClob.java
MariaDbClob.length
@Override public long length() { //The length of a character string is the number of UTF-16 units (not the number of characters) long len = 0; int pos = offset; //set ASCII (<= 127 chars) for (; len < length && data[pos] >= 0; ) { len++; pos++; } //multi-bytes UTF-8 while (pos < offset + length) { byte firstByte = data[pos++]; if (firstByte < 0) { if (firstByte >> 5 != -2 || (firstByte & 30) == 0) { if (firstByte >> 4 == -2) { if (pos + 1 < offset + length) { pos += 2; len++; } else { throw new UncheckedIOException("invalid UTF8", new CharacterCodingException()); } } else if (firstByte >> 3 != -2) { throw new UncheckedIOException("invalid UTF8", new CharacterCodingException()); } else if (pos + 2 < offset + length) { pos += 3; len += 2; } else { //bad truncated UTF8 pos += offset + length; len += 1; } } else { pos++; len++; } } else { len++; } } return len; }
java
@Override public long length() { //The length of a character string is the number of UTF-16 units (not the number of characters) long len = 0; int pos = offset; //set ASCII (<= 127 chars) for (; len < length && data[pos] >= 0; ) { len++; pos++; } //multi-bytes UTF-8 while (pos < offset + length) { byte firstByte = data[pos++]; if (firstByte < 0) { if (firstByte >> 5 != -2 || (firstByte & 30) == 0) { if (firstByte >> 4 == -2) { if (pos + 1 < offset + length) { pos += 2; len++; } else { throw new UncheckedIOException("invalid UTF8", new CharacterCodingException()); } } else if (firstByte >> 3 != -2) { throw new UncheckedIOException("invalid UTF8", new CharacterCodingException()); } else if (pos + 2 < offset + length) { pos += 3; len += 2; } else { //bad truncated UTF8 pos += offset + length; len += 1; } } else { pos++; len++; } } else { len++; } } return len; }
[ "@", "Override", "public", "long", "length", "(", ")", "{", "//The length of a character string is the number of UTF-16 units (not the number of characters)", "long", "len", "=", "0", ";", "int", "pos", "=", "offset", ";", "//set ASCII (<= 127 chars)", "for", "(", ";", ...
Return character length of the Clob. Assume UTF8 encoding.
[ "Return", "character", "length", "of", "the", "Clob", ".", "Assume", "UTF8", "encoding", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbClob.java#L239-L282
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/tls/MariaDbX509KeyManager.java
MariaDbX509KeyManager.searchAccurateAliases
private ArrayList<String> searchAccurateAliases(String[] keyTypes, Principal[] issuers) { if (keyTypes == null || keyTypes.length == 0) { return null; } ArrayList<String> accurateAliases = new ArrayList<>(); for (Map.Entry<String, KeyStore.PrivateKeyEntry> mapEntry : privateKeyHash.entrySet()) { Certificate[] certs = mapEntry.getValue().getCertificateChain(); String alg = certs[0].getPublicKey().getAlgorithm(); for (String keyType : keyTypes) { if (alg.equals(keyType)) { if (issuers != null && issuers.length != 0) { checkLoop: for (Certificate cert : certs) { if (cert instanceof X509Certificate) { X500Principal certificateIssuer = ((X509Certificate) cert).getIssuerX500Principal(); for (Principal issuer : issuers) { if (certificateIssuer.equals(issuer)) { accurateAliases.add(mapEntry.getKey()); break checkLoop; } } } } } else { accurateAliases.add(mapEntry.getKey()); } } } } return accurateAliases; }
java
private ArrayList<String> searchAccurateAliases(String[] keyTypes, Principal[] issuers) { if (keyTypes == null || keyTypes.length == 0) { return null; } ArrayList<String> accurateAliases = new ArrayList<>(); for (Map.Entry<String, KeyStore.PrivateKeyEntry> mapEntry : privateKeyHash.entrySet()) { Certificate[] certs = mapEntry.getValue().getCertificateChain(); String alg = certs[0].getPublicKey().getAlgorithm(); for (String keyType : keyTypes) { if (alg.equals(keyType)) { if (issuers != null && issuers.length != 0) { checkLoop: for (Certificate cert : certs) { if (cert instanceof X509Certificate) { X500Principal certificateIssuer = ((X509Certificate) cert).getIssuerX500Principal(); for (Principal issuer : issuers) { if (certificateIssuer.equals(issuer)) { accurateAliases.add(mapEntry.getKey()); break checkLoop; } } } } } else { accurateAliases.add(mapEntry.getKey()); } } } } return accurateAliases; }
[ "private", "ArrayList", "<", "String", ">", "searchAccurateAliases", "(", "String", "[", "]", "keyTypes", ",", "Principal", "[", "]", "issuers", ")", "{", "if", "(", "keyTypes", "==", "null", "||", "keyTypes", ".", "length", "==", "0", ")", "{", "return"...
Search aliases corresponding to algorithms and issuers. @param keyTypes list of algorithms @param issuers list of issuers; @return list of corresponding aliases
[ "Search", "aliases", "corresponding", "to", "algorithms", "and", "issuers", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/tls/MariaDbX509KeyManager.java#L156-L189
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/socket/SocketUtility.java
SocketUtility.getSocketHandler
@SuppressWarnings("unchecked") public static SocketHandlerFunction getSocketHandler() { try { //forcing use of JNA to ensure AOT compilation Platform.getOSType(); return (urlParser, host) -> { if (urlParser.getOptions().pipe != null) { return new NamedPipeSocket(host, urlParser.getOptions().pipe); } else if (urlParser.getOptions().localSocket != null) { try { return new UnixDomainSocket(urlParser.getOptions().localSocket); } catch (RuntimeException re) { throw new IOException(re.getMessage(), re.getCause()); } } else if (urlParser.getOptions().sharedMemory != null) { try { return new SharedMemorySocket(urlParser.getOptions().sharedMemory); } catch (RuntimeException re) { throw new IOException(re.getMessage(), re.getCause()); } } else { return Utils.standardSocket(urlParser, host); } }; } catch (Throwable cle) { //jna jar's are not in classpath } return (urlParser, host) -> Utils.standardSocket(urlParser, host); }
java
@SuppressWarnings("unchecked") public static SocketHandlerFunction getSocketHandler() { try { //forcing use of JNA to ensure AOT compilation Platform.getOSType(); return (urlParser, host) -> { if (urlParser.getOptions().pipe != null) { return new NamedPipeSocket(host, urlParser.getOptions().pipe); } else if (urlParser.getOptions().localSocket != null) { try { return new UnixDomainSocket(urlParser.getOptions().localSocket); } catch (RuntimeException re) { throw new IOException(re.getMessage(), re.getCause()); } } else if (urlParser.getOptions().sharedMemory != null) { try { return new SharedMemorySocket(urlParser.getOptions().sharedMemory); } catch (RuntimeException re) { throw new IOException(re.getMessage(), re.getCause()); } } else { return Utils.standardSocket(urlParser, host); } }; } catch (Throwable cle) { //jna jar's are not in classpath } return (urlParser, host) -> Utils.standardSocket(urlParser, host); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "SocketHandlerFunction", "getSocketHandler", "(", ")", "{", "try", "{", "//forcing use of JNA to ensure AOT compilation", "Platform", ".", "getOSType", "(", ")", ";", "return", "(", "urlParser", "...
Create socket according to options. In case of compilation ahead of time, will throw an error if dependencies found, then use default socket implementation. @return Socket
[ "Create", "socket", "according", "to", "options", ".", "In", "case", "of", "compilation", "ahead", "of", "time", "will", "throw", "an", "error", "if", "dependencies", "found", "then", "use", "default", "socket", "implementation", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/socket/SocketUtility.java#L15-L45
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/thread/TerminableRunnable.java
TerminableRunnable.blockTillTerminated
public void blockTillTerminated() { while (!runState.compareAndSet(State.IDLE, State.REMOVED)) { // wait and retry LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); if (Thread.currentThread().isInterrupted()) { runState.set(State.REMOVED); return; } } }
java
public void blockTillTerminated() { while (!runState.compareAndSet(State.IDLE, State.REMOVED)) { // wait and retry LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); if (Thread.currentThread().isInterrupted()) { runState.set(State.REMOVED); return; } } }
[ "public", "void", "blockTillTerminated", "(", ")", "{", "while", "(", "!", "runState", ".", "compareAndSet", "(", "State", ".", "IDLE", ",", "State", ".", "REMOVED", ")", ")", "{", "// wait and retry", "LockSupport", ".", "parkNanos", "(", "TimeUnit", ".", ...
Unschedule next launched, and wait for the current task to complete before closing it.
[ "Unschedule", "next", "launched", "and", "wait", "for", "the", "current", "task", "to", "complete", "before", "closing", "it", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/thread/TerminableRunnable.java#L94-L103
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/thread/TerminableRunnable.java
TerminableRunnable.unscheduleTask
public void unscheduleTask() { if (unschedule.compareAndSet(false, true)) { scheduledFuture.cancel(false); scheduledFuture = null; } }
java
public void unscheduleTask() { if (unschedule.compareAndSet(false, true)) { scheduledFuture.cancel(false); scheduledFuture = null; } }
[ "public", "void", "unscheduleTask", "(", ")", "{", "if", "(", "unschedule", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "scheduledFuture", ".", "cancel", "(", "false", ")", ";", "scheduledFuture", "=", "null", ";", "}", "}" ]
Unschedule task if active, and cancel thread to inform it must be interrupted in a proper way.
[ "Unschedule", "task", "if", "active", "and", "cancel", "thread", "to", "inform", "it", "must", "be", "interrupted", "in", "a", "proper", "way", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/thread/TerminableRunnable.java#L112-L118
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/dao/CmdInformationSingle.java
CmdInformationSingle.getGeneratedKeys
public ResultSet getGeneratedKeys(Protocol protocol) { if (insertId == 0) { return SelectResultSet.createEmptyResultSet(); } if (updateCount > 1) { long[] insertIds = new long[(int) updateCount]; for (int i = 0; i < updateCount; i++) { insertIds[i] = insertId + i * autoIncrement; } return SelectResultSet.createGeneratedData(insertIds, protocol, true); } return SelectResultSet.createGeneratedData(new long[]{insertId}, protocol, true); }
java
public ResultSet getGeneratedKeys(Protocol protocol) { if (insertId == 0) { return SelectResultSet.createEmptyResultSet(); } if (updateCount > 1) { long[] insertIds = new long[(int) updateCount]; for (int i = 0; i < updateCount; i++) { insertIds[i] = insertId + i * autoIncrement; } return SelectResultSet.createGeneratedData(insertIds, protocol, true); } return SelectResultSet.createGeneratedData(new long[]{insertId}, protocol, true); }
[ "public", "ResultSet", "getGeneratedKeys", "(", "Protocol", "protocol", ")", "{", "if", "(", "insertId", "==", "0", ")", "{", "return", "SelectResultSet", ".", "createEmptyResultSet", "(", ")", ";", "}", "if", "(", "updateCount", ">", "1", ")", "{", "long"...
Get generated Keys. @param protocol current protocol @return a resultSet containing the single insert ids.
[ "Get", "generated", "Keys", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/dao/CmdInformationSingle.java#L126-L140
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java
BinaryRowProtocol.getInternalBigDecimal
public BigDecimal getInternalBigDecimal(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case BIT: return BigDecimal.valueOf(parseBit()); case TINYINT: return BigDecimal.valueOf((long) getInternalTinyInt(columnInfo)); case SMALLINT: case YEAR: return BigDecimal.valueOf((long) getInternalSmallInt(columnInfo)); case INTEGER: case MEDIUMINT: return BigDecimal.valueOf(getInternalMediumInt(columnInfo)); case BIGINT: long value = ((buf[pos] & 0xff) + ((long) (buf[pos + 1] & 0xff) << 8) + ((long) (buf[pos + 2] & 0xff) << 16) + ((long) (buf[pos + 3] & 0xff) << 24) + ((long) (buf[pos + 4] & 0xff) << 32) + ((long) (buf[pos + 5] & 0xff) << 40) + ((long) (buf[pos + 6] & 0xff) << 48) + ((long) (buf[pos + 7] & 0xff) << 56) ); if (columnInfo.isSigned()) { return new BigDecimal(String.valueOf(BigInteger.valueOf(value))) .setScale(columnInfo.getDecimals()); } else { return new BigDecimal(String.valueOf(new BigInteger(1, new byte[]{(byte) (value >> 56), (byte) (value >> 48), (byte) (value >> 40), (byte) (value >> 32), (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value}))).setScale(columnInfo.getDecimals()); } case FLOAT: return BigDecimal.valueOf(getInternalFloat(columnInfo)); case DOUBLE: return BigDecimal.valueOf(getInternalDouble(columnInfo)); case DECIMAL: case VARSTRING: case VARCHAR: case STRING: case OLDDECIMAL: return new BigDecimal(new String(buf, pos, length, StandardCharsets.UTF_8)); default: throw new SQLException("getBigDecimal not available for data field type " + columnInfo.getColumnType().getJavaTypeName()); } }
java
public BigDecimal getInternalBigDecimal(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case BIT: return BigDecimal.valueOf(parseBit()); case TINYINT: return BigDecimal.valueOf((long) getInternalTinyInt(columnInfo)); case SMALLINT: case YEAR: return BigDecimal.valueOf((long) getInternalSmallInt(columnInfo)); case INTEGER: case MEDIUMINT: return BigDecimal.valueOf(getInternalMediumInt(columnInfo)); case BIGINT: long value = ((buf[pos] & 0xff) + ((long) (buf[pos + 1] & 0xff) << 8) + ((long) (buf[pos + 2] & 0xff) << 16) + ((long) (buf[pos + 3] & 0xff) << 24) + ((long) (buf[pos + 4] & 0xff) << 32) + ((long) (buf[pos + 5] & 0xff) << 40) + ((long) (buf[pos + 6] & 0xff) << 48) + ((long) (buf[pos + 7] & 0xff) << 56) ); if (columnInfo.isSigned()) { return new BigDecimal(String.valueOf(BigInteger.valueOf(value))) .setScale(columnInfo.getDecimals()); } else { return new BigDecimal(String.valueOf(new BigInteger(1, new byte[]{(byte) (value >> 56), (byte) (value >> 48), (byte) (value >> 40), (byte) (value >> 32), (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value}))).setScale(columnInfo.getDecimals()); } case FLOAT: return BigDecimal.valueOf(getInternalFloat(columnInfo)); case DOUBLE: return BigDecimal.valueOf(getInternalDouble(columnInfo)); case DECIMAL: case VARSTRING: case VARCHAR: case STRING: case OLDDECIMAL: return new BigDecimal(new String(buf, pos, length, StandardCharsets.UTF_8)); default: throw new SQLException("getBigDecimal not available for data field type " + columnInfo.getColumnType().getJavaTypeName()); } }
[ "public", "BigDecimal", "getInternalBigDecimal", "(", "ColumnInformation", "columnInfo", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "switch", "(", "columnInfo", ".", "getColumnType", "(", ")...
Get BigDecimal from raw binary format. @param columnInfo column information @return BigDecimal value @throws SQLException if column is not numeric
[ "Get", "BigDecimal", "from", "raw", "binary", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L668-L717
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java
BinaryRowProtocol.getInternalDate
@SuppressWarnings("deprecation") public Date getInternalDate(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case TIMESTAMP: case DATETIME: Timestamp timestamp = getInternalTimestamp(columnInfo, cal, timeZone); return (timestamp == null) ? null : new Date(timestamp.getTime()); case TIME: throw new SQLException("Cannot read Date using a Types.TIME field"); case STRING: String rawValue = new String(buf, pos, length, StandardCharsets.UTF_8); if ("0000-00-00".equals(rawValue)) { lastValueNull |= BIT_LAST_ZERO_DATE; return null; } return new Date( Integer.parseInt(rawValue.substring(0, 4)) - 1900, Integer.parseInt(rawValue.substring(5, 7)) - 1, Integer.parseInt(rawValue.substring(8, 10)) ); default: if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } int year = ((buf[pos] & 0xff) | (buf[pos + 1] & 0xff) << 8); if (length == 2 && columnInfo.getLength() == 2) { //YEAR(2) - deprecated if (year <= 69) { year += 2000; } else { year += 1900; } } int month = 1; int day = 1; if (length >= 4) { month = buf[pos + 2]; day = buf[pos + 3]; } Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date dt = new Date(calendar.getTimeInMillis()); return dt; } }
java
@SuppressWarnings("deprecation") public Date getInternalDate(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case TIMESTAMP: case DATETIME: Timestamp timestamp = getInternalTimestamp(columnInfo, cal, timeZone); return (timestamp == null) ? null : new Date(timestamp.getTime()); case TIME: throw new SQLException("Cannot read Date using a Types.TIME field"); case STRING: String rawValue = new String(buf, pos, length, StandardCharsets.UTF_8); if ("0000-00-00".equals(rawValue)) { lastValueNull |= BIT_LAST_ZERO_DATE; return null; } return new Date( Integer.parseInt(rawValue.substring(0, 4)) - 1900, Integer.parseInt(rawValue.substring(5, 7)) - 1, Integer.parseInt(rawValue.substring(8, 10)) ); default: if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } int year = ((buf[pos] & 0xff) | (buf[pos + 1] & 0xff) << 8); if (length == 2 && columnInfo.getLength() == 2) { //YEAR(2) - deprecated if (year <= 69) { year += 2000; } else { year += 1900; } } int month = 1; int day = 1; if (length >= 4) { month = buf[pos + 2]; day = buf[pos + 3]; } Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date dt = new Date(calendar.getTimeInMillis()); return dt; } }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "Date", "getInternalDate", "(", "ColumnInformation", "columnInfo", ",", "Calendar", "cal", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")"...
Get date from raw binary format. @param columnInfo column information @param cal calendar @param timeZone time zone @return date value @throws SQLException if column is not compatible to Date
[ "Get", "date", "from", "raw", "binary", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L728-L790
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java
BinaryRowProtocol.getInternalTime
public Time getInternalTime(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case TIMESTAMP: case DATETIME: Timestamp ts = getInternalTimestamp(columnInfo, cal, timeZone); return (ts == null) ? null : new Time(ts.getTime()); case DATE: throw new SQLException("Cannot read Time using a Types.DATE field"); default: Calendar calendar = Calendar.getInstance(); calendar.clear(); int day = 0; int hour = 0; int minutes = 0; int seconds = 0; boolean negate = false; if (length > 0) { negate = (buf[pos] & 0xff) == 0x01; } if (length > 4) { day = ((buf[pos + 1] & 0xff) + ((buf[pos + 2] & 0xff) << 8) + ((buf[pos + 3] & 0xff) << 16) + ((buf[pos + 4] & 0xff) << 24)); } if (length > 7) { hour = buf[pos + 5]; minutes = buf[pos + 6]; seconds = buf[pos + 7]; } calendar .set(1970, Calendar.JANUARY, ((negate ? -1 : 1) * day) + 1, (negate ? -1 : 1) * hour, minutes, seconds); int nanoseconds = 0; if (length > 8) { nanoseconds = ((buf[pos + 8] & 0xff) + ((buf[pos + 9] & 0xff) << 8) + ((buf[pos + 10] & 0xff) << 16) + ((buf[pos + 11] & 0xff) << 24)); } calendar.set(Calendar.MILLISECOND, nanoseconds / 1000); return new Time(calendar.getTimeInMillis()); } }
java
public Time getInternalTime(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case TIMESTAMP: case DATETIME: Timestamp ts = getInternalTimestamp(columnInfo, cal, timeZone); return (ts == null) ? null : new Time(ts.getTime()); case DATE: throw new SQLException("Cannot read Time using a Types.DATE field"); default: Calendar calendar = Calendar.getInstance(); calendar.clear(); int day = 0; int hour = 0; int minutes = 0; int seconds = 0; boolean negate = false; if (length > 0) { negate = (buf[pos] & 0xff) == 0x01; } if (length > 4) { day = ((buf[pos + 1] & 0xff) + ((buf[pos + 2] & 0xff) << 8) + ((buf[pos + 3] & 0xff) << 16) + ((buf[pos + 4] & 0xff) << 24)); } if (length > 7) { hour = buf[pos + 5]; minutes = buf[pos + 6]; seconds = buf[pos + 7]; } calendar .set(1970, Calendar.JANUARY, ((negate ? -1 : 1) * day) + 1, (negate ? -1 : 1) * hour, minutes, seconds); int nanoseconds = 0; if (length > 8) { nanoseconds = ((buf[pos + 8] & 0xff) + ((buf[pos + 9] & 0xff) << 8) + ((buf[pos + 10] & 0xff) << 16) + ((buf[pos + 11] & 0xff) << 24)); } calendar.set(Calendar.MILLISECOND, nanoseconds / 1000); return new Time(calendar.getTimeInMillis()); } }
[ "public", "Time", "getInternalTime", "(", "ColumnInformation", "columnInfo", ",", "Calendar", "cal", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "switch", "(", ...
Get time from raw binary format. @param columnInfo column information @param cal calendar @param timeZone time zone @return Time value @throws SQLException if column cannot be converted to Time
[ "Get", "time", "from", "raw", "binary", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L801-L851
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java
BinaryRowProtocol.getInternalObject
public Object getInternalObject(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case BIT: if (columnInfo.getLength() == 1) { return buf[pos] != 0; } byte[] dataBit = new byte[length]; System.arraycopy(buf, pos, dataBit, 0, length); return dataBit; case TINYINT: if (options.tinyInt1isBit && columnInfo.getLength() == 1) { return buf[pos] != 0; } return getInternalInt(columnInfo); case INTEGER: if (!columnInfo.isSigned()) { return getInternalLong(columnInfo); } return getInternalInt(columnInfo); case BIGINT: if (!columnInfo.isSigned()) { return getInternalBigInteger(columnInfo); } return getInternalLong(columnInfo); case DOUBLE: return getInternalDouble(columnInfo); case VARCHAR: case VARSTRING: case STRING: if (columnInfo.isBinary()) { byte[] data = new byte[getLengthMaxFieldSize()]; System.arraycopy(buf, pos, data, 0, getLengthMaxFieldSize()); return data; } return getInternalString(columnInfo, null, timeZone); case TIMESTAMP: case DATETIME: return getInternalTimestamp(columnInfo, null, timeZone); case DATE: return getInternalDate(columnInfo, null, timeZone); case DECIMAL: return getInternalBigDecimal(columnInfo); case BLOB: case LONGBLOB: case MEDIUMBLOB: case TINYBLOB: byte[] dataBlob = new byte[getLengthMaxFieldSize()]; System.arraycopy(buf, pos, dataBlob, 0, getLengthMaxFieldSize()); return dataBlob; case NULL: return null; case YEAR: if (options.yearIsDateType) { return getInternalDate(columnInfo, null, timeZone); } return getInternalShort(columnInfo); case SMALLINT: case MEDIUMINT: return getInternalInt(columnInfo); case FLOAT: return getInternalFloat(columnInfo); case TIME: return getInternalTime(columnInfo, null, timeZone); case OLDDECIMAL: case JSON: return getInternalString(columnInfo, null, timeZone); case GEOMETRY: byte[] data = new byte[length]; System.arraycopy(buf, pos, data, 0, length); return data; case ENUM: break; case NEWDATE: break; case SET: break; default: break; } throw ExceptionMapper.getFeatureNotSupportedException( "Type '" + columnInfo.getColumnType().getTypeName() + "' is not supported"); }
java
public Object getInternalObject(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case BIT: if (columnInfo.getLength() == 1) { return buf[pos] != 0; } byte[] dataBit = new byte[length]; System.arraycopy(buf, pos, dataBit, 0, length); return dataBit; case TINYINT: if (options.tinyInt1isBit && columnInfo.getLength() == 1) { return buf[pos] != 0; } return getInternalInt(columnInfo); case INTEGER: if (!columnInfo.isSigned()) { return getInternalLong(columnInfo); } return getInternalInt(columnInfo); case BIGINT: if (!columnInfo.isSigned()) { return getInternalBigInteger(columnInfo); } return getInternalLong(columnInfo); case DOUBLE: return getInternalDouble(columnInfo); case VARCHAR: case VARSTRING: case STRING: if (columnInfo.isBinary()) { byte[] data = new byte[getLengthMaxFieldSize()]; System.arraycopy(buf, pos, data, 0, getLengthMaxFieldSize()); return data; } return getInternalString(columnInfo, null, timeZone); case TIMESTAMP: case DATETIME: return getInternalTimestamp(columnInfo, null, timeZone); case DATE: return getInternalDate(columnInfo, null, timeZone); case DECIMAL: return getInternalBigDecimal(columnInfo); case BLOB: case LONGBLOB: case MEDIUMBLOB: case TINYBLOB: byte[] dataBlob = new byte[getLengthMaxFieldSize()]; System.arraycopy(buf, pos, dataBlob, 0, getLengthMaxFieldSize()); return dataBlob; case NULL: return null; case YEAR: if (options.yearIsDateType) { return getInternalDate(columnInfo, null, timeZone); } return getInternalShort(columnInfo); case SMALLINT: case MEDIUMINT: return getInternalInt(columnInfo); case FLOAT: return getInternalFloat(columnInfo); case TIME: return getInternalTime(columnInfo, null, timeZone); case OLDDECIMAL: case JSON: return getInternalString(columnInfo, null, timeZone); case GEOMETRY: byte[] data = new byte[length]; System.arraycopy(buf, pos, data, 0, length); return data; case ENUM: break; case NEWDATE: break; case SET: break; default: break; } throw ExceptionMapper.getFeatureNotSupportedException( "Type '" + columnInfo.getColumnType().getTypeName() + "' is not supported"); }
[ "public", "Object", "getInternalObject", "(", "ColumnInformation", "columnInfo", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "switch", "(", "columnInfo", ".", "...
Get Object from raw binary format. @param columnInfo column information @param timeZone time zone @return Object value @throws SQLException if column type is not compatible
[ "Get", "Object", "from", "raw", "binary", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L982-L1068
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java
BinaryRowProtocol.getInternalBoolean
public boolean getInternalBoolean(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return false; } switch (columnInfo.getColumnType()) { case BIT: return parseBit() != 0; case TINYINT: return getInternalTinyInt(columnInfo) != 0; case SMALLINT: case YEAR: return getInternalSmallInt(columnInfo) != 0; case INTEGER: case MEDIUMINT: return getInternalMediumInt(columnInfo) != 0; case BIGINT: return getInternalLong(columnInfo) != 0; case FLOAT: return getInternalFloat(columnInfo) != 0; case DOUBLE: return getInternalDouble(columnInfo) != 0; case DECIMAL: case OLDDECIMAL: return getInternalBigDecimal(columnInfo).longValue() != 0; default: final String rawVal = new String(buf, pos, length, StandardCharsets.UTF_8); return !("false".equals(rawVal) || "0".equals(rawVal)); } }
java
public boolean getInternalBoolean(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return false; } switch (columnInfo.getColumnType()) { case BIT: return parseBit() != 0; case TINYINT: return getInternalTinyInt(columnInfo) != 0; case SMALLINT: case YEAR: return getInternalSmallInt(columnInfo) != 0; case INTEGER: case MEDIUMINT: return getInternalMediumInt(columnInfo) != 0; case BIGINT: return getInternalLong(columnInfo) != 0; case FLOAT: return getInternalFloat(columnInfo) != 0; case DOUBLE: return getInternalDouble(columnInfo) != 0; case DECIMAL: case OLDDECIMAL: return getInternalBigDecimal(columnInfo).longValue() != 0; default: final String rawVal = new String(buf, pos, length, StandardCharsets.UTF_8); return !("false".equals(rawVal) || "0".equals(rawVal)); } }
[ "public", "boolean", "getInternalBoolean", "(", "ColumnInformation", "columnInfo", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "false", ";", "}", "switch", "(", "columnInfo", ".", "getColumnType", "(", ")", ...
Get boolean from raw binary format. @param columnInfo column information @return boolean value @throws SQLException if column type doesn't permit conversion
[ "Get", "boolean", "from", "raw", "binary", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L1077-L1105
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java
BinaryRowProtocol.getInternalByte
public byte getInternalByte(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } long value; switch (columnInfo.getColumnType()) { case BIT: value = parseBit(); break; case TINYINT: value = getInternalTinyInt(columnInfo); break; case SMALLINT: case YEAR: value = getInternalSmallInt(columnInfo); break; case INTEGER: case MEDIUMINT: value = getInternalMediumInt(columnInfo); break; case BIGINT: value = getInternalLong(columnInfo); break; case FLOAT: value = (long) getInternalFloat(columnInfo); break; case DOUBLE: value = (long) getInternalDouble(columnInfo); break; case DECIMAL: case OLDDECIMAL: BigDecimal bigDecimal = getInternalBigDecimal(columnInfo); rangeCheck(Byte.class, Byte.MIN_VALUE, Byte.MAX_VALUE, bigDecimal, columnInfo); return bigDecimal.byteValue(); case VARSTRING: case VARCHAR: case STRING: value = Long.parseLong(new String(buf, pos, length, StandardCharsets.UTF_8)); break; default: throw new SQLException( "getByte not available for data field type " + columnInfo.getColumnType() .getJavaTypeName()); } rangeCheck(Byte.class, Byte.MIN_VALUE, Byte.MAX_VALUE, value, columnInfo); return (byte) value; }
java
public byte getInternalByte(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } long value; switch (columnInfo.getColumnType()) { case BIT: value = parseBit(); break; case TINYINT: value = getInternalTinyInt(columnInfo); break; case SMALLINT: case YEAR: value = getInternalSmallInt(columnInfo); break; case INTEGER: case MEDIUMINT: value = getInternalMediumInt(columnInfo); break; case BIGINT: value = getInternalLong(columnInfo); break; case FLOAT: value = (long) getInternalFloat(columnInfo); break; case DOUBLE: value = (long) getInternalDouble(columnInfo); break; case DECIMAL: case OLDDECIMAL: BigDecimal bigDecimal = getInternalBigDecimal(columnInfo); rangeCheck(Byte.class, Byte.MIN_VALUE, Byte.MAX_VALUE, bigDecimal, columnInfo); return bigDecimal.byteValue(); case VARSTRING: case VARCHAR: case STRING: value = Long.parseLong(new String(buf, pos, length, StandardCharsets.UTF_8)); break; default: throw new SQLException( "getByte not available for data field type " + columnInfo.getColumnType() .getJavaTypeName()); } rangeCheck(Byte.class, Byte.MIN_VALUE, Byte.MAX_VALUE, value, columnInfo); return (byte) value; }
[ "public", "byte", "getInternalByte", "(", "ColumnInformation", "columnInfo", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "0", ";", "}", "long", "value", ";", "switch", "(", "columnInfo", ".", "getColumnType"...
Get byte from raw binary format. @param columnInfo column information @return byte value @throws SQLException if column type doesn't permit conversion
[ "Get", "byte", "from", "raw", "binary", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L1114-L1160
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java
BinaryRowProtocol.getInternalTimeString
public String getInternalTimeString(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } if (length == 0) { // binary send 00:00:00 as 0. if (columnInfo.getDecimals() == 0) { return "00:00:00"; } else { StringBuilder value = new StringBuilder("00:00:00."); int decimal = columnInfo.getDecimals(); while (decimal-- > 0) { value.append("0"); } return value.toString(); } } String rawValue = new String(buf, pos, length, StandardCharsets.UTF_8); if ("0000-00-00".equals(rawValue)) { return null; } int day = ((buf[pos + 1] & 0xff) | ((buf[pos + 2] & 0xff) << 8) | ((buf[pos + 3] & 0xff) << 16) | ((buf[pos + 4] & 0xff) << 24)); int hour = buf[pos + 5]; int timeHour = hour + day * 24; String hourString; if (timeHour < 10) { hourString = "0" + timeHour; } else { hourString = Integer.toString(timeHour); } String minuteString; int minutes = buf[pos + 6]; if (minutes < 10) { minuteString = "0" + minutes; } else { minuteString = Integer.toString(minutes); } String secondString; int seconds = buf[pos + 7]; if (seconds < 10) { secondString = "0" + seconds; } else { secondString = Integer.toString(seconds); } int microseconds = 0; if (length > 8) { microseconds = ((buf[pos + 8] & 0xff) | (buf[pos + 9] & 0xff) << 8 | (buf[pos + 10] & 0xff) << 16 | (buf[pos + 11] & 0xff) << 24); } StringBuilder microsecondString = new StringBuilder(Integer.toString(microseconds)); while (microsecondString.length() < 6) { microsecondString.insert(0, "0"); } boolean negative = (buf[pos] == 0x01); return (negative ? "-" : "") + (hourString + ":" + minuteString + ":" + secondString + "." + microsecondString); }
java
public String getInternalTimeString(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } if (length == 0) { // binary send 00:00:00 as 0. if (columnInfo.getDecimals() == 0) { return "00:00:00"; } else { StringBuilder value = new StringBuilder("00:00:00."); int decimal = columnInfo.getDecimals(); while (decimal-- > 0) { value.append("0"); } return value.toString(); } } String rawValue = new String(buf, pos, length, StandardCharsets.UTF_8); if ("0000-00-00".equals(rawValue)) { return null; } int day = ((buf[pos + 1] & 0xff) | ((buf[pos + 2] & 0xff) << 8) | ((buf[pos + 3] & 0xff) << 16) | ((buf[pos + 4] & 0xff) << 24)); int hour = buf[pos + 5]; int timeHour = hour + day * 24; String hourString; if (timeHour < 10) { hourString = "0" + timeHour; } else { hourString = Integer.toString(timeHour); } String minuteString; int minutes = buf[pos + 6]; if (minutes < 10) { minuteString = "0" + minutes; } else { minuteString = Integer.toString(minutes); } String secondString; int seconds = buf[pos + 7]; if (seconds < 10) { secondString = "0" + seconds; } else { secondString = Integer.toString(seconds); } int microseconds = 0; if (length > 8) { microseconds = ((buf[pos + 8] & 0xff) | (buf[pos + 9] & 0xff) << 8 | (buf[pos + 10] & 0xff) << 16 | (buf[pos + 11] & 0xff) << 24); } StringBuilder microsecondString = new StringBuilder(Integer.toString(microseconds)); while (microsecondString.length() < 6) { microsecondString.insert(0, "0"); } boolean negative = (buf[pos] == 0x01); return (negative ? "-" : "") + (hourString + ":" + minuteString + ":" + secondString + "." + microsecondString); }
[ "public", "String", "getInternalTimeString", "(", "ColumnInformation", "columnInfo", ")", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "length", "==", "0", ")", "{", "// binary send 00:00:00 as 0.", "if", "(", ...
Get Time in string format from raw binary format. @param columnInfo column information @return time value
[ "Get", "Time", "in", "string", "format", "from", "raw", "binary", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L1228-L1295
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java
BinaryRowProtocol.getInternalZonedDateTime
public ZonedDateTime getInternalZonedDateTime(ColumnInformation columnInfo, Class clazz, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } switch (columnInfo.getColumnType().getSqlType()) { case Types.TIMESTAMP: int year = ((buf[pos] & 0xff) | (buf[pos + 1] & 0xff) << 8); int month = buf[pos + 2]; int day = buf[pos + 3]; int hour = 0; int minutes = 0; int seconds = 0; int microseconds = 0; if (length > 4) { hour = buf[pos + 4]; minutes = buf[pos + 5]; seconds = buf[pos + 6]; if (length > 7) { microseconds = ((buf[pos + 7] & 0xff) + ((buf[pos + 8] & 0xff) << 8) + ((buf[pos + 9] & 0xff) << 16) + ((buf[pos + 10] & 0xff) << 24)); } } return ZonedDateTime .of(year, month, day, hour, minutes, seconds, microseconds * 1000, timeZone.toZoneId()); case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: //string conversion String raw = new String(buf, pos, length, StandardCharsets.UTF_8); if (raw.startsWith("0000-00-00 00:00:00")) { return null; } try { return ZonedDateTime.parse(raw, TEXT_ZONED_DATE_TIME); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as ZonedDateTime. time must have \"yyyy-MM-dd[T/ ]HH:mm:ss[.S]\" " + "with offset and timezone format (example : '2011-12-03 10:15:30+01:00[Europe/Paris]')"); } default: throw new SQLException( "Cannot read " + clazz.getName() + " using a " + columnInfo.getColumnType() .getJavaTypeName() + " field"); } }
java
public ZonedDateTime getInternalZonedDateTime(ColumnInformation columnInfo, Class clazz, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } switch (columnInfo.getColumnType().getSqlType()) { case Types.TIMESTAMP: int year = ((buf[pos] & 0xff) | (buf[pos + 1] & 0xff) << 8); int month = buf[pos + 2]; int day = buf[pos + 3]; int hour = 0; int minutes = 0; int seconds = 0; int microseconds = 0; if (length > 4) { hour = buf[pos + 4]; minutes = buf[pos + 5]; seconds = buf[pos + 6]; if (length > 7) { microseconds = ((buf[pos + 7] & 0xff) + ((buf[pos + 8] & 0xff) << 8) + ((buf[pos + 9] & 0xff) << 16) + ((buf[pos + 10] & 0xff) << 24)); } } return ZonedDateTime .of(year, month, day, hour, minutes, seconds, microseconds * 1000, timeZone.toZoneId()); case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: //string conversion String raw = new String(buf, pos, length, StandardCharsets.UTF_8); if (raw.startsWith("0000-00-00 00:00:00")) { return null; } try { return ZonedDateTime.parse(raw, TEXT_ZONED_DATE_TIME); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as ZonedDateTime. time must have \"yyyy-MM-dd[T/ ]HH:mm:ss[.S]\" " + "with offset and timezone format (example : '2011-12-03 10:15:30+01:00[Europe/Paris]')"); } default: throw new SQLException( "Cannot read " + clazz.getName() + " using a " + columnInfo.getColumnType() .getJavaTypeName() + " field"); } }
[ "public", "ZonedDateTime", "getInternalZonedDateTime", "(", "ColumnInformation", "columnInfo", ",", "Class", "clazz", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", ...
Get ZonedDateTime from raw binary format. @param columnInfo column information @param clazz asked class @param timeZone time zone @return ZonedDateTime value @throws SQLException if column type doesn't permit conversion
[ "Get", "ZonedDateTime", "from", "raw", "binary", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L1367-L1427
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java
BinaryRowProtocol.getInternalLocalTime
public LocalTime getInternalLocalTime(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } switch (columnInfo.getColumnType().getSqlType()) { case Types.TIME: int day = 0; int hour = 0; int minutes = 0; int seconds = 0; int microseconds = 0; final boolean negate = (buf[pos] & 0xff) == 0x01; if (length > 4) { day = ((buf[pos + 1] & 0xff) + ((buf[pos + 2] & 0xff) << 8) + ((buf[pos + 3] & 0xff) << 16) + ((buf[pos + 4] & 0xff) << 24)); } if (length > 7) { hour = buf[pos + 5]; minutes = buf[pos + 6]; seconds = buf[pos + 7]; } if (length > 8) { microseconds = ((buf[pos + 8] & 0xff) + ((buf[pos + 9] & 0xff) << 8) + ((buf[pos + 10] & 0xff) << 16) + ((buf[pos + 11] & 0xff) << 24)); } return LocalTime .of((negate ? -1 : 1) * (day * 24 + hour), minutes, seconds, microseconds * 1000); case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: //string conversion String raw = new String(buf, pos, length, StandardCharsets.UTF_8); try { return LocalTime .parse(raw, DateTimeFormatter.ISO_LOCAL_TIME.withZone(timeZone.toZoneId())); } catch (DateTimeParseException dateParserEx) { throw new SQLException( raw + " cannot be parse as LocalTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo.getColumnType() + "\")"); } case Types.TIMESTAMP: ZonedDateTime zonedDateTime = getInternalZonedDateTime(columnInfo, LocalTime.class, timeZone); return zonedDateTime == null ? null : zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalTime(); default: throw new SQLException( "Cannot read LocalTime using a " + columnInfo.getColumnType().getJavaTypeName() + " field"); } }
java
public LocalTime getInternalLocalTime(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } switch (columnInfo.getColumnType().getSqlType()) { case Types.TIME: int day = 0; int hour = 0; int minutes = 0; int seconds = 0; int microseconds = 0; final boolean negate = (buf[pos] & 0xff) == 0x01; if (length > 4) { day = ((buf[pos + 1] & 0xff) + ((buf[pos + 2] & 0xff) << 8) + ((buf[pos + 3] & 0xff) << 16) + ((buf[pos + 4] & 0xff) << 24)); } if (length > 7) { hour = buf[pos + 5]; minutes = buf[pos + 6]; seconds = buf[pos + 7]; } if (length > 8) { microseconds = ((buf[pos + 8] & 0xff) + ((buf[pos + 9] & 0xff) << 8) + ((buf[pos + 10] & 0xff) << 16) + ((buf[pos + 11] & 0xff) << 24)); } return LocalTime .of((negate ? -1 : 1) * (day * 24 + hour), minutes, seconds, microseconds * 1000); case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: //string conversion String raw = new String(buf, pos, length, StandardCharsets.UTF_8); try { return LocalTime .parse(raw, DateTimeFormatter.ISO_LOCAL_TIME.withZone(timeZone.toZoneId())); } catch (DateTimeParseException dateParserEx) { throw new SQLException( raw + " cannot be parse as LocalTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo.getColumnType() + "\")"); } case Types.TIMESTAMP: ZonedDateTime zonedDateTime = getInternalZonedDateTime(columnInfo, LocalTime.class, timeZone); return zonedDateTime == null ? null : zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalTime(); default: throw new SQLException( "Cannot read LocalTime using a " + columnInfo.getColumnType().getJavaTypeName() + " field"); } }
[ "public", "LocalTime", "getInternalLocalTime", "(", "ColumnInformation", "columnInfo", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "length", "==", "0...
Get LocalTime from raw binary format. @param columnInfo column information @param timeZone time zone @return LocalTime value @throws SQLException if column type doesn't permit conversion
[ "Get", "LocalTime", "from", "raw", "binary", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/BinaryRowProtocol.java#L1548-L1618
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pools.java
Pools.retrievePool
public static Pool retrievePool(UrlParser urlParser) { if (!poolMap.containsKey(urlParser)) { synchronized (poolMap) { if (!poolMap.containsKey(urlParser)) { if (poolExecutor == null) { poolExecutor = new ScheduledThreadPoolExecutor(1, new MariaDbThreadFactory("MariaDbPool-maxTimeoutIdle-checker")); } Pool pool = new Pool(urlParser, poolIndex.incrementAndGet(), poolExecutor); poolMap.put(urlParser, pool); return pool; } } } return poolMap.get(urlParser); }
java
public static Pool retrievePool(UrlParser urlParser) { if (!poolMap.containsKey(urlParser)) { synchronized (poolMap) { if (!poolMap.containsKey(urlParser)) { if (poolExecutor == null) { poolExecutor = new ScheduledThreadPoolExecutor(1, new MariaDbThreadFactory("MariaDbPool-maxTimeoutIdle-checker")); } Pool pool = new Pool(urlParser, poolIndex.incrementAndGet(), poolExecutor); poolMap.put(urlParser, pool); return pool; } } } return poolMap.get(urlParser); }
[ "public", "static", "Pool", "retrievePool", "(", "UrlParser", "urlParser", ")", "{", "if", "(", "!", "poolMap", ".", "containsKey", "(", "urlParser", ")", ")", "{", "synchronized", "(", "poolMap", ")", "{", "if", "(", "!", "poolMap", ".", "containsKey", ...
Get existing pool for a configuration. Create it if doesn't exists. @param urlParser configuration parser @return pool
[ "Get", "existing", "pool", "for", "a", "configuration", ".", "Create", "it", "if", "doesn", "t", "exists", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pools.java#L45-L60
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pools.java
Pools.remove
public static void remove(Pool pool) { if (poolMap.containsKey(pool.getUrlParser())) { synchronized (poolMap) { if (poolMap.containsKey(pool.getUrlParser())) { poolMap.remove(pool.getUrlParser()); shutdownExecutor(); } } } }
java
public static void remove(Pool pool) { if (poolMap.containsKey(pool.getUrlParser())) { synchronized (poolMap) { if (poolMap.containsKey(pool.getUrlParser())) { poolMap.remove(pool.getUrlParser()); shutdownExecutor(); } } } }
[ "public", "static", "void", "remove", "(", "Pool", "pool", ")", "{", "if", "(", "poolMap", ".", "containsKey", "(", "pool", ".", "getUrlParser", "(", ")", ")", ")", "{", "synchronized", "(", "poolMap", ")", "{", "if", "(", "poolMap", ".", "containsKey"...
Remove pool. @param pool pool to remove
[ "Remove", "pool", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pools.java#L67-L76
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pools.java
Pools.close
public static void close() { synchronized (poolMap) { for (Pool pool : poolMap.values()) { try { pool.close(); } catch (InterruptedException exception) { //eat } } shutdownExecutor(); poolMap.clear(); } }
java
public static void close() { synchronized (poolMap) { for (Pool pool : poolMap.values()) { try { pool.close(); } catch (InterruptedException exception) { //eat } } shutdownExecutor(); poolMap.clear(); } }
[ "public", "static", "void", "close", "(", ")", "{", "synchronized", "(", "poolMap", ")", "{", "for", "(", "Pool", "pool", ":", "poolMap", ".", "values", "(", ")", ")", "{", "try", "{", "pool", ".", "close", "(", ")", ";", "}", "catch", "(", "Inte...
Close all pools.
[ "Close", "all", "pools", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pools.java#L81-L93
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pools.java
Pools.close
public static void close(String poolName) { if (poolName == null) { return; } synchronized (poolMap) { for (Pool pool : poolMap.values()) { if (poolName.equals(pool.getUrlParser().getOptions().poolName)) { try { pool.close(); } catch (InterruptedException exception) { //eat } poolMap.remove(pool.getUrlParser()); return; } } if (poolMap.isEmpty()) { shutdownExecutor(); } } }
java
public static void close(String poolName) { if (poolName == null) { return; } synchronized (poolMap) { for (Pool pool : poolMap.values()) { if (poolName.equals(pool.getUrlParser().getOptions().poolName)) { try { pool.close(); } catch (InterruptedException exception) { //eat } poolMap.remove(pool.getUrlParser()); return; } } if (poolMap.isEmpty()) { shutdownExecutor(); } } }
[ "public", "static", "void", "close", "(", "String", "poolName", ")", "{", "if", "(", "poolName", "==", "null", ")", "{", "return", ";", "}", "synchronized", "(", "poolMap", ")", "{", "for", "(", "Pool", "pool", ":", "poolMap", ".", "values", "(", ")"...
Closing a pool with name defined in url. @param poolName the option "poolName" value
[ "Closing", "a", "pool", "with", "name", "defined", "in", "url", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pools.java#L100-L121
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/input/ReadAheadBufferedStream.java
ReadAheadBufferedStream.read
public synchronized int read(byte[] externalBuf, int off, int len) throws IOException { if (len == 0) { return 0; } int totalReads = 0; while (true) { //read if (end - pos <= 0) { if (len - totalReads >= buf.length) { //buffer length is less than asked byte and buffer is empty // => filling directly into external buffer int reads = super.read(externalBuf, off + totalReads, len - totalReads); if (reads <= 0) { return (totalReads == 0) ? -1 : totalReads; } return totalReads + reads; } else { //filling internal buffer fillBuffer(len - totalReads); if (end <= 0) { return (totalReads == 0) ? -1 : totalReads; } } } //copy internal value to buffer. int copyLength = Math.min(len - totalReads, end - pos); System.arraycopy(buf, pos, externalBuf, off + totalReads, copyLength); pos += copyLength; totalReads += copyLength; if (totalReads >= len || super.available() <= 0) { return totalReads; } } }
java
public synchronized int read(byte[] externalBuf, int off, int len) throws IOException { if (len == 0) { return 0; } int totalReads = 0; while (true) { //read if (end - pos <= 0) { if (len - totalReads >= buf.length) { //buffer length is less than asked byte and buffer is empty // => filling directly into external buffer int reads = super.read(externalBuf, off + totalReads, len - totalReads); if (reads <= 0) { return (totalReads == 0) ? -1 : totalReads; } return totalReads + reads; } else { //filling internal buffer fillBuffer(len - totalReads); if (end <= 0) { return (totalReads == 0) ? -1 : totalReads; } } } //copy internal value to buffer. int copyLength = Math.min(len - totalReads, end - pos); System.arraycopy(buf, pos, externalBuf, off + totalReads, copyLength); pos += copyLength; totalReads += copyLength; if (totalReads >= len || super.available() <= 0) { return totalReads; } } }
[ "public", "synchronized", "int", "read", "(", "byte", "[", "]", "externalBuf", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "len", "==", "0", ")", "{", "return", "0", ";", "}", "int", "totalReads", "=", "0", "...
Returing byte array, from cache of reading socket if needed. @param externalBuf buffer to fill @param off offset @param len length to read @return number of added bytes @throws IOException if exception during socket reading
[ "Returing", "byte", "array", "from", "cache", "of", "reading", "socket", "if", "needed", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/input/ReadAheadBufferedStream.java#L80-L120
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/input/ReadAheadBufferedStream.java
ReadAheadBufferedStream.fillBuffer
private void fillBuffer(int minNeededBytes) throws IOException { int lengthToReallyRead = Math.min(BUF_SIZE, Math.max(super.available(), minNeededBytes)); end = super.read(buf, 0, lengthToReallyRead); pos = 0; }
java
private void fillBuffer(int minNeededBytes) throws IOException { int lengthToReallyRead = Math.min(BUF_SIZE, Math.max(super.available(), minNeededBytes)); end = super.read(buf, 0, lengthToReallyRead); pos = 0; }
[ "private", "void", "fillBuffer", "(", "int", "minNeededBytes", ")", "throws", "IOException", "{", "int", "lengthToReallyRead", "=", "Math", ".", "min", "(", "BUF_SIZE", ",", "Math", ".", "max", "(", "super", ".", "available", "(", ")", ",", "minNeededBytes",...
Fill buffer with required length, or available bytes. @param minNeededBytes asked number of bytes @throws IOException in case of failing reading stream.
[ "Fill", "buffer", "with", "required", "length", "or", "available", "bytes", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/input/ReadAheadBufferedStream.java#L128-L132
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/tls/MariaDbX509TrustManager.java
MariaDbX509TrustManager.checkClientTrusted
@Override public void checkClientTrusted(X509Certificate[] x509Certificates, String string) throws CertificateException { if (trustManager == null) { return; } trustManager.checkClientTrusted(x509Certificates, string); }
java
@Override public void checkClientTrusted(X509Certificate[] x509Certificates, String string) throws CertificateException { if (trustManager == null) { return; } trustManager.checkClientTrusted(x509Certificates, string); }
[ "@", "Override", "public", "void", "checkClientTrusted", "(", "X509Certificate", "[", "]", "x509Certificates", ",", "String", "string", ")", "throws", "CertificateException", "{", "if", "(", "trustManager", "==", "null", ")", "{", "return", ";", "}", "trustManag...
Check client trusted. @param x509Certificates certificate @param string string @throws CertificateException exception
[ "Check", "client", "trusted", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/tls/MariaDbX509TrustManager.java#L203-L210
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java
Pool.addConnectionRequest
private void addConnectionRequest() { if (totalConnection.get() < options.maxPoolSize && poolState.get() == POOL_STATE_OK) { //ensure to have one worker if was timeout connectionAppender.prestartCoreThread(); connectionAppenderQueue.offer(() -> { if ((totalConnection.get() < options.minPoolSize || pendingRequestNumber.get() > 0) && totalConnection.get() < options.maxPoolSize) { try { addConnection(); } catch (SQLException sqle) { //eat } } }); } }
java
private void addConnectionRequest() { if (totalConnection.get() < options.maxPoolSize && poolState.get() == POOL_STATE_OK) { //ensure to have one worker if was timeout connectionAppender.prestartCoreThread(); connectionAppenderQueue.offer(() -> { if ((totalConnection.get() < options.minPoolSize || pendingRequestNumber.get() > 0) && totalConnection.get() < options.maxPoolSize) { try { addConnection(); } catch (SQLException sqle) { //eat } } }); } }
[ "private", "void", "addConnectionRequest", "(", ")", "{", "if", "(", "totalConnection", ".", "get", "(", ")", "<", "options", ".", "maxPoolSize", "&&", "poolState", ".", "get", "(", ")", "==", "POOL_STATE_OK", ")", "{", "//ensure to have one worker if was timeou...
Add new connection if needed. Only one thread create new connection, so new connection request will wait to newly created connection or for a released connection.
[ "Add", "new", "connection", "if", "needed", ".", "Only", "one", "thread", "create", "new", "connection", "so", "new", "connection", "request", "will", "wait", "to", "newly", "created", "connection", "or", "for", "a", "released", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java#L140-L157
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java
Pool.removeIdleTimeoutConnection
private void removeIdleTimeoutConnection() { //descending iterator since first from queue are the first to be used Iterator<MariaDbPooledConnection> iterator = idleConnections.descendingIterator(); MariaDbPooledConnection item; while (iterator.hasNext()) { item = iterator.next(); long idleTime = System.nanoTime() - item.getLastUsed().get(); boolean timedOut = idleTime > TimeUnit.SECONDS.toNanos(maxIdleTime); boolean shouldBeReleased = false; if (globalInfo != null) { // idle time is reaching server @@wait_timeout if (idleTime > TimeUnit.SECONDS.toNanos(globalInfo.getWaitTimeout() - 45)) { shouldBeReleased = true; } // idle has reach option maxIdleTime value and pool has more connections than minPoolSiz if (timedOut && totalConnection.get() > options.minPoolSize) { shouldBeReleased = true; } } else if (timedOut) { shouldBeReleased = true; } if (shouldBeReleased && idleConnections.remove(item)) { totalConnection.decrementAndGet(); silentCloseConnection(item); addConnectionRequest(); if (logger.isDebugEnabled()) { logger.debug( "pool {} connection removed due to inactivity (total:{}, active:{}, pending:{})", poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get()); } } } }
java
private void removeIdleTimeoutConnection() { //descending iterator since first from queue are the first to be used Iterator<MariaDbPooledConnection> iterator = idleConnections.descendingIterator(); MariaDbPooledConnection item; while (iterator.hasNext()) { item = iterator.next(); long idleTime = System.nanoTime() - item.getLastUsed().get(); boolean timedOut = idleTime > TimeUnit.SECONDS.toNanos(maxIdleTime); boolean shouldBeReleased = false; if (globalInfo != null) { // idle time is reaching server @@wait_timeout if (idleTime > TimeUnit.SECONDS.toNanos(globalInfo.getWaitTimeout() - 45)) { shouldBeReleased = true; } // idle has reach option maxIdleTime value and pool has more connections than minPoolSiz if (timedOut && totalConnection.get() > options.minPoolSize) { shouldBeReleased = true; } } else if (timedOut) { shouldBeReleased = true; } if (shouldBeReleased && idleConnections.remove(item)) { totalConnection.decrementAndGet(); silentCloseConnection(item); addConnectionRequest(); if (logger.isDebugEnabled()) { logger.debug( "pool {} connection removed due to inactivity (total:{}, active:{}, pending:{})", poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get()); } } } }
[ "private", "void", "removeIdleTimeoutConnection", "(", ")", "{", "//descending iterator since first from queue are the first to be used", "Iterator", "<", "MariaDbPooledConnection", ">", "iterator", "=", "idleConnections", ".", "descendingIterator", "(", ")", ";", "MariaDbPoole...
Removing idle connection. Close them and recreate connection to reach minimal number of connection.
[ "Removing", "idle", "connection", ".", "Close", "them", "and", "recreate", "connection", "to", "reach", "minimal", "number", "of", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java#L163-L208
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java
Pool.addConnection
private void addConnection() throws SQLException { //create new connection Protocol protocol = Utils.retrieveProxy(urlParser, globalInfo); MariaDbConnection connection = new MariaDbConnection(protocol); MariaDbPooledConnection pooledConnection = createPoolConnection(connection); if (options.staticGlobal) { //on first connection load initial state if (globalInfo == null) { initializePoolGlobalState(connection); } //set default transaction isolation level to permit resetting to initial state connection.setDefaultTransactionIsolation(globalInfo.getDefaultTransactionIsolation()); } else { //set default transaction isolation level to permit resetting to initial state connection.setDefaultTransactionIsolation(connection.getTransactionIsolation()); } if (poolState.get() == POOL_STATE_OK && totalConnection.incrementAndGet() <= options.maxPoolSize) { idleConnections.addFirst(pooledConnection); if (logger.isDebugEnabled()) { logger.debug("pool {} new physical connection created (total:{}, active:{}, pending:{})", poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get()); } return; } silentCloseConnection(pooledConnection); }
java
private void addConnection() throws SQLException { //create new connection Protocol protocol = Utils.retrieveProxy(urlParser, globalInfo); MariaDbConnection connection = new MariaDbConnection(protocol); MariaDbPooledConnection pooledConnection = createPoolConnection(connection); if (options.staticGlobal) { //on first connection load initial state if (globalInfo == null) { initializePoolGlobalState(connection); } //set default transaction isolation level to permit resetting to initial state connection.setDefaultTransactionIsolation(globalInfo.getDefaultTransactionIsolation()); } else { //set default transaction isolation level to permit resetting to initial state connection.setDefaultTransactionIsolation(connection.getTransactionIsolation()); } if (poolState.get() == POOL_STATE_OK && totalConnection.incrementAndGet() <= options.maxPoolSize) { idleConnections.addFirst(pooledConnection); if (logger.isDebugEnabled()) { logger.debug("pool {} new physical connection created (total:{}, active:{}, pending:{})", poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get()); } return; } silentCloseConnection(pooledConnection); }
[ "private", "void", "addConnection", "(", ")", "throws", "SQLException", "{", "//create new connection", "Protocol", "protocol", "=", "Utils", ".", "retrieveProxy", "(", "urlParser", ",", "globalInfo", ")", ";", "MariaDbConnection", "connection", "=", "new", "MariaDb...
Create new connection. @throws SQLException if connection creation failed
[ "Create", "new", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java#L215-L246
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java
Pool.getIdleConnection
private MariaDbPooledConnection getIdleConnection(long timeout, TimeUnit timeUnit) throws InterruptedException { while (true) { MariaDbPooledConnection item = (timeout == 0) ? idleConnections.pollFirst() : idleConnections.pollFirst(timeout, timeUnit); if (item != null) { MariaDbConnection connection = item.getConnection(); try { if (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - item.getLastUsed().get()) > options.poolValidMinDelay) { //validate connection if (connection.isValid(10)) { //10 seconds timeout item.lastUsedToNow(); return item; } } else { // connection has been retrieved recently -> skip connection validation item.lastUsedToNow(); return item; } } catch (SQLException sqle) { //eat } totalConnection.decrementAndGet(); // validation failed silentAbortConnection(item); addConnectionRequest(); if (logger.isDebugEnabled()) { logger.debug( "pool {} connection removed from pool due to failed validation (total:{}, active:{}, pending:{})", poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get()); } continue; } return null; } }
java
private MariaDbPooledConnection getIdleConnection(long timeout, TimeUnit timeUnit) throws InterruptedException { while (true) { MariaDbPooledConnection item = (timeout == 0) ? idleConnections.pollFirst() : idleConnections.pollFirst(timeout, timeUnit); if (item != null) { MariaDbConnection connection = item.getConnection(); try { if (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - item.getLastUsed().get()) > options.poolValidMinDelay) { //validate connection if (connection.isValid(10)) { //10 seconds timeout item.lastUsedToNow(); return item; } } else { // connection has been retrieved recently -> skip connection validation item.lastUsedToNow(); return item; } } catch (SQLException sqle) { //eat } totalConnection.decrementAndGet(); // validation failed silentAbortConnection(item); addConnectionRequest(); if (logger.isDebugEnabled()) { logger.debug( "pool {} connection removed from pool due to failed validation (total:{}, active:{}, pending:{})", poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get()); } continue; } return null; } }
[ "private", "MariaDbPooledConnection", "getIdleConnection", "(", "long", "timeout", ",", "TimeUnit", "timeUnit", ")", "throws", "InterruptedException", "{", "while", "(", "true", ")", "{", "MariaDbPooledConnection", "item", "=", "(", "timeout", "==", "0", ")", "?",...
Get an existing idle connection in pool. @return an IDLE connection.
[ "Get", "an", "existing", "idle", "connection", "in", "pool", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java#L257-L304
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java
Pool.getConnection
public MariaDbConnection getConnection(String username, String password) throws SQLException { try { if ((urlParser.getUsername() != null ? urlParser.getUsername().equals(username) : username == null) && (urlParser.getPassword() != null ? urlParser.getPassword().equals(password) : password == null)) { return getConnection(); } UrlParser tmpUrlParser = (UrlParser) urlParser.clone(); tmpUrlParser.setUsername(username); tmpUrlParser.setPassword(password); Protocol protocol = Utils.retrieveProxy(tmpUrlParser, globalInfo); return new MariaDbConnection(protocol); } catch (CloneNotSupportedException cloneException) { //cannot occur throw new SQLException("Error getting connection, parameters cannot be cloned", cloneException); } }
java
public MariaDbConnection getConnection(String username, String password) throws SQLException { try { if ((urlParser.getUsername() != null ? urlParser.getUsername().equals(username) : username == null) && (urlParser.getPassword() != null ? urlParser.getPassword().equals(password) : password == null)) { return getConnection(); } UrlParser tmpUrlParser = (UrlParser) urlParser.clone(); tmpUrlParser.setUsername(username); tmpUrlParser.setPassword(password); Protocol protocol = Utils.retrieveProxy(tmpUrlParser, globalInfo); return new MariaDbConnection(protocol); } catch (CloneNotSupportedException cloneException) { //cannot occur throw new SQLException("Error getting connection, parameters cannot be cloned", cloneException); } }
[ "public", "MariaDbConnection", "getConnection", "(", "String", "username", ",", "String", "password", ")", "throws", "SQLException", "{", "try", "{", "if", "(", "(", "urlParser", ".", "getUsername", "(", ")", "!=", "null", "?", "urlParser", ".", "getUsername",...
Get new connection from pool if user and password correspond to pool. If username and password are different from pool, will return a dedicated connection. @param username username @param password password @return connection @throws SQLException if any error occur during connection
[ "Get", "new", "connection", "from", "pool", "if", "user", "and", "password", "correspond", "to", "pool", ".", "If", "username", "and", "password", "are", "different", "from", "pool", "will", "return", "a", "dedicated", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java#L425-L447
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java
Pool.close
public void close() throws InterruptedException { synchronized (this) { Pools.remove(this); poolState.set(POOL_STATE_CLOSING); pendingRequestNumber.set(0); scheduledFuture.cancel(false); connectionAppender.shutdown(); try { connectionAppender.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException i) { //eat } if (logger.isInfoEnabled()) { logger.info("closing pool {} (total:{}, active:{}, pending:{})", poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get()); } ExecutorService connectionRemover = new ThreadPoolExecutor(totalConnection.get(), options.maxPoolSize, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(options.maxPoolSize), new MariaDbThreadFactory(poolTag + "-destroyer")); //loop for up to 10 seconds to close not used connection long start = System.nanoTime(); do { closeAll(connectionRemover, idleConnections); if (totalConnection.get() > 0) { Thread.sleep(0, 10_00); } } while (totalConnection.get() > 0 && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start) < 10); //after having wait for 10 seconds, force removal, even if used connections if (totalConnection.get() > 0 || idleConnections.isEmpty()) { closeAll(connectionRemover, idleConnections); } connectionRemover.shutdown(); try { unRegisterJmx(); } catch (Exception exception) { //eat } connectionRemover.awaitTermination(10, TimeUnit.SECONDS); } }
java
public void close() throws InterruptedException { synchronized (this) { Pools.remove(this); poolState.set(POOL_STATE_CLOSING); pendingRequestNumber.set(0); scheduledFuture.cancel(false); connectionAppender.shutdown(); try { connectionAppender.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException i) { //eat } if (logger.isInfoEnabled()) { logger.info("closing pool {} (total:{}, active:{}, pending:{})", poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get()); } ExecutorService connectionRemover = new ThreadPoolExecutor(totalConnection.get(), options.maxPoolSize, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(options.maxPoolSize), new MariaDbThreadFactory(poolTag + "-destroyer")); //loop for up to 10 seconds to close not used connection long start = System.nanoTime(); do { closeAll(connectionRemover, idleConnections); if (totalConnection.get() > 0) { Thread.sleep(0, 10_00); } } while (totalConnection.get() > 0 && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start) < 10); //after having wait for 10 seconds, force removal, even if used connections if (totalConnection.get() > 0 || idleConnections.isEmpty()) { closeAll(connectionRemover, idleConnections); } connectionRemover.shutdown(); try { unRegisterJmx(); } catch (Exception exception) { //eat } connectionRemover.awaitTermination(10, TimeUnit.SECONDS); } }
[ "public", "void", "close", "(", ")", "throws", "InterruptedException", "{", "synchronized", "(", "this", ")", "{", "Pools", ".", "remove", "(", "this", ")", ";", "poolState", ".", "set", "(", "POOL_STATE_CLOSING", ")", ";", "pendingRequestNumber", ".", "set"...
Close pool and underlying connections. @throws InterruptedException if interrupted
[ "Close", "pool", "and", "underlying", "connections", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/pool/Pool.java#L465-L513
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java
AbstractMastersListener.addToBlacklist
public void addToBlacklist(HostAddress hostAddress) { if (hostAddress != null && !isExplicitClosed()) { blacklist.putIfAbsent(hostAddress, System.nanoTime()); } }
java
public void addToBlacklist(HostAddress hostAddress) { if (hostAddress != null && !isExplicitClosed()) { blacklist.putIfAbsent(hostAddress, System.nanoTime()); } }
[ "public", "void", "addToBlacklist", "(", "HostAddress", "hostAddress", ")", "{", "if", "(", "hostAddress", "!=", "null", "&&", "!", "isExplicitClosed", "(", ")", ")", "{", "blacklist", ".", "putIfAbsent", "(", "hostAddress", ",", "System", ".", "nanoTime", "...
After a failover, put the hostAddress in a static list so the other connection will not take this host in account for a time. @param hostAddress the HostAddress to add to blacklist
[ "After", "a", "failover", "put", "the", "hostAddress", "in", "a", "static", "list", "so", "the", "other", "connection", "will", "not", "take", "this", "host", "in", "account", "for", "a", "time", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java#L212-L216
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java
AbstractMastersListener.resetOldsBlackListHosts
public void resetOldsBlackListHosts() { long currentTimeNanos = System.nanoTime(); Set<Map.Entry<HostAddress, Long>> entries = blacklist.entrySet(); for (Map.Entry<HostAddress, Long> blEntry : entries) { long entryNanos = blEntry.getValue(); long durationSeconds = TimeUnit.NANOSECONDS.toSeconds(currentTimeNanos - entryNanos); if (durationSeconds >= urlParser.getOptions().loadBalanceBlacklistTimeout) { blacklist.remove(blEntry.getKey(), entryNanos); } } }
java
public void resetOldsBlackListHosts() { long currentTimeNanos = System.nanoTime(); Set<Map.Entry<HostAddress, Long>> entries = blacklist.entrySet(); for (Map.Entry<HostAddress, Long> blEntry : entries) { long entryNanos = blEntry.getValue(); long durationSeconds = TimeUnit.NANOSECONDS.toSeconds(currentTimeNanos - entryNanos); if (durationSeconds >= urlParser.getOptions().loadBalanceBlacklistTimeout) { blacklist.remove(blEntry.getKey(), entryNanos); } } }
[ "public", "void", "resetOldsBlackListHosts", "(", ")", "{", "long", "currentTimeNanos", "=", "System", ".", "nanoTime", "(", ")", ";", "Set", "<", "Map", ".", "Entry", "<", "HostAddress", ",", "Long", ">", ">", "entries", "=", "blacklist", ".", "entrySet",...
Permit to remove Host to blacklist after loadBalanceBlacklistTimeout seconds.
[ "Permit", "to", "remove", "Host", "to", "blacklist", "after", "loadBalanceBlacklistTimeout", "seconds", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java#L232-L242
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java
AbstractMastersListener.setMasterHostFail
public boolean setMasterHostFail() { if (masterHostFail.compareAndSet(false, true)) { masterHostFailNanos = System.nanoTime(); currentConnectionAttempts.set(0); return true; } return false; }
java
public boolean setMasterHostFail() { if (masterHostFail.compareAndSet(false, true)) { masterHostFailNanos = System.nanoTime(); currentConnectionAttempts.set(0); return true; } return false; }
[ "public", "boolean", "setMasterHostFail", "(", ")", "{", "if", "(", "masterHostFail", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "masterHostFailNanos", "=", "System", ".", "nanoTime", "(", ")", ";", "currentConnectionAttempts", ".", "set",...
Set master fail variables. @return true if was already failed
[ "Set", "master", "fail", "variables", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java#L275-L282
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java
AbstractMastersListener.relaunchOperation
public HandleErrorResult relaunchOperation(Method method, Object[] args) throws IllegalAccessException, InvocationTargetException { HandleErrorResult handleErrorResult = new HandleErrorResult(true); if (method != null) { switch (method.getName()) { case "executeQuery": if (args[2] instanceof String) { String query = ((String) args[2]).toUpperCase(Locale.ROOT); if (!"ALTER SYSTEM CRASH".equals(query) && !query.startsWith("KILL")) { logger.debug("relaunch query to new connection {}", ((currentProtocol != null) ? "(conn=" + currentProtocol.getServerThreadId() + ")" : "")); handleErrorResult.resultObject = method.invoke(currentProtocol, args); handleErrorResult.mustThrowError = false; } } break; case "executePreparedQuery": //the statementId has been discarded with previous session try { boolean mustBeOnMaster = (Boolean) args[0]; ServerPrepareResult oldServerPrepareResult = (ServerPrepareResult) args[1]; ServerPrepareResult serverPrepareResult = currentProtocol .prepare(oldServerPrepareResult.getSql(), mustBeOnMaster); oldServerPrepareResult.failover(serverPrepareResult.getStatementId(), currentProtocol); logger.debug("relaunch query to new connection " + ((currentProtocol != null) ? "server thread id " + currentProtocol .getServerThreadId() : "")); handleErrorResult.resultObject = method.invoke(currentProtocol, args); handleErrorResult.mustThrowError = false; } catch (Exception e) { //if retry prepare fail, discard error. execution error will indicate the error. } break; default: handleErrorResult.resultObject = method.invoke(currentProtocol, args); handleErrorResult.mustThrowError = false; break; } } return handleErrorResult; }
java
public HandleErrorResult relaunchOperation(Method method, Object[] args) throws IllegalAccessException, InvocationTargetException { HandleErrorResult handleErrorResult = new HandleErrorResult(true); if (method != null) { switch (method.getName()) { case "executeQuery": if (args[2] instanceof String) { String query = ((String) args[2]).toUpperCase(Locale.ROOT); if (!"ALTER SYSTEM CRASH".equals(query) && !query.startsWith("KILL")) { logger.debug("relaunch query to new connection {}", ((currentProtocol != null) ? "(conn=" + currentProtocol.getServerThreadId() + ")" : "")); handleErrorResult.resultObject = method.invoke(currentProtocol, args); handleErrorResult.mustThrowError = false; } } break; case "executePreparedQuery": //the statementId has been discarded with previous session try { boolean mustBeOnMaster = (Boolean) args[0]; ServerPrepareResult oldServerPrepareResult = (ServerPrepareResult) args[1]; ServerPrepareResult serverPrepareResult = currentProtocol .prepare(oldServerPrepareResult.getSql(), mustBeOnMaster); oldServerPrepareResult.failover(serverPrepareResult.getStatementId(), currentProtocol); logger.debug("relaunch query to new connection " + ((currentProtocol != null) ? "server thread id " + currentProtocol .getServerThreadId() : "")); handleErrorResult.resultObject = method.invoke(currentProtocol, args); handleErrorResult.mustThrowError = false; } catch (Exception e) { //if retry prepare fail, discard error. execution error will indicate the error. } break; default: handleErrorResult.resultObject = method.invoke(currentProtocol, args); handleErrorResult.mustThrowError = false; break; } } return handleErrorResult; }
[ "public", "HandleErrorResult", "relaunchOperation", "(", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "IllegalAccessException", ",", "InvocationTargetException", "{", "HandleErrorResult", "handleErrorResult", "=", "new", "HandleErrorResult", "(", ...
After a failover that has bean done, relaunch the operation that was in progress. In case of special operation that crash server, doesn't relaunched it; @param method the methode accessed @param args the parameters @return An object that indicate the result or that the exception as to be thrown @throws IllegalAccessException if the initial call is not permit @throws InvocationTargetException if there is any error relaunching initial method
[ "After", "a", "failover", "that", "has", "bean", "done", "relaunch", "the", "operation", "that", "was", "in", "progress", ".", "In", "case", "of", "special", "operation", "that", "crash", "server", "doesn", "t", "relaunched", "it", ";" ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java#L306-L351
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java
AbstractMastersListener.isQueryRelaunchable
public boolean isQueryRelaunchable(Method method, Object[] args) { if (method != null) { switch (method.getName()) { case "executeQuery": if (!((Boolean) args[0])) { return true; //launched on slave connection } if (args[2] instanceof String) { return ((String) args[2]).toUpperCase(Locale.ROOT).startsWith("SELECT"); } else if (args[2] instanceof ClientPrepareResult) { @SuppressWarnings("unchecked") String query = new String(((ClientPrepareResult) args[2]).getQueryParts().get(0)) .toUpperCase(Locale.ROOT); return query.startsWith("SELECT"); } break; case "executePreparedQuery": if (!((Boolean) args[0])) { return true; //launched on slave connection } ServerPrepareResult serverPrepareResult = (ServerPrepareResult) args[1]; return (serverPrepareResult.getSql()).toUpperCase(Locale.ROOT).startsWith("SELECT"); case "executeBatchStmt": case "executeBatchClient": case "executeBatchServer": return !((Boolean) args[0]); default: return false; } } return false; }
java
public boolean isQueryRelaunchable(Method method, Object[] args) { if (method != null) { switch (method.getName()) { case "executeQuery": if (!((Boolean) args[0])) { return true; //launched on slave connection } if (args[2] instanceof String) { return ((String) args[2]).toUpperCase(Locale.ROOT).startsWith("SELECT"); } else if (args[2] instanceof ClientPrepareResult) { @SuppressWarnings("unchecked") String query = new String(((ClientPrepareResult) args[2]).getQueryParts().get(0)) .toUpperCase(Locale.ROOT); return query.startsWith("SELECT"); } break; case "executePreparedQuery": if (!((Boolean) args[0])) { return true; //launched on slave connection } ServerPrepareResult serverPrepareResult = (ServerPrepareResult) args[1]; return (serverPrepareResult.getSql()).toUpperCase(Locale.ROOT).startsWith("SELECT"); case "executeBatchStmt": case "executeBatchClient": case "executeBatchServer": return !((Boolean) args[0]); default: return false; } } return false; }
[ "public", "boolean", "isQueryRelaunchable", "(", "Method", "method", ",", "Object", "[", "]", "args", ")", "{", "if", "(", "method", "!=", "null", ")", "{", "switch", "(", "method", ".", "getName", "(", ")", ")", "{", "case", "\"executeQuery\"", ":", "...
Check if query can be re-executed. @param method invoke method @param args invoke arguments @return true if can be re-executed
[ "Check", "if", "query", "can", "be", "re", "-", "executed", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java#L360-L391
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java
AbstractMastersListener.syncConnection
public void syncConnection(Protocol from, Protocol to) throws SQLException { if (from != null) { proxy.lock.lock(); try { to.resetStateAfterFailover(from.getMaxRows(), from.getTransactionIsolationLevel(), from.getDatabase(), from.getAutocommit()); } finally { proxy.lock.unlock(); } } }
java
public void syncConnection(Protocol from, Protocol to) throws SQLException { if (from != null) { proxy.lock.lock(); try { to.resetStateAfterFailover(from.getMaxRows(), from.getTransactionIsolationLevel(), from.getDatabase(), from.getAutocommit()); } finally { proxy.lock.unlock(); } } }
[ "public", "void", "syncConnection", "(", "Protocol", "from", ",", "Protocol", "to", ")", "throws", "SQLException", "{", "if", "(", "from", "!=", "null", ")", "{", "proxy", ".", "lock", ".", "lock", "(", ")", ";", "try", "{", "to", ".", "resetStateAfter...
When switching between 2 connections, report existing connection parameter to the new used connection. @param from used connection @param to will-be-current connection @throws SQLException if catalog cannot be set
[ "When", "switching", "between", "2", "connections", "report", "existing", "connection", "parameter", "to", "the", "new", "used", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java#L409-L422
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java
AbstractMastersListener.throwFailoverMessage
@Override public void throwFailoverMessage(HostAddress failHostAddress, boolean wasMaster, SQLException queryException, boolean reconnected) throws SQLException { String firstPart = "Communications link failure with " + (wasMaster ? "primary" : "secondary") + ((failHostAddress != null) ? " host " + failHostAddress.host + ":" + failHostAddress.port : "") + ". "; String error = ""; if (reconnected) { error += " Driver has reconnect connection"; } else { if (currentConnectionAttempts.get() > urlParser.getOptions().retriesAllDown) { error += " Driver will not try to reconnect (too much failure > " + urlParser .getOptions().retriesAllDown + ")"; } } String message; String sqlState; int vendorCode = 0; Throwable cause = null; if (queryException == null) { message = firstPart + error; sqlState = CONNECTION_EXCEPTION.getSqlState(); } else { message = firstPart + queryException.getMessage() + ". " + error; sqlState = queryException.getSQLState(); vendorCode = queryException.getErrorCode(); cause = queryException.getCause(); } if (sqlState != null && sqlState.startsWith("08")) { if (reconnected) { //change sqlState to "Transaction has been rolled back", to transaction exception, since reconnection has succeed sqlState = "25S03"; } else { throw new SQLNonTransientConnectionException(message, sqlState, vendorCode, cause); } } throw new SQLException(message, sqlState, vendorCode, cause); }
java
@Override public void throwFailoverMessage(HostAddress failHostAddress, boolean wasMaster, SQLException queryException, boolean reconnected) throws SQLException { String firstPart = "Communications link failure with " + (wasMaster ? "primary" : "secondary") + ((failHostAddress != null) ? " host " + failHostAddress.host + ":" + failHostAddress.port : "") + ". "; String error = ""; if (reconnected) { error += " Driver has reconnect connection"; } else { if (currentConnectionAttempts.get() > urlParser.getOptions().retriesAllDown) { error += " Driver will not try to reconnect (too much failure > " + urlParser .getOptions().retriesAllDown + ")"; } } String message; String sqlState; int vendorCode = 0; Throwable cause = null; if (queryException == null) { message = firstPart + error; sqlState = CONNECTION_EXCEPTION.getSqlState(); } else { message = firstPart + queryException.getMessage() + ". " + error; sqlState = queryException.getSQLState(); vendorCode = queryException.getErrorCode(); cause = queryException.getCause(); } if (sqlState != null && sqlState.startsWith("08")) { if (reconnected) { //change sqlState to "Transaction has been rolled back", to transaction exception, since reconnection has succeed sqlState = "25S03"; } else { throw new SQLNonTransientConnectionException(message, sqlState, vendorCode, cause); } } throw new SQLException(message, sqlState, vendorCode, cause); }
[ "@", "Override", "public", "void", "throwFailoverMessage", "(", "HostAddress", "failHostAddress", ",", "boolean", "wasMaster", ",", "SQLException", "queryException", ",", "boolean", "reconnected", ")", "throws", "SQLException", "{", "String", "firstPart", "=", "\"Comm...
Throw a human readable message after a failoverException. @param failHostAddress failedHostAddress @param wasMaster was failed connection master @param queryException internal error @param reconnected connection status @throws SQLException error with failover information
[ "Throw", "a", "human", "readable", "message", "after", "a", "failoverException", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersListener.java#L496-L540
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalString
public String getInternalString(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case BIT: return String.valueOf(parseBit()); case DOUBLE: case FLOAT: return zeroFillingIfNeeded(new String(buf, pos, length, StandardCharsets.UTF_8), columnInfo); case TIME: return getInternalTimeString(columnInfo); case DATE: Date date = getInternalDate(columnInfo, cal, timeZone); if (date == null) { if ((lastValueNull & BIT_LAST_ZERO_DATE) != 0) { lastValueNull ^= BIT_LAST_ZERO_DATE; return new String(buf, pos, length, StandardCharsets.UTF_8); } return null; } return date.toString(); case YEAR: if (options.yearIsDateType) { Date date1 = getInternalDate(columnInfo, cal, timeZone); return (date1 == null) ? null : date1.toString(); } break; case TIMESTAMP: case DATETIME: Timestamp timestamp = getInternalTimestamp(columnInfo, cal, timeZone); if (timestamp == null) { if ((lastValueNull & BIT_LAST_ZERO_DATE) != 0) { lastValueNull ^= BIT_LAST_ZERO_DATE; return new String(buf, pos, length, StandardCharsets.UTF_8); } return null; } return timestamp.toString(); case DECIMAL: case OLDDECIMAL: BigDecimal bigDecimal = getInternalBigDecimal(columnInfo); return (bigDecimal == null) ? null : zeroFillingIfNeeded(bigDecimal.toString(), columnInfo); case NULL: return null; default: break; } if (maxFieldSize > 0) { return new String(buf, pos, Math.min(maxFieldSize * 3, length), StandardCharsets.UTF_8) .substring(0, Math.min(maxFieldSize, length)); } return new String(buf, pos, length, StandardCharsets.UTF_8); }
java
public String getInternalString(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case BIT: return String.valueOf(parseBit()); case DOUBLE: case FLOAT: return zeroFillingIfNeeded(new String(buf, pos, length, StandardCharsets.UTF_8), columnInfo); case TIME: return getInternalTimeString(columnInfo); case DATE: Date date = getInternalDate(columnInfo, cal, timeZone); if (date == null) { if ((lastValueNull & BIT_LAST_ZERO_DATE) != 0) { lastValueNull ^= BIT_LAST_ZERO_DATE; return new String(buf, pos, length, StandardCharsets.UTF_8); } return null; } return date.toString(); case YEAR: if (options.yearIsDateType) { Date date1 = getInternalDate(columnInfo, cal, timeZone); return (date1 == null) ? null : date1.toString(); } break; case TIMESTAMP: case DATETIME: Timestamp timestamp = getInternalTimestamp(columnInfo, cal, timeZone); if (timestamp == null) { if ((lastValueNull & BIT_LAST_ZERO_DATE) != 0) { lastValueNull ^= BIT_LAST_ZERO_DATE; return new String(buf, pos, length, StandardCharsets.UTF_8); } return null; } return timestamp.toString(); case DECIMAL: case OLDDECIMAL: BigDecimal bigDecimal = getInternalBigDecimal(columnInfo); return (bigDecimal == null) ? null : zeroFillingIfNeeded(bigDecimal.toString(), columnInfo); case NULL: return null; default: break; } if (maxFieldSize > 0) { return new String(buf, pos, Math.min(maxFieldSize * 3, length), StandardCharsets.UTF_8) .substring(0, Math.min(maxFieldSize, length)); } return new String(buf, pos, length, StandardCharsets.UTF_8); }
[ "public", "String", "getInternalString", "(", "ColumnInformation", "columnInfo", ",", "Calendar", "cal", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "switch", "...
Get String from raw text format. @param columnInfo column information @param cal calendar @param timeZone time zone @return String value @throws SQLException if column type doesn't permit conversion
[ "Get", "String", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L186-L244
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalInt
public int getInternalInt(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } long value = getInternalLong(columnInfo); rangeCheck(Integer.class, Integer.MIN_VALUE, Integer.MAX_VALUE, value, columnInfo); return (int) value; }
java
public int getInternalInt(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } long value = getInternalLong(columnInfo); rangeCheck(Integer.class, Integer.MIN_VALUE, Integer.MAX_VALUE, value, columnInfo); return (int) value; }
[ "public", "int", "getInternalInt", "(", "ColumnInformation", "columnInfo", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "0", ";", "}", "long", "value", "=", "getInternalLong", "(", "columnInfo", ")", ";", "...
Get int from raw text format. @param columnInfo column information @return int value @throws SQLException if column type doesn't permit conversion or not in Integer range
[ "Get", "int", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L253-L260
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalFloat
public float getInternalFloat(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } switch (columnInfo.getColumnType()) { case BIT: return parseBit(); case TINYINT: case SMALLINT: case YEAR: case INTEGER: case MEDIUMINT: case FLOAT: case DOUBLE: case DECIMAL: case VARSTRING: case VARCHAR: case STRING: case OLDDECIMAL: case BIGINT: try { return Float.valueOf(new String(buf, pos, length, StandardCharsets.UTF_8)); } catch (NumberFormatException nfe) { SQLException sqlException = new SQLException("Incorrect format \"" + new String(buf, pos, length, StandardCharsets.UTF_8) + "\" for getFloat for data field with type " + columnInfo.getColumnType() .getJavaTypeName(), "22003", 1264); //noinspection UnnecessaryInitCause sqlException.initCause(nfe); throw sqlException; } default: throw new SQLException( "getFloat not available for data field type " + columnInfo.getColumnType() .getJavaTypeName()); } }
java
public float getInternalFloat(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } switch (columnInfo.getColumnType()) { case BIT: return parseBit(); case TINYINT: case SMALLINT: case YEAR: case INTEGER: case MEDIUMINT: case FLOAT: case DOUBLE: case DECIMAL: case VARSTRING: case VARCHAR: case STRING: case OLDDECIMAL: case BIGINT: try { return Float.valueOf(new String(buf, pos, length, StandardCharsets.UTF_8)); } catch (NumberFormatException nfe) { SQLException sqlException = new SQLException("Incorrect format \"" + new String(buf, pos, length, StandardCharsets.UTF_8) + "\" for getFloat for data field with type " + columnInfo.getColumnType() .getJavaTypeName(), "22003", 1264); //noinspection UnnecessaryInitCause sqlException.initCause(nfe); throw sqlException; } default: throw new SQLException( "getFloat not available for data field type " + columnInfo.getColumnType() .getJavaTypeName()); } }
[ "public", "float", "getInternalFloat", "(", "ColumnInformation", "columnInfo", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "0", ";", "}", "switch", "(", "columnInfo", ".", "getColumnType", "(", ")", ")", "...
Get float from raw text format. @param columnInfo column information @return float value @throws SQLException if column type doesn't permit conversion or not in Float range
[ "Get", "float", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L350-L387
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalBigDecimal
public BigDecimal getInternalBigDecimal(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } if (columnInfo.getColumnType() == ColumnType.BIT) { return BigDecimal.valueOf(parseBit()); } return new BigDecimal(new String(buf, pos, length, StandardCharsets.UTF_8)); }
java
public BigDecimal getInternalBigDecimal(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } if (columnInfo.getColumnType() == ColumnType.BIT) { return BigDecimal.valueOf(parseBit()); } return new BigDecimal(new String(buf, pos, length, StandardCharsets.UTF_8)); }
[ "public", "BigDecimal", "getInternalBigDecimal", "(", "ColumnInformation", "columnInfo", ")", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "columnInfo", ".", "getColumnType", "(", ")", "==", "ColumnType", ".", ...
Get BigDecimal from raw text format. @param columnInfo column information @return BigDecimal value
[ "Get", "BigDecimal", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L442-L451
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalDate
@SuppressWarnings("deprecation") public Date getInternalDate(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case DATE: int[] datePart = new int[]{0,0,0}; int partIdx = 0; for (int begin = pos; begin < pos + length; begin++) { byte b = buf[begin]; if (b == '-') { partIdx++; continue; } if (b < '0' || b > '9') { throw new SQLException( "cannot parse data in date string '" + new String(buf, pos, length, StandardCharsets.UTF_8) + "'"); } datePart[partIdx] = datePart[partIdx] * 10 + b - 48; } if (datePart[0] == 0 && datePart[1] == 0 && datePart[2] == 0) { lastValueNull |= BIT_LAST_ZERO_DATE; return null; } return new Date( datePart[0] - 1900, datePart[1] - 1, datePart[2]); case TIMESTAMP: case DATETIME: Timestamp timestamp = getInternalTimestamp(columnInfo, cal, timeZone); if (timestamp == null) { return null; } return new Date(timestamp.getTime()); case TIME: throw new SQLException("Cannot read DATE using a Types.TIME field"); case YEAR: int year = 0; for (int begin = pos; begin < pos + length; begin++) { year = year * 10 + buf[begin] - 48; } if (length == 2 && columnInfo.getLength() == 2) { if (year <= 69) { year += 2000; } else { year += 1900; } } return new Date(year - 1900, 0, 1); default: try { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setTimeZone(timeZone); java.util.Date utilDate = sdf.parse(new String(buf, pos, length, StandardCharsets.UTF_8)); return new Date(utilDate.getTime()); } catch (ParseException e) { throw ExceptionMapper .getSqlException("Could not get object as Date : " + e.getMessage(), "S1009", e); } } }
java
@SuppressWarnings("deprecation") public Date getInternalDate(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } switch (columnInfo.getColumnType()) { case DATE: int[] datePart = new int[]{0,0,0}; int partIdx = 0; for (int begin = pos; begin < pos + length; begin++) { byte b = buf[begin]; if (b == '-') { partIdx++; continue; } if (b < '0' || b > '9') { throw new SQLException( "cannot parse data in date string '" + new String(buf, pos, length, StandardCharsets.UTF_8) + "'"); } datePart[partIdx] = datePart[partIdx] * 10 + b - 48; } if (datePart[0] == 0 && datePart[1] == 0 && datePart[2] == 0) { lastValueNull |= BIT_LAST_ZERO_DATE; return null; } return new Date( datePart[0] - 1900, datePart[1] - 1, datePart[2]); case TIMESTAMP: case DATETIME: Timestamp timestamp = getInternalTimestamp(columnInfo, cal, timeZone); if (timestamp == null) { return null; } return new Date(timestamp.getTime()); case TIME: throw new SQLException("Cannot read DATE using a Types.TIME field"); case YEAR: int year = 0; for (int begin = pos; begin < pos + length; begin++) { year = year * 10 + buf[begin] - 48; } if (length == 2 && columnInfo.getLength() == 2) { if (year <= 69) { year += 2000; } else { year += 1900; } } return new Date(year - 1900, 0, 1); default: try { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sdf.setTimeZone(timeZone); java.util.Date utilDate = sdf.parse(new String(buf, pos, length, StandardCharsets.UTF_8)); return new Date(utilDate.getTime()); } catch (ParseException e) { throw ExceptionMapper .getSqlException("Could not get object as Date : " + e.getMessage(), "S1009", e); } } }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "Date", "getInternalDate", "(", "ColumnInformation", "columnInfo", ",", "Calendar", "cal", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")"...
Get date from raw text format. @param columnInfo column information @param cal calendar @param timeZone time zone @return date value @throws SQLException if column type doesn't permit conversion
[ "Get", "date", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L462-L534
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalTime
public Time getInternalTime(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (columnInfo.getColumnType() == ColumnType.TIMESTAMP || columnInfo.getColumnType() == ColumnType.DATETIME) { Timestamp timestamp = getInternalTimestamp(columnInfo, cal, timeZone); return (timestamp == null) ? null : new Time(timestamp.getTime()); } else if (columnInfo.getColumnType() == ColumnType.DATE) { throw new SQLException("Cannot read Time using a Types.DATE field"); } else { String raw = new String(buf, pos, length, StandardCharsets.UTF_8); if (!options.useLegacyDatetimeCode && (raw.startsWith("-") || raw.split(":").length != 3 || raw.indexOf(":") > 3)) { throw new SQLException("Time format \"" + raw + "\" incorrect, must be HH:mm:ss"); } boolean negate = raw.startsWith("-"); if (negate) { raw = raw.substring(1); } String[] rawPart = raw.split(":"); if (rawPart.length == 3) { int hour = Integer.parseInt(rawPart[0]); int minutes = Integer.parseInt(rawPart[1]); int seconds = Integer.parseInt(rawPart[2].substring(0, 2)); Calendar calendar = Calendar.getInstance(); if (options.useLegacyDatetimeCode) { calendar.setLenient(true); } calendar.clear(); calendar.set(1970, Calendar.JANUARY, 1, (negate ? -1 : 1) * hour, minutes, seconds); int nanoseconds = extractNanos(raw); calendar.set(Calendar.MILLISECOND, nanoseconds / 1000000); return new Time(calendar.getTimeInMillis()); } else { throw new SQLException( raw + " cannot be parse as time. time must have \"99:99:99\" format"); } } }
java
public Time getInternalTime(ColumnInformation columnInfo, Calendar cal, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (columnInfo.getColumnType() == ColumnType.TIMESTAMP || columnInfo.getColumnType() == ColumnType.DATETIME) { Timestamp timestamp = getInternalTimestamp(columnInfo, cal, timeZone); return (timestamp == null) ? null : new Time(timestamp.getTime()); } else if (columnInfo.getColumnType() == ColumnType.DATE) { throw new SQLException("Cannot read Time using a Types.DATE field"); } else { String raw = new String(buf, pos, length, StandardCharsets.UTF_8); if (!options.useLegacyDatetimeCode && (raw.startsWith("-") || raw.split(":").length != 3 || raw.indexOf(":") > 3)) { throw new SQLException("Time format \"" + raw + "\" incorrect, must be HH:mm:ss"); } boolean negate = raw.startsWith("-"); if (negate) { raw = raw.substring(1); } String[] rawPart = raw.split(":"); if (rawPart.length == 3) { int hour = Integer.parseInt(rawPart[0]); int minutes = Integer.parseInt(rawPart[1]); int seconds = Integer.parseInt(rawPart[2].substring(0, 2)); Calendar calendar = Calendar.getInstance(); if (options.useLegacyDatetimeCode) { calendar.setLenient(true); } calendar.clear(); calendar.set(1970, Calendar.JANUARY, 1, (negate ? -1 : 1) * hour, minutes, seconds); int nanoseconds = extractNanos(raw); calendar.set(Calendar.MILLISECOND, nanoseconds / 1000000); return new Time(calendar.getTimeInMillis()); } else { throw new SQLException( raw + " cannot be parse as time. time must have \"99:99:99\" format"); } } }
[ "public", "Time", "getInternalTime", "(", "ColumnInformation", "columnInfo", ",", "Calendar", "cal", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "c...
Get time from raw text format. @param columnInfo column information @param cal calendar @param timeZone time zone @return time value @throws SQLException if column type doesn't permit conversion
[ "Get", "time", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L545-L591
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalBoolean
public boolean getInternalBoolean(ColumnInformation columnInfo) { if (lastValueWasNull()) { return false; } if (columnInfo.getColumnType() == ColumnType.BIT) { return parseBit() != 0; } final String rawVal = new String(buf, pos, length, StandardCharsets.UTF_8); return !("false".equals(rawVal) || "0".equals(rawVal)); }
java
public boolean getInternalBoolean(ColumnInformation columnInfo) { if (lastValueWasNull()) { return false; } if (columnInfo.getColumnType() == ColumnType.BIT) { return parseBit() != 0; } final String rawVal = new String(buf, pos, length, StandardCharsets.UTF_8); return !("false".equals(rawVal) || "0".equals(rawVal)); }
[ "public", "boolean", "getInternalBoolean", "(", "ColumnInformation", "columnInfo", ")", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "columnInfo", ".", "getColumnType", "(", ")", "==", "ColumnType", ".", "BI...
Get boolean from raw text format. @param columnInfo column information @return boolean value
[ "Get", "boolean", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L797-L807
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalByte
public byte getInternalByte(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } long value = getInternalLong(columnInfo); rangeCheck(Byte.class, Byte.MIN_VALUE, Byte.MAX_VALUE, value, columnInfo); return (byte) value; }
java
public byte getInternalByte(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } long value = getInternalLong(columnInfo); rangeCheck(Byte.class, Byte.MIN_VALUE, Byte.MAX_VALUE, value, columnInfo); return (byte) value; }
[ "public", "byte", "getInternalByte", "(", "ColumnInformation", "columnInfo", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "0", ";", "}", "long", "value", "=", "getInternalLong", "(", "columnInfo", ")", ";", ...
Get byte from raw text format. @param columnInfo column information @return byte value @throws SQLException if column type doesn't permit conversion
[ "Get", "byte", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L816-L823
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalShort
public short getInternalShort(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } long value = getInternalLong(columnInfo); rangeCheck(Short.class, Short.MIN_VALUE, Short.MAX_VALUE, value, columnInfo); return (short) value; }
java
public short getInternalShort(ColumnInformation columnInfo) throws SQLException { if (lastValueWasNull()) { return 0; } long value = getInternalLong(columnInfo); rangeCheck(Short.class, Short.MIN_VALUE, Short.MAX_VALUE, value, columnInfo); return (short) value; }
[ "public", "short", "getInternalShort", "(", "ColumnInformation", "columnInfo", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "0", ";", "}", "long", "value", "=", "getInternalLong", "(", "columnInfo", ")", ";",...
Get short from raw text format. @param columnInfo column information @return short value @throws SQLException if column type doesn't permit conversion or value is not in Short range
[ "Get", "short", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L832-L839
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalTimeString
public String getInternalTimeString(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } String rawValue = new String(buf, pos, length, StandardCharsets.UTF_8); if ("0000-00-00".equals(rawValue)) { return null; } if (options.maximizeMysqlCompatibility && options.useLegacyDatetimeCode && rawValue.indexOf(".") > 0) { return rawValue.substring(0, rawValue.indexOf(".")); } return rawValue; }
java
public String getInternalTimeString(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } String rawValue = new String(buf, pos, length, StandardCharsets.UTF_8); if ("0000-00-00".equals(rawValue)) { return null; } if (options.maximizeMysqlCompatibility && options.useLegacyDatetimeCode && rawValue.indexOf(".") > 0) { return rawValue.substring(0, rawValue.indexOf(".")); } return rawValue; }
[ "public", "String", "getInternalTimeString", "(", "ColumnInformation", "columnInfo", ")", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "String", "rawValue", "=", "new", "String", "(", "buf", ",", "pos", ",", "length", ...
Get Time in string format from raw text format. @param columnInfo column information @return String representation of time
[ "Get", "Time", "in", "string", "format", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L847-L862
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalBigInteger
public BigInteger getInternalBigInteger(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } return new BigInteger(new String(buf, pos, length, StandardCharsets.UTF_8)); }
java
public BigInteger getInternalBigInteger(ColumnInformation columnInfo) { if (lastValueWasNull()) { return null; } return new BigInteger(new String(buf, pos, length, StandardCharsets.UTF_8)); }
[ "public", "BigInteger", "getInternalBigInteger", "(", "ColumnInformation", "columnInfo", ")", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "return", "new", "BigInteger", "(", "new", "String", "(", "buf", ",", "pos", ","...
Get BigInteger format from raw text format. @param columnInfo column information @return BigInteger value
[ "Get", "BigInteger", "format", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L870-L875
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalZonedDateTime
public ZonedDateTime getInternalZonedDateTime(ColumnInformation columnInfo, Class clazz, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } String raw = new String(buf, pos, length, StandardCharsets.UTF_8); switch (columnInfo.getColumnType().getSqlType()) { case Types.TIMESTAMP: if (raw.startsWith("0000-00-00 00:00:00")) { return null; } try { LocalDateTime localDateTime = LocalDateTime .parse(raw, TEXT_LOCAL_DATE_TIME.withZone(timeZone.toZoneId())); return ZonedDateTime.of(localDateTime, timeZone.toZoneId()); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as LocalDateTime. time must have \"yyyy-MM-dd HH:mm:ss[.S]\" format"); } case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: if (raw.startsWith("0000-00-00 00:00:00")) { return null; } try { return ZonedDateTime.parse(raw, TEXT_ZONED_DATE_TIME); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as ZonedDateTime. time must have \"yyyy-MM-dd[T/ ]HH:mm:ss[.S]\" " + "with offset and timezone format (example : '2011-12-03 10:15:30+01:00[Europe/Paris]')"); } default: throw new SQLException( "Cannot read " + clazz.getName() + " using a " + columnInfo.getColumnType() .getJavaTypeName() + " field"); } }
java
public ZonedDateTime getInternalZonedDateTime(ColumnInformation columnInfo, Class clazz, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } String raw = new String(buf, pos, length, StandardCharsets.UTF_8); switch (columnInfo.getColumnType().getSqlType()) { case Types.TIMESTAMP: if (raw.startsWith("0000-00-00 00:00:00")) { return null; } try { LocalDateTime localDateTime = LocalDateTime .parse(raw, TEXT_LOCAL_DATE_TIME.withZone(timeZone.toZoneId())); return ZonedDateTime.of(localDateTime, timeZone.toZoneId()); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as LocalDateTime. time must have \"yyyy-MM-dd HH:mm:ss[.S]\" format"); } case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: if (raw.startsWith("0000-00-00 00:00:00")) { return null; } try { return ZonedDateTime.parse(raw, TEXT_ZONED_DATE_TIME); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as ZonedDateTime. time must have \"yyyy-MM-dd[T/ ]HH:mm:ss[.S]\" " + "with offset and timezone format (example : '2011-12-03 10:15:30+01:00[Europe/Paris]')"); } default: throw new SQLException( "Cannot read " + clazz.getName() + " using a " + columnInfo.getColumnType() .getJavaTypeName() + " field"); } }
[ "public", "ZonedDateTime", "getInternalZonedDateTime", "(", "ColumnInformation", "columnInfo", ",", "Class", "clazz", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", ...
Get ZonedDateTime format from raw text format. @param columnInfo column information @param clazz class for logging @param timeZone time zone @return ZonedDateTime value @throws SQLException if column type doesn't permit conversion
[ "Get", "ZonedDateTime", "format", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L886-L935
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalOffsetTime
public OffsetTime getInternalOffsetTime(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } ZoneId zoneId = timeZone.toZoneId().normalized(); if (zoneId instanceof ZoneOffset) { ZoneOffset zoneOffset = (ZoneOffset) zoneId; String raw = new String(buf, pos, length, StandardCharsets.UTF_8); switch (columnInfo.getColumnType().getSqlType()) { case Types.TIMESTAMP: if (raw.startsWith("0000-00-00 00:00:00")) { return null; } try { return ZonedDateTime.parse(raw, TEXT_LOCAL_DATE_TIME.withZone(zoneOffset)) .toOffsetDateTime().toOffsetTime(); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as OffsetTime. time must have \"yyyy-MM-dd HH:mm:ss[.S]\" format"); } case Types.TIME: try { LocalTime localTime = LocalTime .parse(raw, DateTimeFormatter.ISO_LOCAL_TIME.withZone(zoneOffset)); return OffsetTime.of(localTime, zoneOffset); } catch (DateTimeParseException dateParserEx) { throw new SQLException( raw + " cannot be parse as OffsetTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo.getColumnType() + "\")"); } case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: try { return OffsetTime.parse(raw, DateTimeFormatter.ISO_OFFSET_TIME); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as OffsetTime (format is \"HH:mm:ss[.S]\" with offset for data type \"" + columnInfo.getColumnType() + "\")"); } default: throw new SQLException("Cannot read " + OffsetTime.class.getName() + " using a " + columnInfo.getColumnType().getJavaTypeName() + " field"); } } if (options.useLegacyDatetimeCode) { //system timezone is not an offset throw new SQLException( "Cannot return an OffsetTime for a TIME field when default timezone is '" + zoneId + "' (only possible for time-zone offset from Greenwich/UTC, such as +02:00)"); } //server timezone is not an offset throw new SQLException( "Cannot return an OffsetTime for a TIME field when server timezone '" + zoneId + "' (only possible for time-zone offset from Greenwich/UTC, such as +02:00)"); }
java
public OffsetTime getInternalOffsetTime(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } ZoneId zoneId = timeZone.toZoneId().normalized(); if (zoneId instanceof ZoneOffset) { ZoneOffset zoneOffset = (ZoneOffset) zoneId; String raw = new String(buf, pos, length, StandardCharsets.UTF_8); switch (columnInfo.getColumnType().getSqlType()) { case Types.TIMESTAMP: if (raw.startsWith("0000-00-00 00:00:00")) { return null; } try { return ZonedDateTime.parse(raw, TEXT_LOCAL_DATE_TIME.withZone(zoneOffset)) .toOffsetDateTime().toOffsetTime(); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as OffsetTime. time must have \"yyyy-MM-dd HH:mm:ss[.S]\" format"); } case Types.TIME: try { LocalTime localTime = LocalTime .parse(raw, DateTimeFormatter.ISO_LOCAL_TIME.withZone(zoneOffset)); return OffsetTime.of(localTime, zoneOffset); } catch (DateTimeParseException dateParserEx) { throw new SQLException( raw + " cannot be parse as OffsetTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo.getColumnType() + "\")"); } case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: try { return OffsetTime.parse(raw, DateTimeFormatter.ISO_OFFSET_TIME); } catch (DateTimeParseException dateParserEx) { throw new SQLException(raw + " cannot be parse as OffsetTime (format is \"HH:mm:ss[.S]\" with offset for data type \"" + columnInfo.getColumnType() + "\")"); } default: throw new SQLException("Cannot read " + OffsetTime.class.getName() + " using a " + columnInfo.getColumnType().getJavaTypeName() + " field"); } } if (options.useLegacyDatetimeCode) { //system timezone is not an offset throw new SQLException( "Cannot return an OffsetTime for a TIME field when default timezone is '" + zoneId + "' (only possible for time-zone offset from Greenwich/UTC, such as +02:00)"); } //server timezone is not an offset throw new SQLException( "Cannot return an OffsetTime for a TIME field when server timezone '" + zoneId + "' (only possible for time-zone offset from Greenwich/UTC, such as +02:00)"); }
[ "public", "OffsetTime", "getInternalOffsetTime", "(", "ColumnInformation", "columnInfo", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "length", "==", ...
Get OffsetTime format from raw text format. @param columnInfo column information @param timeZone time zone @return OffsetTime value @throws SQLException if column type doesn't permit conversion
[ "Get", "OffsetTime", "format", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L945-L1013
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalLocalTime
public LocalTime getInternalLocalTime(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } String raw = new String(buf, pos, length, StandardCharsets.UTF_8); switch (columnInfo.getColumnType().getSqlType()) { case Types.TIME: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: try { return LocalTime .parse(raw, DateTimeFormatter.ISO_LOCAL_TIME.withZone(timeZone.toZoneId())); } catch (DateTimeParseException dateParserEx) { throw new SQLException( raw + " cannot be parse as LocalTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo.getColumnType() + "\")"); } case Types.TIMESTAMP: ZonedDateTime zonedDateTime = getInternalZonedDateTime(columnInfo, LocalTime.class, timeZone); return zonedDateTime == null ? null : zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalTime(); default: throw new SQLException( "Cannot read LocalTime using a " + columnInfo.getColumnType().getJavaTypeName() + " field"); } }
java
public LocalTime getInternalLocalTime(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } String raw = new String(buf, pos, length, StandardCharsets.UTF_8); switch (columnInfo.getColumnType().getSqlType()) { case Types.TIME: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: try { return LocalTime .parse(raw, DateTimeFormatter.ISO_LOCAL_TIME.withZone(timeZone.toZoneId())); } catch (DateTimeParseException dateParserEx) { throw new SQLException( raw + " cannot be parse as LocalTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo.getColumnType() + "\")"); } case Types.TIMESTAMP: ZonedDateTime zonedDateTime = getInternalZonedDateTime(columnInfo, LocalTime.class, timeZone); return zonedDateTime == null ? null : zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalTime(); default: throw new SQLException( "Cannot read LocalTime using a " + columnInfo.getColumnType().getJavaTypeName() + " field"); } }
[ "public", "LocalTime", "getInternalLocalTime", "(", "ColumnInformation", "columnInfo", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "length", "==", "0...
Get LocalTime format from raw text format. @param columnInfo column information @param timeZone time zone @return LocalTime value @throws SQLException if column type doesn't permit conversion
[ "Get", "LocalTime", "format", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L1023-L1061
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java
TextRowProtocol.getInternalLocalDate
public LocalDate getInternalLocalDate(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } String raw = new String(buf, pos, length, StandardCharsets.UTF_8); switch (columnInfo.getColumnType().getSqlType()) { case Types.DATE: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: if (raw.startsWith("0000-00-00")) { return null; } try { return LocalDate .parse(raw, DateTimeFormatter.ISO_LOCAL_DATE.withZone(timeZone.toZoneId())); } catch (DateTimeParseException dateParserEx) { throw new SQLException( raw + " cannot be parse as LocalDate (format is \"yyyy-MM-dd\" for data type \"" + columnInfo.getColumnType() + "\")"); } case Types.TIMESTAMP: ZonedDateTime zonedDateTime = getInternalZonedDateTime(columnInfo, LocalDate.class, timeZone); return zonedDateTime == null ? null : zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDate(); default: throw new SQLException( "Cannot read LocalDate using a " + columnInfo.getColumnType().getJavaTypeName() + " field"); } }
java
public LocalDate getInternalLocalDate(ColumnInformation columnInfo, TimeZone timeZone) throws SQLException { if (lastValueWasNull()) { return null; } if (length == 0) { lastValueNull |= BIT_LAST_FIELD_NULL; return null; } String raw = new String(buf, pos, length, StandardCharsets.UTF_8); switch (columnInfo.getColumnType().getSqlType()) { case Types.DATE: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: if (raw.startsWith("0000-00-00")) { return null; } try { return LocalDate .parse(raw, DateTimeFormatter.ISO_LOCAL_DATE.withZone(timeZone.toZoneId())); } catch (DateTimeParseException dateParserEx) { throw new SQLException( raw + " cannot be parse as LocalDate (format is \"yyyy-MM-dd\" for data type \"" + columnInfo.getColumnType() + "\")"); } case Types.TIMESTAMP: ZonedDateTime zonedDateTime = getInternalZonedDateTime(columnInfo, LocalDate.class, timeZone); return zonedDateTime == null ? null : zonedDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDate(); default: throw new SQLException( "Cannot read LocalDate using a " + columnInfo.getColumnType().getJavaTypeName() + " field"); } }
[ "public", "LocalDate", "getInternalLocalDate", "(", "ColumnInformation", "columnInfo", ",", "TimeZone", "timeZone", ")", "throws", "SQLException", "{", "if", "(", "lastValueWasNull", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "length", "==", "0...
Get LocalDate format from raw text format. @param columnInfo column information @param timeZone time zone @return LocalDate value @throws SQLException if column type doesn't permit conversion
[ "Get", "LocalDate", "format", "from", "raw", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/rowprotocol/TextRowProtocol.java#L1071-L1112
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java
AbstractConnectProtocol.connect
public void connect() throws SQLException { if (!isClosed()) { close(); } try { connect((currentHost != null) ? currentHost.host : null, (currentHost != null) ? currentHost.port : 3306); } catch (IOException ioException) { throw ExceptionMapper.connException( "Could not connect to " + currentHost + ". " + ioException.getMessage() + getTraces(), ioException); } }
java
public void connect() throws SQLException { if (!isClosed()) { close(); } try { connect((currentHost != null) ? currentHost.host : null, (currentHost != null) ? currentHost.port : 3306); } catch (IOException ioException) { throw ExceptionMapper.connException( "Could not connect to " + currentHost + ". " + ioException.getMessage() + getTraces(), ioException); } }
[ "public", "void", "connect", "(", ")", "throws", "SQLException", "{", "if", "(", "!", "isClosed", "(", ")", ")", "{", "close", "(", ")", ";", "}", "try", "{", "connect", "(", "(", "currentHost", "!=", "null", ")", "?", "currentHost", ".", "host", "...
Connect to currentHost. @throws SQLException exception
[ "Connect", "to", "currentHost", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java#L363-L376
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java
AbstractConnectProtocol.connect
private void connect(String host, int port) throws SQLException, IOException { try { socket = Utils.createSocket(urlParser, host); if (options.socketTimeout != null) { socket.setSoTimeout(options.socketTimeout); } initializeSocketOption(); // Bind the socket to a particular interface if the connection property // localSocketAddress has been defined. if (options.localSocketAddress != null) { InetSocketAddress localAddress = new InetSocketAddress(options.localSocketAddress, 0); socket.bind(localAddress); } if (!socket.isConnected()) { InetSocketAddress sockAddr = urlParser.getOptions().pipe == null ? new InetSocketAddress(host, port) : null; if (options.connectTimeout != 0) { socket.connect(sockAddr, options.connectTimeout); } else { socket.connect(sockAddr); } } handleConnectionPhases(host); connected = true; if (options.useCompression) { writer = new CompressPacketOutputStream(writer.getOutputStream(), options.maxQuerySizeToLog); reader = new DecompressPacketInputStream( ((StandardPacketInputStream) reader).getInputStream(), options.maxQuerySizeToLog); if (options.enablePacketDebug) { writer.setTraceCache(traceCache); reader.setTraceCache(traceCache); } } boolean mustLoadAdditionalInfo = true; if (globalInfo != null) { if (globalInfo.isAutocommit() == options.autocommit) { mustLoadAdditionalInfo = false; } } if (mustLoadAdditionalInfo) { Map<String, String> serverData = new TreeMap<>(); if (options.usePipelineAuth && !options.createDatabaseIfNotExist) { try { sendPipelineAdditionalData(); readPipelineAdditionalData(serverData); } catch (SQLException sqle) { if ("08".equals(sqle.getSQLState())) { throw sqle; } //in case pipeline is not supported //(proxy flush socket after reading first packet) additionalData(serverData); } } else { additionalData(serverData); } writer.setMaxAllowedPacket(Integer.parseInt(serverData.get("max_allowed_packet"))); autoIncrementIncrement = Integer.parseInt(serverData.get("auto_increment_increment")); loadCalendar(serverData.get("time_zone"), serverData.get("system_time_zone")); } else { writer.setMaxAllowedPacket((int) globalInfo.getMaxAllowedPacket()); autoIncrementIncrement = globalInfo.getAutoIncrementIncrement(); loadCalendar(globalInfo.getTimeZone(), globalInfo.getSystemTimeZone()); } reader.setServerThreadId(this.serverThreadId, isMasterConnection()); writer.setServerThreadId(this.serverThreadId, isMasterConnection()); activeStreamingResult = null; hostFailed = false; } catch (IOException | SQLException ioException) { ensureClosingSocketOnException(); throw ioException; } }
java
private void connect(String host, int port) throws SQLException, IOException { try { socket = Utils.createSocket(urlParser, host); if (options.socketTimeout != null) { socket.setSoTimeout(options.socketTimeout); } initializeSocketOption(); // Bind the socket to a particular interface if the connection property // localSocketAddress has been defined. if (options.localSocketAddress != null) { InetSocketAddress localAddress = new InetSocketAddress(options.localSocketAddress, 0); socket.bind(localAddress); } if (!socket.isConnected()) { InetSocketAddress sockAddr = urlParser.getOptions().pipe == null ? new InetSocketAddress(host, port) : null; if (options.connectTimeout != 0) { socket.connect(sockAddr, options.connectTimeout); } else { socket.connect(sockAddr); } } handleConnectionPhases(host); connected = true; if (options.useCompression) { writer = new CompressPacketOutputStream(writer.getOutputStream(), options.maxQuerySizeToLog); reader = new DecompressPacketInputStream( ((StandardPacketInputStream) reader).getInputStream(), options.maxQuerySizeToLog); if (options.enablePacketDebug) { writer.setTraceCache(traceCache); reader.setTraceCache(traceCache); } } boolean mustLoadAdditionalInfo = true; if (globalInfo != null) { if (globalInfo.isAutocommit() == options.autocommit) { mustLoadAdditionalInfo = false; } } if (mustLoadAdditionalInfo) { Map<String, String> serverData = new TreeMap<>(); if (options.usePipelineAuth && !options.createDatabaseIfNotExist) { try { sendPipelineAdditionalData(); readPipelineAdditionalData(serverData); } catch (SQLException sqle) { if ("08".equals(sqle.getSQLState())) { throw sqle; } //in case pipeline is not supported //(proxy flush socket after reading first packet) additionalData(serverData); } } else { additionalData(serverData); } writer.setMaxAllowedPacket(Integer.parseInt(serverData.get("max_allowed_packet"))); autoIncrementIncrement = Integer.parseInt(serverData.get("auto_increment_increment")); loadCalendar(serverData.get("time_zone"), serverData.get("system_time_zone")); } else { writer.setMaxAllowedPacket((int) globalInfo.getMaxAllowedPacket()); autoIncrementIncrement = globalInfo.getAutoIncrementIncrement(); loadCalendar(globalInfo.getTimeZone(), globalInfo.getSystemTimeZone()); } reader.setServerThreadId(this.serverThreadId, isMasterConnection()); writer.setServerThreadId(this.serverThreadId, isMasterConnection()); activeStreamingResult = null; hostFailed = false; } catch (IOException | SQLException ioException) { ensureClosingSocketOnException(); throw ioException; } }
[ "private", "void", "connect", "(", "String", "host", ",", "int", "port", ")", "throws", "SQLException", ",", "IOException", "{", "try", "{", "socket", "=", "Utils", ".", "createSocket", "(", "urlParser", ",", "host", ")", ";", "if", "(", "options", ".", ...
Connect the client and perform handshake. @param host host @param port port @throws SQLException handshake error, e.g wrong user or password @throws IOException connection error (host/port not available)
[ "Connect", "the", "client", "and", "perform", "handshake", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java#L386-L473
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java
AbstractConnectProtocol.sendPipelineCheckMaster
private void sendPipelineCheckMaster() throws IOException { if (urlParser.getHaMode() == HaMode.AURORA) { writer.startPacket(0); writer.write(COM_QUERY); writer.write(IS_MASTER_QUERY); writer.flush(); } }
java
private void sendPipelineCheckMaster() throws IOException { if (urlParser.getHaMode() == HaMode.AURORA) { writer.startPacket(0); writer.write(COM_QUERY); writer.write(IS_MASTER_QUERY); writer.flush(); } }
[ "private", "void", "sendPipelineCheckMaster", "(", ")", "throws", "IOException", "{", "if", "(", "urlParser", ".", "getHaMode", "(", ")", "==", "HaMode", ".", "AURORA", ")", "{", "writer", ".", "startPacket", "(", "0", ")", ";", "writer", ".", "write", "...
Send query to identify if server is master. @throws IOException in case of socket error.
[ "Send", "query", "to", "identify", "if", "server", "is", "master", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java#L1068-L1075
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java
AbstractConnectProtocol.enabledSslCipherSuites
private void enabledSslCipherSuites(SSLSocket sslSocket) throws SQLException { if (options.enabledSslCipherSuites != null) { List<String> possibleCiphers = Arrays.asList(sslSocket.getSupportedCipherSuites()); String[] ciphers = options.enabledSslCipherSuites.split("[,;\\s]+"); for (String cipher : ciphers) { if (!possibleCiphers.contains(cipher)) { throw new SQLException("Unsupported SSL cipher '" + cipher + "'. Supported ciphers : " + possibleCiphers.toString().replace("[", "").replace("]", "")); } } sslSocket.setEnabledCipherSuites(ciphers); } }
java
private void enabledSslCipherSuites(SSLSocket sslSocket) throws SQLException { if (options.enabledSslCipherSuites != null) { List<String> possibleCiphers = Arrays.asList(sslSocket.getSupportedCipherSuites()); String[] ciphers = options.enabledSslCipherSuites.split("[,;\\s]+"); for (String cipher : ciphers) { if (!possibleCiphers.contains(cipher)) { throw new SQLException("Unsupported SSL cipher '" + cipher + "'. Supported ciphers : " + possibleCiphers.toString().replace("[", "").replace("]", "")); } } sslSocket.setEnabledCipherSuites(ciphers); } }
[ "private", "void", "enabledSslCipherSuites", "(", "SSLSocket", "sslSocket", ")", "throws", "SQLException", "{", "if", "(", "options", ".", "enabledSslCipherSuites", "!=", "null", ")", "{", "List", "<", "String", ">", "possibleCiphers", "=", "Arrays", ".", "asLis...
Set ssl socket cipher according to options. @param sslSocket current ssl socket @throws SQLException if a cipher isn't known
[ "Set", "ssl", "socket", "cipher", "according", "to", "options", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java#L1265-L1277
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java
AbstractConnectProtocol.versionGreaterOrEqual
public boolean versionGreaterOrEqual(int major, int minor, int patch) { if (this.majorVersion > major) { return true; } if (this.majorVersion < major) { return false; } /* * Major versions are equal, compare minor versions */ if (this.minorVersion > minor) { return true; } if (this.minorVersion < minor) { return false; } //Minor versions are equal, compare patch version. return this.patchVersion >= patch; }
java
public boolean versionGreaterOrEqual(int major, int minor, int patch) { if (this.majorVersion > major) { return true; } if (this.majorVersion < major) { return false; } /* * Major versions are equal, compare minor versions */ if (this.minorVersion > minor) { return true; } if (this.minorVersion < minor) { return false; } //Minor versions are equal, compare patch version. return this.patchVersion >= patch; }
[ "public", "boolean", "versionGreaterOrEqual", "(", "int", "major", ",", "int", "minor", ",", "int", "patch", ")", "{", "if", "(", "this", ".", "majorVersion", ">", "major", ")", "{", "return", "true", ";", "}", "if", "(", "this", ".", "majorVersion", "...
Utility method to check if database version is greater than parameters. @param major major version @param minor minor version @param patch patch version @return true if version is greater than parameters
[ "Utility", "method", "to", "check", "if", "database", "version", "is", "greater", "than", "parameters", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractConnectProtocol.java#L1287-L1308
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/authentication/ClearPasswordPlugin.java
ClearPasswordPlugin.process
public Buffer process(PacketOutputStream out, PacketInputStream in, AtomicInteger sequence) throws IOException { if (password == null || password.isEmpty()) { out.writeEmptyPacket(sequence.incrementAndGet()); } else { out.startPacket(sequence.incrementAndGet()); byte[] bytePwd; if (passwordCharacterEncoding != null && !passwordCharacterEncoding.isEmpty()) { bytePwd = password.getBytes(passwordCharacterEncoding); } else { bytePwd = password.getBytes(); } out.write(bytePwd); out.write(0); out.flush(); } Buffer buffer = in.getPacket(true); sequence.set(in.getLastPacketSeq()); return buffer; }
java
public Buffer process(PacketOutputStream out, PacketInputStream in, AtomicInteger sequence) throws IOException { if (password == null || password.isEmpty()) { out.writeEmptyPacket(sequence.incrementAndGet()); } else { out.startPacket(sequence.incrementAndGet()); byte[] bytePwd; if (passwordCharacterEncoding != null && !passwordCharacterEncoding.isEmpty()) { bytePwd = password.getBytes(passwordCharacterEncoding); } else { bytePwd = password.getBytes(); } out.write(bytePwd); out.write(0); out.flush(); } Buffer buffer = in.getPacket(true); sequence.set(in.getLastPacketSeq()); return buffer; }
[ "public", "Buffer", "process", "(", "PacketOutputStream", "out", ",", "PacketInputStream", "in", ",", "AtomicInteger", "sequence", ")", "throws", "IOException", "{", "if", "(", "password", "==", "null", "||", "password", ".", "isEmpty", "(", ")", ")", "{", "...
Send password in clear text to server. @param out out stream @param in in stream @param sequence packet sequence @return response packet @throws IOException if socket error
[ "Send", "password", "in", "clear", "text", "to", "server", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/authentication/ClearPasswordPlugin.java#L87-L107
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/input/StandardPacketInputStream.java
StandardPacketInputStream.create
public static byte[] create(byte[][] rowDatas, ColumnType[] columnTypes) { int totalLength = 0; for (byte[] rowData : rowDatas) { if (rowData == null) { totalLength++; } else { int length = rowData.length; if (length < 251) { totalLength += length + 1; } else if (length < 65536) { totalLength += length + 3; } else if (length < 16777216) { totalLength += length + 4; } else { totalLength += length + 9; } } } byte[] buf = new byte[totalLength]; int pos = 0; for (byte[] arr : rowDatas) { if (arr == null) { buf[pos++] = (byte) 251; } else { int length = arr.length; if (length < 251) { buf[pos++] = (byte) length; } else if (length < 65536) { buf[pos++] = (byte) 0xfc; buf[pos++] = (byte) length; buf[pos++] = (byte) (length >>> 8); } else if (length < 16777216) { buf[pos++] = (byte) 0xfd; buf[pos++] = (byte) length; buf[pos++] = (byte) (length >>> 8); buf[pos++] = (byte) (length >>> 16); } else { buf[pos++] = (byte) 0xfe; buf[pos++] = (byte) length; buf[pos++] = (byte) (length >>> 8); buf[pos++] = (byte) (length >>> 16); buf[pos++] = (byte) (length >>> 24); //byte[] cannot have more than 4 byte length size, so buf[pos+5] -> buf[pos+8] = 0x00; pos += 4; } System.arraycopy(arr, 0, buf, pos, length); pos += length; } } return buf; }
java
public static byte[] create(byte[][] rowDatas, ColumnType[] columnTypes) { int totalLength = 0; for (byte[] rowData : rowDatas) { if (rowData == null) { totalLength++; } else { int length = rowData.length; if (length < 251) { totalLength += length + 1; } else if (length < 65536) { totalLength += length + 3; } else if (length < 16777216) { totalLength += length + 4; } else { totalLength += length + 9; } } } byte[] buf = new byte[totalLength]; int pos = 0; for (byte[] arr : rowDatas) { if (arr == null) { buf[pos++] = (byte) 251; } else { int length = arr.length; if (length < 251) { buf[pos++] = (byte) length; } else if (length < 65536) { buf[pos++] = (byte) 0xfc; buf[pos++] = (byte) length; buf[pos++] = (byte) (length >>> 8); } else if (length < 16777216) { buf[pos++] = (byte) 0xfd; buf[pos++] = (byte) length; buf[pos++] = (byte) (length >>> 8); buf[pos++] = (byte) (length >>> 16); } else { buf[pos++] = (byte) 0xfe; buf[pos++] = (byte) length; buf[pos++] = (byte) (length >>> 8); buf[pos++] = (byte) (length >>> 16); buf[pos++] = (byte) (length >>> 24); //byte[] cannot have more than 4 byte length size, so buf[pos+5] -> buf[pos+8] = 0x00; pos += 4; } System.arraycopy(arr, 0, buf, pos, length); pos += length; } } return buf; }
[ "public", "static", "byte", "[", "]", "create", "(", "byte", "[", "]", "[", "]", "rowDatas", ",", "ColumnType", "[", "]", "columnTypes", ")", "{", "int", "totalLength", "=", "0", ";", "for", "(", "byte", "[", "]", "rowData", ":", "rowDatas", ")", "...
Create Buffer with Text protocol values. @param rowDatas datas @param columnTypes column types @return Buffer
[ "Create", "Buffer", "with", "Text", "protocol", "values", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/input/StandardPacketInputStream.java#L159-L211
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/UrlParser.java
UrlParser.parse
public static UrlParser parse(final String url, Properties prop) throws SQLException { if (url != null && (url.startsWith("jdbc:mariadb:") || url.startsWith("jdbc:mysql:") && !url .contains(DISABLE_MYSQL_URL))) { UrlParser urlParser = new UrlParser(); parseInternal(urlParser, url, (prop == null) ? new Properties() : prop); return urlParser; } return null; }
java
public static UrlParser parse(final String url, Properties prop) throws SQLException { if (url != null && (url.startsWith("jdbc:mariadb:") || url.startsWith("jdbc:mysql:") && !url .contains(DISABLE_MYSQL_URL))) { UrlParser urlParser = new UrlParser(); parseInternal(urlParser, url, (prop == null) ? new Properties() : prop); return urlParser; } return null; }
[ "public", "static", "UrlParser", "parse", "(", "final", "String", "url", ",", "Properties", "prop", ")", "throws", "SQLException", "{", "if", "(", "url", "!=", "null", "&&", "(", "url", ".", "startsWith", "(", "\"jdbc:mariadb:\"", ")", "||", "url", ".", ...
Parse url connection string with additional properties. @param url connection string @param prop properties @return UrlParser instance @throws SQLException if parsing exception occur
[ "Parse", "url", "connection", "string", "with", "additional", "properties", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/UrlParser.java#L155-L164
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/UrlParser.java
UrlParser.parseInternal
private static void parseInternal(UrlParser urlParser, String url, Properties properties) throws SQLException { try { urlParser.initialUrl = url; int separator = url.indexOf("//"); if (separator == -1) { throw new IllegalArgumentException( "url parsing error : '//' is not present in the url " + url); } urlParser.haMode = parseHaMode(url, separator); String urlSecondPart = url.substring(separator + 2); int dbIndex = urlSecondPart.indexOf("/"); int paramIndex = urlSecondPart.indexOf("?"); String hostAddressesString; String additionalParameters; if ((dbIndex < paramIndex && dbIndex < 0) || (dbIndex > paramIndex && paramIndex > -1)) { hostAddressesString = urlSecondPart.substring(0, paramIndex); additionalParameters = urlSecondPart.substring(paramIndex); } else if ((dbIndex < paramIndex && dbIndex > -1) || (dbIndex > paramIndex && paramIndex < 0)) { hostAddressesString = urlSecondPart.substring(0, dbIndex); additionalParameters = urlSecondPart.substring(dbIndex); } else { hostAddressesString = urlSecondPart; additionalParameters = null; } defineUrlParserParameters(urlParser, properties, hostAddressesString, additionalParameters); setDefaultHostAddressType(urlParser); urlParser.loadMultiMasterValue(); } catch (IllegalArgumentException i) { throw new SQLException("error parsing url : " + i.getMessage(), i); } }
java
private static void parseInternal(UrlParser urlParser, String url, Properties properties) throws SQLException { try { urlParser.initialUrl = url; int separator = url.indexOf("//"); if (separator == -1) { throw new IllegalArgumentException( "url parsing error : '//' is not present in the url " + url); } urlParser.haMode = parseHaMode(url, separator); String urlSecondPart = url.substring(separator + 2); int dbIndex = urlSecondPart.indexOf("/"); int paramIndex = urlSecondPart.indexOf("?"); String hostAddressesString; String additionalParameters; if ((dbIndex < paramIndex && dbIndex < 0) || (dbIndex > paramIndex && paramIndex > -1)) { hostAddressesString = urlSecondPart.substring(0, paramIndex); additionalParameters = urlSecondPart.substring(paramIndex); } else if ((dbIndex < paramIndex && dbIndex > -1) || (dbIndex > paramIndex && paramIndex < 0)) { hostAddressesString = urlSecondPart.substring(0, dbIndex); additionalParameters = urlSecondPart.substring(dbIndex); } else { hostAddressesString = urlSecondPart; additionalParameters = null; } defineUrlParserParameters(urlParser, properties, hostAddressesString, additionalParameters); setDefaultHostAddressType(urlParser); urlParser.loadMultiMasterValue(); } catch (IllegalArgumentException i) { throw new SQLException("error parsing url : " + i.getMessage(), i); } }
[ "private", "static", "void", "parseInternal", "(", "UrlParser", "urlParser", ",", "String", "url", ",", "Properties", "properties", ")", "throws", "SQLException", "{", "try", "{", "urlParser", ".", "initialUrl", "=", "url", ";", "int", "separator", "=", "url",...
Parses the connection URL in order to set the UrlParser instance with all the information provided through the URL. @param urlParser object instance in which all data from the connection url is stored @param url connection URL @param properties properties @throws SQLException if format is incorrect
[ "Parses", "the", "connection", "URL", "in", "order", "to", "set", "the", "UrlParser", "instance", "with", "all", "the", "information", "provided", "through", "the", "URL", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/UrlParser.java#L175-L211
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/UrlParser.java
UrlParser.auroraPipelineQuirks
public UrlParser auroraPipelineQuirks() { //Aurora has issue with pipelining, depending on network speed. //Driver must rely on information provided by user : hostname if dns, and HA mode.</p> boolean disablePipeline = isAurora(); if (options.useBatchMultiSend == null) { options.useBatchMultiSend = disablePipeline ? Boolean.FALSE : Boolean.TRUE; } if (options.usePipelineAuth == null) { options.usePipelineAuth = disablePipeline ? Boolean.FALSE : Boolean.TRUE; } return this; }
java
public UrlParser auroraPipelineQuirks() { //Aurora has issue with pipelining, depending on network speed. //Driver must rely on information provided by user : hostname if dns, and HA mode.</p> boolean disablePipeline = isAurora(); if (options.useBatchMultiSend == null) { options.useBatchMultiSend = disablePipeline ? Boolean.FALSE : Boolean.TRUE; } if (options.usePipelineAuth == null) { options.usePipelineAuth = disablePipeline ? Boolean.FALSE : Boolean.TRUE; } return this; }
[ "public", "UrlParser", "auroraPipelineQuirks", "(", ")", "{", "//Aurora has issue with pipelining, depending on network speed.", "//Driver must rely on information provided by user : hostname if dns, and HA mode.</p>", "boolean", "disablePipeline", "=", "isAurora", "(", ")", ";", "if",...
Permit to set parameters not forced. if options useBatchMultiSend and usePipelineAuth are not explicitly set in connection string, value will default to true or false according if aurora detection. @return UrlParser for easy testing
[ "Permit", "to", "set", "parameters", "not", "forced", ".", "if", "options", "useBatchMultiSend", "and", "usePipelineAuth", "are", "not", "explicitly", "set", "in", "connection", "string", "value", "will", "default", "to", "true", "or", "false", "according", "if"...
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/UrlParser.java#L343-L357
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/ServerPrepareStatementCache.java
ServerPrepareStatementCache.removeEldestEntry
@Override public boolean removeEldestEntry(Map.Entry eldest) { boolean mustBeRemoved = this.size() > maxSize; if (mustBeRemoved) { ServerPrepareResult serverPrepareResult = ((ServerPrepareResult) eldest.getValue()); serverPrepareResult.setRemoveFromCache(); if (serverPrepareResult.canBeDeallocate()) { try { protocol.forceReleasePrepareStatement(serverPrepareResult.getStatementId()); } catch (SQLException e) { //eat exception } } } return mustBeRemoved; }
java
@Override public boolean removeEldestEntry(Map.Entry eldest) { boolean mustBeRemoved = this.size() > maxSize; if (mustBeRemoved) { ServerPrepareResult serverPrepareResult = ((ServerPrepareResult) eldest.getValue()); serverPrepareResult.setRemoveFromCache(); if (serverPrepareResult.canBeDeallocate()) { try { protocol.forceReleasePrepareStatement(serverPrepareResult.getStatementId()); } catch (SQLException e) { //eat exception } } } return mustBeRemoved; }
[ "@", "Override", "public", "boolean", "removeEldestEntry", "(", "Map", ".", "Entry", "eldest", ")", "{", "boolean", "mustBeRemoved", "=", "this", ".", "size", "(", ")", ">", "maxSize", ";", "if", "(", "mustBeRemoved", ")", "{", "ServerPrepareResult", "server...
Remove eldestEntry. @param eldest eldest entry @return true if eldest entry must be removed
[ "Remove", "eldestEntry", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/ServerPrepareStatementCache.java#L83-L99
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/ServerPrepareStatementCache.java
ServerPrepareStatementCache.put
public synchronized ServerPrepareResult put(String key, ServerPrepareResult result) { ServerPrepareResult cachedServerPrepareResult = super.get(key); //if there is already some cached data (and not been deallocate), return existing cached data if (cachedServerPrepareResult != null && cachedServerPrepareResult.incrementShareCounter()) { return cachedServerPrepareResult; } //if no cache data, or been deallocate, put new result in cache result.setAddToCache(); super.put(key, result); return null; }
java
public synchronized ServerPrepareResult put(String key, ServerPrepareResult result) { ServerPrepareResult cachedServerPrepareResult = super.get(key); //if there is already some cached data (and not been deallocate), return existing cached data if (cachedServerPrepareResult != null && cachedServerPrepareResult.incrementShareCounter()) { return cachedServerPrepareResult; } //if no cache data, or been deallocate, put new result in cache result.setAddToCache(); super.put(key, result); return null; }
[ "public", "synchronized", "ServerPrepareResult", "put", "(", "String", "key", ",", "ServerPrepareResult", "result", ")", "{", "ServerPrepareResult", "cachedServerPrepareResult", "=", "super", ".", "get", "(", "key", ")", ";", "//if there is already some cached data (and n...
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the existing cached prepared result shared counter will be incremented. @param key key @param result new prepare result. @return the previous value associated with key if not been deallocate, or null if there was no mapping for key.
[ "Associates", "the", "specified", "value", "with", "the", "specified", "key", "in", "this", "map", ".", "If", "the", "map", "previously", "contained", "a", "mapping", "for", "the", "key", "the", "existing", "cached", "prepared", "result", "shared", "counter", ...
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/ServerPrepareStatementCache.java#L111-L121
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/authentication/gssapi/WindowsNativeSspiAuthentication.java
WindowsNativeSspiAuthentication.authenticate
public void authenticate(final PacketOutputStream out, final PacketInputStream in, final AtomicInteger sequence, final String servicePrincipalName, final String mechanisms) throws IOException { // initialize a security context on the client IWindowsSecurityContext clientContext = WindowsSecurityContextImpl .getCurrent(mechanisms, servicePrincipalName); do { // Step 1: send token to server byte[] tokenForTheServerOnTheClient = clientContext.getToken(); out.startPacket(sequence.incrementAndGet()); out.write(tokenForTheServerOnTheClient); out.flush(); // Step 2: read server response token if (clientContext.isContinue()) { Buffer buffer = in.getPacket(true); sequence.set(in.getLastPacketSeq()); byte[] tokenForTheClientOnTheServer = buffer.readRawBytes(buffer.remaining()); Sspi.SecBufferDesc continueToken = new Sspi.SecBufferDesc(Sspi.SECBUFFER_TOKEN, tokenForTheClientOnTheServer); clientContext.initialize(clientContext.getHandle(), continueToken, servicePrincipalName); } } while (clientContext.isContinue()); clientContext.dispose(); }
java
public void authenticate(final PacketOutputStream out, final PacketInputStream in, final AtomicInteger sequence, final String servicePrincipalName, final String mechanisms) throws IOException { // initialize a security context on the client IWindowsSecurityContext clientContext = WindowsSecurityContextImpl .getCurrent(mechanisms, servicePrincipalName); do { // Step 1: send token to server byte[] tokenForTheServerOnTheClient = clientContext.getToken(); out.startPacket(sequence.incrementAndGet()); out.write(tokenForTheServerOnTheClient); out.flush(); // Step 2: read server response token if (clientContext.isContinue()) { Buffer buffer = in.getPacket(true); sequence.set(in.getLastPacketSeq()); byte[] tokenForTheClientOnTheServer = buffer.readRawBytes(buffer.remaining()); Sspi.SecBufferDesc continueToken = new Sspi.SecBufferDesc(Sspi.SECBUFFER_TOKEN, tokenForTheClientOnTheServer); clientContext.initialize(clientContext.getHandle(), continueToken, servicePrincipalName); } } while (clientContext.isContinue()); clientContext.dispose(); }
[ "public", "void", "authenticate", "(", "final", "PacketOutputStream", "out", ",", "final", "PacketInputStream", "in", ",", "final", "AtomicInteger", "sequence", ",", "final", "String", "servicePrincipalName", ",", "final", "String", "mechanisms", ")", "throws", "IOE...
Process native windows GSS plugin authentication. @param out out stream @param in in stream @param sequence packet sequence @param servicePrincipalName principal name @param mechanisms gssapi mechanism @throws IOException if socket error
[ "Process", "native", "windows", "GSS", "plugin", "authentication", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/authentication/gssapi/WindowsNativeSspiAuthentication.java#L78-L106
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/SendClosePacket.java
SendClosePacket.send
public static void send(final PacketOutputStream pos) { try { pos.startPacket(0); pos.write(Packet.COM_QUIT); pos.flush(); } catch (IOException ioe) { //eat } }
java
public static void send(final PacketOutputStream pos) { try { pos.startPacket(0); pos.write(Packet.COM_QUIT); pos.flush(); } catch (IOException ioe) { //eat } }
[ "public", "static", "void", "send", "(", "final", "PacketOutputStream", "pos", ")", "{", "try", "{", "pos", ".", "startPacket", "(", "0", ")", ";", "pos", ".", "write", "(", "Packet", ".", "COM_QUIT", ")", ";", "pos", ".", "flush", "(", ")", ";", "...
Send close stream to server. @param pos write outputStream
[ "Send", "close", "stream", "to", "server", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/SendClosePacket.java#L67-L75
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.flush
public void flush() throws IOException { flushBuffer(true); out.flush(); // if buffer is big, and last query doesn't use at least half of it, resize buffer to default value if (buf.length > SMALL_BUFFER_SIZE && cmdLength * 2 < buf.length) { buf = new byte[SMALL_BUFFER_SIZE]; } if (cmdLength >= maxAllowedPacket) { throw new MaxAllowedPacketException( "query size (" + cmdLength + ") is >= to max_allowed_packet (" + maxAllowedPacket + ")", true); } }
java
public void flush() throws IOException { flushBuffer(true); out.flush(); // if buffer is big, and last query doesn't use at least half of it, resize buffer to default value if (buf.length > SMALL_BUFFER_SIZE && cmdLength * 2 < buf.length) { buf = new byte[SMALL_BUFFER_SIZE]; } if (cmdLength >= maxAllowedPacket) { throw new MaxAllowedPacketException( "query size (" + cmdLength + ") is >= to max_allowed_packet (" + maxAllowedPacket + ")", true); } }
[ "public", "void", "flush", "(", ")", "throws", "IOException", "{", "flushBuffer", "(", "true", ")", ";", "out", ".", "flush", "(", ")", ";", "// if buffer is big, and last query doesn't use at least half of it, resize buffer to default value", "if", "(", "buf", ".", "...
Send packet to socket. @throws IOException if socket error occur.
[ "Send", "packet", "to", "socket", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L184-L198
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.checkMaxAllowedLength
public void checkMaxAllowedLength(int length) throws MaxAllowedPacketException { if (cmdLength + length >= maxAllowedPacket && cmdLength == 0) { //launch exception only if no packet has been send. throw new MaxAllowedPacketException("query size (" + (cmdLength + length) + ") is >= to max_allowed_packet (" + maxAllowedPacket + ")", false); } }
java
public void checkMaxAllowedLength(int length) throws MaxAllowedPacketException { if (cmdLength + length >= maxAllowedPacket && cmdLength == 0) { //launch exception only if no packet has been send. throw new MaxAllowedPacketException("query size (" + (cmdLength + length) + ") is >= to max_allowed_packet (" + maxAllowedPacket + ")", false); } }
[ "public", "void", "checkMaxAllowedLength", "(", "int", "length", ")", "throws", "MaxAllowedPacketException", "{", "if", "(", "cmdLength", "+", "length", ">=", "maxAllowedPacket", "&&", "cmdLength", "==", "0", ")", "{", "//launch exception only if no packet has been send...
Count query size. If query size is greater than max_allowed_packet and nothing has been already send, throw an exception to avoid having the connection closed. @param length additional length to query size @throws MaxAllowedPacketException if query has not to be send.
[ "Count", "query", "size", ".", "If", "query", "size", "is", "greater", "than", "max_allowed_packet", "and", "nothing", "has", "been", "already", "send", "throw", "an", "exception", "to", "avoid", "having", "the", "connection", "closed", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L211-L217
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.writeShort
public void writeShort(short value) throws IOException { if (2 > buf.length - pos) { //not enough space remaining byte[] arr = new byte[2]; arr[0] = (byte) value; arr[1] = (byte) (value >> 8); write(arr, 0, 2); return; } buf[pos] = (byte) value; buf[pos + 1] = (byte) (value >> 8); pos += 2; }
java
public void writeShort(short value) throws IOException { if (2 > buf.length - pos) { //not enough space remaining byte[] arr = new byte[2]; arr[0] = (byte) value; arr[1] = (byte) (value >> 8); write(arr, 0, 2); return; } buf[pos] = (byte) value; buf[pos + 1] = (byte) (value >> 8); pos += 2; }
[ "public", "void", "writeShort", "(", "short", "value", ")", "throws", "IOException", "{", "if", "(", "2", ">", "buf", ".", "length", "-", "pos", ")", "{", "//not enough space remaining", "byte", "[", "]", "arr", "=", "new", "byte", "[", "2", "]", ";", ...
Write short value into buffer. flush buffer if too small. @param value short value @throws IOException if socket error occur
[ "Write", "short", "value", "into", "buffer", ".", "flush", "buffer", "if", "too", "small", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L233-L246
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.writeInt
public void writeInt(int value) throws IOException { if (4 > buf.length - pos) { //not enough space remaining byte[] arr = new byte[4]; arr[0] = (byte) value; arr[1] = (byte) (value >> 8); arr[2] = (byte) (value >> 16); arr[3] = (byte) (value >> 24); write(arr, 0, 4); return; } buf[pos] = (byte) value; buf[pos + 1] = (byte) (value >> 8); buf[pos + 2] = (byte) (value >> 16); buf[pos + 3] = (byte) (value >> 24); pos += 4; }
java
public void writeInt(int value) throws IOException { if (4 > buf.length - pos) { //not enough space remaining byte[] arr = new byte[4]; arr[0] = (byte) value; arr[1] = (byte) (value >> 8); arr[2] = (byte) (value >> 16); arr[3] = (byte) (value >> 24); write(arr, 0, 4); return; } buf[pos] = (byte) value; buf[pos + 1] = (byte) (value >> 8); buf[pos + 2] = (byte) (value >> 16); buf[pos + 3] = (byte) (value >> 24); pos += 4; }
[ "public", "void", "writeInt", "(", "int", "value", ")", "throws", "IOException", "{", "if", "(", "4", ">", "buf", ".", "length", "-", "pos", ")", "{", "//not enough space remaining", "byte", "[", "]", "arr", "=", "new", "byte", "[", "4", "]", ";", "a...
Write int value into buffer. flush buffer if too small. @param value int value @throws IOException if socket error occur
[ "Write", "int", "value", "into", "buffer", ".", "flush", "buffer", "if", "too", "small", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L254-L271
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.writeLong
public void writeLong(long value) throws IOException { if (8 > buf.length - pos) { //not enough space remaining byte[] arr = new byte[8]; arr[0] = (byte) value; arr[1] = (byte) (value >> 8); arr[2] = (byte) (value >> 16); arr[3] = (byte) (value >> 24); arr[4] = (byte) (value >> 32); arr[5] = (byte) (value >> 40); arr[6] = (byte) (value >> 48); arr[7] = (byte) (value >> 56); write(arr, 0, 8); return; } buf[pos] = (byte) value; buf[pos + 1] = (byte) (value >> 8); buf[pos + 2] = (byte) (value >> 16); buf[pos + 3] = (byte) (value >> 24); buf[pos + 4] = (byte) (value >> 32); buf[pos + 5] = (byte) (value >> 40); buf[pos + 6] = (byte) (value >> 48); buf[pos + 7] = (byte) (value >> 56); pos += 8; }
java
public void writeLong(long value) throws IOException { if (8 > buf.length - pos) { //not enough space remaining byte[] arr = new byte[8]; arr[0] = (byte) value; arr[1] = (byte) (value >> 8); arr[2] = (byte) (value >> 16); arr[3] = (byte) (value >> 24); arr[4] = (byte) (value >> 32); arr[5] = (byte) (value >> 40); arr[6] = (byte) (value >> 48); arr[7] = (byte) (value >> 56); write(arr, 0, 8); return; } buf[pos] = (byte) value; buf[pos + 1] = (byte) (value >> 8); buf[pos + 2] = (byte) (value >> 16); buf[pos + 3] = (byte) (value >> 24); buf[pos + 4] = (byte) (value >> 32); buf[pos + 5] = (byte) (value >> 40); buf[pos + 6] = (byte) (value >> 48); buf[pos + 7] = (byte) (value >> 56); pos += 8; }
[ "public", "void", "writeLong", "(", "long", "value", ")", "throws", "IOException", "{", "if", "(", "8", ">", "buf", ".", "length", "-", "pos", ")", "{", "//not enough space remaining", "byte", "[", "]", "arr", "=", "new", "byte", "[", "8", "]", ";", ...
Write long value into buffer. flush buffer if too small. @param value long value @throws IOException if socket error occur
[ "Write", "long", "value", "into", "buffer", ".", "flush", "buffer", "if", "too", "small", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L279-L304
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.writeBytes
public void writeBytes(byte value, int len) throws IOException { if (len > buf.length - pos) { //not enough space remaining byte[] arr = new byte[len]; Arrays.fill(arr, value); write(arr, 0, len); return; } for (int i = pos; i < pos + len; i++) { buf[i] = value; } pos += len; }
java
public void writeBytes(byte value, int len) throws IOException { if (len > buf.length - pos) { //not enough space remaining byte[] arr = new byte[len]; Arrays.fill(arr, value); write(arr, 0, len); return; } for (int i = pos; i < pos + len; i++) { buf[i] = value; } pos += len; }
[ "public", "void", "writeBytes", "(", "byte", "value", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "len", ">", "buf", ".", "length", "-", "pos", ")", "{", "//not enough space remaining", "byte", "[", "]", "arr", "=", "new", "byte", ...
Write byte value, len times into buffer. flush buffer if too small. @param value byte value @param len number of time to write value. @throws IOException if socket error occur.
[ "Write", "byte", "value", "len", "times", "into", "buffer", ".", "flush", "buffer", "if", "too", "small", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L313-L326
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.write
public void write(int value) throws IOException { if (pos >= buf.length) { if (pos >= getMaxPacketLength() && !bufferContainDataAfterMark) { //buffer is more than a Packet, must flushBuffer() flushBuffer(false); } else { growBuffer(1); } } buf[pos++] = (byte) value; }
java
public void write(int value) throws IOException { if (pos >= buf.length) { if (pos >= getMaxPacketLength() && !bufferContainDataAfterMark) { //buffer is more than a Packet, must flushBuffer() flushBuffer(false); } else { growBuffer(1); } } buf[pos++] = (byte) value; }
[ "public", "void", "write", "(", "int", "value", ")", "throws", "IOException", "{", "if", "(", "pos", ">=", "buf", ".", "length", ")", "{", "if", "(", "pos", ">=", "getMaxPacketLength", "(", ")", "&&", "!", "bufferContainDataAfterMark", ")", "{", "//buffe...
Write byte into buffer, flush buffer to socket if needed. @param value byte to send @throws IOException if socket error occur.
[ "Write", "byte", "into", "buffer", "flush", "buffer", "to", "socket", "if", "needed", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L413-L423
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.write
public void write(byte[] arr, int off, int len) throws IOException { if (len > buf.length - pos) { if (buf.length != getMaxPacketLength()) { growBuffer(len); } //max buffer size if (len > buf.length - pos) { if (mark != -1) { growBuffer(len); if (mark != -1) { flushBufferStopAtMark(); } } else { //not enough space in buffer, will stream : // fill buffer and flush until all data are snd int remainingLen = len; do { int lenToFillBuffer = Math.min(getMaxPacketLength() - pos, remainingLen); System.arraycopy(arr, off, buf, pos, lenToFillBuffer); remainingLen -= lenToFillBuffer; off += lenToFillBuffer; pos += lenToFillBuffer; if (remainingLen > 0) { flushBuffer(false); } else { break; } } while (true); return; } } } System.arraycopy(arr, off, buf, pos, len); pos += len; }
java
public void write(byte[] arr, int off, int len) throws IOException { if (len > buf.length - pos) { if (buf.length != getMaxPacketLength()) { growBuffer(len); } //max buffer size if (len > buf.length - pos) { if (mark != -1) { growBuffer(len); if (mark != -1) { flushBufferStopAtMark(); } } else { //not enough space in buffer, will stream : // fill buffer and flush until all data are snd int remainingLen = len; do { int lenToFillBuffer = Math.min(getMaxPacketLength() - pos, remainingLen); System.arraycopy(arr, off, buf, pos, lenToFillBuffer); remainingLen -= lenToFillBuffer; off += lenToFillBuffer; pos += lenToFillBuffer; if (remainingLen > 0) { flushBuffer(false); } else { break; } } while (true); return; } } } System.arraycopy(arr, off, buf, pos, len); pos += len; }
[ "public", "void", "write", "(", "byte", "[", "]", "arr", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "if", "(", "len", ">", "buf", ".", "length", "-", "pos", ")", "{", "if", "(", "buf", ".", "length", "!=", "getMaxPac...
Write byte array to buffer. If buffer is full, flush socket. @param arr byte array @param off offset @param len byte length to write @throws IOException if socket error occur
[ "Write", "byte", "array", "to", "buffer", ".", "If", "buffer", "is", "full", "flush", "socket", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L437-L475
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.write
public void write(Reader reader, boolean escape, boolean noBackslashEscapes) throws IOException { char[] buffer = new char[4096]; int len; while ((len = reader.read(buffer)) >= 0) { byte[] data = new String(buffer, 0, len).getBytes("UTF-8"); if (escape) { writeBytesEscaped(data, data.length, noBackslashEscapes); } else { write(data); } } }
java
public void write(Reader reader, boolean escape, boolean noBackslashEscapes) throws IOException { char[] buffer = new char[4096]; int len; while ((len = reader.read(buffer)) >= 0) { byte[] data = new String(buffer, 0, len).getBytes("UTF-8"); if (escape) { writeBytesEscaped(data, data.length, noBackslashEscapes); } else { write(data); } } }
[ "public", "void", "write", "(", "Reader", "reader", ",", "boolean", "escape", ",", "boolean", "noBackslashEscapes", ")", "throws", "IOException", "{", "char", "[", "]", "buffer", "=", "new", "char", "[", "4096", "]", ";", "int", "len", ";", "while", "(",...
Write reader into socket. @param reader reader @param escape must be escape @param noBackslashEscapes escape method @throws IOException if socket error occur
[ "Write", "reader", "into", "socket", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L652-L664
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.writeBytesEscaped
public void writeBytesEscaped(byte[] bytes, int len, boolean noBackslashEscapes) throws IOException { if (len * 2 > buf.length - pos) { //makes buffer bigger (up to 16M) if (buf.length != getMaxPacketLength()) { growBuffer(len * 2); } //data may be bigger than buffer. //must flush buffer when full (and reset position to 0) if (len * 2 > buf.length - pos) { if (mark != -1) { growBuffer(len * 2); if (mark != -1) { flushBufferStopAtMark(); } } else { //not enough space in buffer, will fill buffer if (noBackslashEscapes) { for (int i = 0; i < len; i++) { if (QUOTE == bytes[i]) { buf[pos++] = QUOTE; if (buf.length <= pos) { flushBuffer(false); } } buf[pos++] = bytes[i]; if (buf.length <= pos) { flushBuffer(false); } } } else { for (int i = 0; i < len; i++) { if (bytes[i] == QUOTE || bytes[i] == BACKSLASH || bytes[i] == DBL_QUOTE || bytes[i] == ZERO_BYTE) { buf[pos++] = '\\'; if (buf.length <= pos) { flushBuffer(false); } } buf[pos++] = bytes[i]; if (buf.length <= pos) { flushBuffer(false); } } } return; } } } //sure to have enough place filling buffer directly if (noBackslashEscapes) { for (int i = 0; i < len; i++) { if (QUOTE == bytes[i]) { buf[pos++] = QUOTE; } buf[pos++] = bytes[i]; } } else { for (int i = 0; i < len; i++) { if (bytes[i] == QUOTE || bytes[i] == BACKSLASH || bytes[i] == '"' || bytes[i] == ZERO_BYTE) { buf[pos++] = BACKSLASH; //add escape slash } buf[pos++] = bytes[i]; } } }
java
public void writeBytesEscaped(byte[] bytes, int len, boolean noBackslashEscapes) throws IOException { if (len * 2 > buf.length - pos) { //makes buffer bigger (up to 16M) if (buf.length != getMaxPacketLength()) { growBuffer(len * 2); } //data may be bigger than buffer. //must flush buffer when full (and reset position to 0) if (len * 2 > buf.length - pos) { if (mark != -1) { growBuffer(len * 2); if (mark != -1) { flushBufferStopAtMark(); } } else { //not enough space in buffer, will fill buffer if (noBackslashEscapes) { for (int i = 0; i < len; i++) { if (QUOTE == bytes[i]) { buf[pos++] = QUOTE; if (buf.length <= pos) { flushBuffer(false); } } buf[pos++] = bytes[i]; if (buf.length <= pos) { flushBuffer(false); } } } else { for (int i = 0; i < len; i++) { if (bytes[i] == QUOTE || bytes[i] == BACKSLASH || bytes[i] == DBL_QUOTE || bytes[i] == ZERO_BYTE) { buf[pos++] = '\\'; if (buf.length <= pos) { flushBuffer(false); } } buf[pos++] = bytes[i]; if (buf.length <= pos) { flushBuffer(false); } } } return; } } } //sure to have enough place filling buffer directly if (noBackslashEscapes) { for (int i = 0; i < len; i++) { if (QUOTE == bytes[i]) { buf[pos++] = QUOTE; } buf[pos++] = bytes[i]; } } else { for (int i = 0; i < len; i++) { if (bytes[i] == QUOTE || bytes[i] == BACKSLASH || bytes[i] == '"' || bytes[i] == ZERO_BYTE) { buf[pos++] = BACKSLASH; //add escape slash } buf[pos++] = bytes[i]; } } }
[ "public", "void", "writeBytesEscaped", "(", "byte", "[", "]", "bytes", ",", "int", "len", ",", "boolean", "noBackslashEscapes", ")", "throws", "IOException", "{", "if", "(", "len", "*", "2", ">", "buf", ".", "length", "-", "pos", ")", "{", "//makes buffe...
Write escape bytes to socket. @param bytes bytes @param len len to write @param noBackslashEscapes escape method @throws IOException if socket error occur
[ "Write", "escape", "bytes", "to", "socket", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L698-L776
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.flushBufferStopAtMark
@Override public void flushBufferStopAtMark() throws IOException { final int end = pos; pos = mark; flushBuffer(true); out.flush(); startPacket(0); System.arraycopy(buf, mark, buf, pos, end - mark); pos += end - mark; mark = -1; bufferContainDataAfterMark = true; }
java
@Override public void flushBufferStopAtMark() throws IOException { final int end = pos; pos = mark; flushBuffer(true); out.flush(); startPacket(0); System.arraycopy(buf, mark, buf, pos, end - mark); pos += end - mark; mark = -1; bufferContainDataAfterMark = true; }
[ "@", "Override", "public", "void", "flushBufferStopAtMark", "(", ")", "throws", "IOException", "{", "final", "int", "end", "=", "pos", ";", "pos", "=", "mark", ";", "flushBuffer", "(", "true", ")", ";", "out", ".", "flush", "(", ")", ";", "startPacket", ...
Flush to last mark. @throws IOException if flush fail.
[ "Flush", "to", "last", "mark", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L818-L830
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java
AbstractPacketOutputStream.resetMark
public byte[] resetMark() { mark = -1; if (bufferContainDataAfterMark) { byte[] data = Arrays.copyOfRange(buf, initialPacketPos(), pos); startPacket(0); bufferContainDataAfterMark = false; return data; } return null; }
java
public byte[] resetMark() { mark = -1; if (bufferContainDataAfterMark) { byte[] data = Arrays.copyOfRange(buf, initialPacketPos(), pos); startPacket(0); bufferContainDataAfterMark = false; return data; } return null; }
[ "public", "byte", "[", "]", "resetMark", "(", ")", "{", "mark", "=", "-", "1", ";", "if", "(", "bufferContainDataAfterMark", ")", "{", "byte", "[", "]", "data", "=", "Arrays", ".", "copyOfRange", "(", "buf", ",", "initialPacketPos", "(", ")", ",", "p...
Reset mark flag and send bytes after mark flag. @return bytes after mark flag
[ "Reset", "mark", "flag", "and", "send", "bytes", "after", "mark", "flag", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/AbstractPacketOutputStream.java#L841-L851
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/scheduler/SchedulerServiceProviderHolder.java
SchedulerServiceProviderHolder.getScheduler
public static DynamicSizedSchedulerInterface getScheduler(int initialThreadCount, String poolName, int maximumPoolSize) { return getSchedulerProvider().getScheduler(initialThreadCount, poolName, maximumPoolSize); }
java
public static DynamicSizedSchedulerInterface getScheduler(int initialThreadCount, String poolName, int maximumPoolSize) { return getSchedulerProvider().getScheduler(initialThreadCount, poolName, maximumPoolSize); }
[ "public", "static", "DynamicSizedSchedulerInterface", "getScheduler", "(", "int", "initialThreadCount", ",", "String", "poolName", ",", "int", "maximumPoolSize", ")", "{", "return", "getSchedulerProvider", "(", ")", ".", "getScheduler", "(", "initialThreadCount", ",", ...
Get a Dynamic sized scheduler directly with the current set provider. @param initialThreadCount Number of threads scheduler is allowed to grow to @param poolName name of pool to identify threads @param maximumPoolSize maximum pool size @return Scheduler capable of providing the needed thread count
[ "Get", "a", "Dynamic", "sized", "scheduler", "directly", "with", "the", "current", "set", "provider", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/scheduler/SchedulerServiceProviderHolder.java#L135-L138
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/socket/NamedPipeSocket.java
NamedPipeSocket.connect
public void connect(SocketAddress endpoint, int timeout) throws IOException { String filename; if (host == null || host.equals("localhost")) { filename = "\\\\.\\pipe\\" + name; } else { filename = "\\\\" + host + "\\pipe\\" + name; } //use a default timeout of 100ms if no timeout set. int usedTimeout = timeout == 0 ? 100 : timeout; long initialNano = System.nanoTime(); do { try { file = new RandomAccessFile(filename, "rw"); break; } catch (FileNotFoundException fileNotFoundException) { try { //using JNA if available Kernel32.INSTANCE.WaitNamedPipe(filename, timeout); //then retry connection file = new RandomAccessFile(filename, "rw"); } catch (Throwable cle) { // in case JNA not on classpath, then wait 10ms before next try. if (System.nanoTime() - initialNano > TimeUnit.MILLISECONDS.toNanos(usedTimeout)) { if (timeout == 0) { throw new FileNotFoundException(fileNotFoundException.getMessage() + "\nplease consider set connectTimeout option, so connection can retry having access to named pipe. " + "\n(Named pipe can throw ERROR_PIPE_BUSY error)"); } throw fileNotFoundException; } try { TimeUnit.MILLISECONDS.sleep(5); } catch (InterruptedException interrupted) { IOException ioException = new IOException( "Interruption during connection to named pipe"); ioException.initCause(interrupted); throw ioException; } } } } while (true); is = new InputStream() { @Override public int read(byte[] bytes, int off, int len) throws IOException { return file.read(bytes, off, len); } @Override public int read() throws IOException { return file.read(); } @Override public int read(byte[] bytes) throws IOException { return file.read(bytes); } }; os = new OutputStream() { @Override public void write(byte[] bytes, int off, int len) throws IOException { file.write(bytes, off, len); } @Override public void write(int value) throws IOException { file.write(value); } @Override public void write(byte[] bytes) throws IOException { file.write(bytes); } }; }
java
public void connect(SocketAddress endpoint, int timeout) throws IOException { String filename; if (host == null || host.equals("localhost")) { filename = "\\\\.\\pipe\\" + name; } else { filename = "\\\\" + host + "\\pipe\\" + name; } //use a default timeout of 100ms if no timeout set. int usedTimeout = timeout == 0 ? 100 : timeout; long initialNano = System.nanoTime(); do { try { file = new RandomAccessFile(filename, "rw"); break; } catch (FileNotFoundException fileNotFoundException) { try { //using JNA if available Kernel32.INSTANCE.WaitNamedPipe(filename, timeout); //then retry connection file = new RandomAccessFile(filename, "rw"); } catch (Throwable cle) { // in case JNA not on classpath, then wait 10ms before next try. if (System.nanoTime() - initialNano > TimeUnit.MILLISECONDS.toNanos(usedTimeout)) { if (timeout == 0) { throw new FileNotFoundException(fileNotFoundException.getMessage() + "\nplease consider set connectTimeout option, so connection can retry having access to named pipe. " + "\n(Named pipe can throw ERROR_PIPE_BUSY error)"); } throw fileNotFoundException; } try { TimeUnit.MILLISECONDS.sleep(5); } catch (InterruptedException interrupted) { IOException ioException = new IOException( "Interruption during connection to named pipe"); ioException.initCause(interrupted); throw ioException; } } } } while (true); is = new InputStream() { @Override public int read(byte[] bytes, int off, int len) throws IOException { return file.read(bytes, off, len); } @Override public int read() throws IOException { return file.read(); } @Override public int read(byte[] bytes) throws IOException { return file.read(bytes); } }; os = new OutputStream() { @Override public void write(byte[] bytes, int off, int len) throws IOException { file.write(bytes, off, len); } @Override public void write(int value) throws IOException { file.write(value); } @Override public void write(byte[] bytes) throws IOException { file.write(bytes); } }; }
[ "public", "void", "connect", "(", "SocketAddress", "endpoint", ",", "int", "timeout", ")", "throws", "IOException", "{", "String", "filename", ";", "if", "(", "host", "==", "null", "||", "host", ".", "equals", "(", "\"localhost\"", ")", ")", "{", "filename...
Name pipe connection. @param endpoint endPoint @param timeout timeout in milliseconds @throws IOException exception
[ "Name", "pipe", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/socket/NamedPipeSocket.java#L100-L176
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/parameters/SerializableParameter.java
SerializableParameter.writeTo
public void writeTo(final PacketOutputStream pos) throws IOException { if (loadedStream == null) { writeObjectToBytes(); } pos.write(BINARY_INTRODUCER); pos.writeBytesEscaped(loadedStream, loadedStream.length, noBackSlashEscapes); pos.write(QUOTE); }
java
public void writeTo(final PacketOutputStream pos) throws IOException { if (loadedStream == null) { writeObjectToBytes(); } pos.write(BINARY_INTRODUCER); pos.writeBytesEscaped(loadedStream, loadedStream.length, noBackSlashEscapes); pos.write(QUOTE); }
[ "public", "void", "writeTo", "(", "final", "PacketOutputStream", "pos", ")", "throws", "IOException", "{", "if", "(", "loadedStream", "==", "null", ")", "{", "writeObjectToBytes", "(", ")", ";", "}", "pos", ".", "write", "(", "BINARY_INTRODUCER", ")", ";", ...
Write object to buffer for text protocol. @param pos the stream to write to @throws IOException if error reading stream
[ "Write", "object", "to", "buffer", "for", "text", "protocol", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/SerializableParameter.java#L78-L86
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/util/dao/ServerPrepareResult.java
ServerPrepareResult.failover
public void failover(int statementId, Protocol unProxiedProtocol) { this.statementId = statementId; this.unProxiedProtocol = unProxiedProtocol; this.parameterTypeHeader = new ColumnType[parameters.length]; this.shareCounter = 1; this.isBeingDeallocate = false; }
java
public void failover(int statementId, Protocol unProxiedProtocol) { this.statementId = statementId; this.unProxiedProtocol = unProxiedProtocol; this.parameterTypeHeader = new ColumnType[parameters.length]; this.shareCounter = 1; this.isBeingDeallocate = false; }
[ "public", "void", "failover", "(", "int", "statementId", ",", "Protocol", "unProxiedProtocol", ")", "{", "this", ".", "statementId", "=", "statementId", ";", "this", ".", "unProxiedProtocol", "=", "unProxiedProtocol", ";", "this", ".", "parameterTypeHeader", "=", ...
Update information after a failover. @param statementId new statement Id @param unProxiedProtocol the protocol on which the prepare has been done
[ "Update", "information", "after", "a", "failover", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/util/dao/ServerPrepareResult.java#L103-L110
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java
MariaDbResultSetMetaData.isNullable
public int isNullable(final int column) throws SQLException { if ((getColumnInformation(column).getFlags() & ColumnFlags.NOT_NULL) == 0) { return ResultSetMetaData.columnNullable; } else { return ResultSetMetaData.columnNoNulls; } }
java
public int isNullable(final int column) throws SQLException { if ((getColumnInformation(column).getFlags() & ColumnFlags.NOT_NULL) == 0) { return ResultSetMetaData.columnNullable; } else { return ResultSetMetaData.columnNoNulls; } }
[ "public", "int", "isNullable", "(", "final", "int", "column", ")", "throws", "SQLException", "{", "if", "(", "(", "getColumnInformation", "(", "column", ")", ".", "getFlags", "(", ")", "&", "ColumnFlags", ".", "NOT_NULL", ")", "==", "0", ")", "{", "retur...
Indicates the nullability of values in the designated column. @param column the first column is 1, the second is 2, ... @return the nullability status of the given column; one of <code>columnNoNulls</code>, <code>columnNullable</code> or <code>columnNullableUnknown</code> @throws SQLException if a database access error occurs
[ "Indicates", "the", "nullability", "of", "values", "in", "the", "designated", "column", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java#L144-L150
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java
MariaDbResultSetMetaData.getTableName
public String getTableName(final int column) throws SQLException { if (returnTableAlias) { return getColumnInformation(column).getTable(); } else { return getColumnInformation(column).getOriginalTable(); } }
java
public String getTableName(final int column) throws SQLException { if (returnTableAlias) { return getColumnInformation(column).getTable(); } else { return getColumnInformation(column).getOriginalTable(); } }
[ "public", "String", "getTableName", "(", "final", "int", "column", ")", "throws", "SQLException", "{", "if", "(", "returnTableAlias", ")", "{", "return", "getColumnInformation", "(", "column", ")", ".", "getTable", "(", ")", ";", "}", "else", "{", "return", ...
Gets the designated column's table name. @param column the first column is 1, the second is 2, ... @return table name or "" if not applicable @throws SQLException if a database access error occurs
[ "Gets", "the", "designated", "column", "s", "table", "name", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java#L255-L261
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java
MariaDbResultSetMetaData.getColumnType
public int getColumnType(final int column) throws SQLException { ColumnInformation ci = getColumnInformation(column); switch (ci.getColumnType()) { case BIT: if (ci.getLength() == 1) { return Types.BIT; } return Types.VARBINARY; case TINYINT: if (ci.getLength() == 1 && options.tinyInt1isBit) { return Types.BIT; } return Types.TINYINT; case YEAR: if (options.yearIsDateType) { return Types.DATE; } return Types.SMALLINT; case BLOB: if (ci.getLength() < 0 || ci.getLength() > 16777215) { return Types.LONGVARBINARY; } return Types.VARBINARY; case VARCHAR: case VARSTRING: if (ci.isBinary()) { return Types.VARBINARY; } if (ci.getLength() < 0) { return Types.LONGVARCHAR; } return Types.VARCHAR; case STRING: if (ci.isBinary()) { return Types.BINARY; } return Types.CHAR; default: return ci.getColumnType().getSqlType(); } }
java
public int getColumnType(final int column) throws SQLException { ColumnInformation ci = getColumnInformation(column); switch (ci.getColumnType()) { case BIT: if (ci.getLength() == 1) { return Types.BIT; } return Types.VARBINARY; case TINYINT: if (ci.getLength() == 1 && options.tinyInt1isBit) { return Types.BIT; } return Types.TINYINT; case YEAR: if (options.yearIsDateType) { return Types.DATE; } return Types.SMALLINT; case BLOB: if (ci.getLength() < 0 || ci.getLength() > 16777215) { return Types.LONGVARBINARY; } return Types.VARBINARY; case VARCHAR: case VARSTRING: if (ci.isBinary()) { return Types.VARBINARY; } if (ci.getLength() < 0) { return Types.LONGVARCHAR; } return Types.VARCHAR; case STRING: if (ci.isBinary()) { return Types.BINARY; } return Types.CHAR; default: return ci.getColumnType().getSqlType(); } }
[ "public", "int", "getColumnType", "(", "final", "int", "column", ")", "throws", "SQLException", "{", "ColumnInformation", "ci", "=", "getColumnInformation", "(", "column", ")", ";", "switch", "(", "ci", ".", "getColumnType", "(", ")", ")", "{", "case", "BIT"...
Retrieves the designated column's SQL type. @param column the first column is 1, the second is 2, ... @return SQL type from java.sql.Types @throws SQLException if a database access error occurs @see Types
[ "Retrieves", "the", "designated", "column", "s", "SQL", "type", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbResultSetMetaData.java#L276-L317
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java
MariaDbDatabaseMetaData.skipWhite
private static int skipWhite(char[] part, int startPos) { for (int i = startPos; i < part.length; i++) { if (!Character.isWhitespace(part[i])) { return i; } } return part.length; }
java
private static int skipWhite(char[] part, int startPos) { for (int i = startPos; i < part.length; i++) { if (!Character.isWhitespace(part[i])) { return i; } } return part.length; }
[ "private", "static", "int", "skipWhite", "(", "char", "[", "]", "part", ",", "int", "startPos", ")", "{", "for", "(", "int", "i", "=", "startPos", ";", "i", "<", "part", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "Character", ".", ...
Return new position, or -1 on error
[ "Return", "new", "position", "or", "-", "1", "on", "error" ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java#L116-L123
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java
MariaDbDatabaseMetaData.catalogCond
private String catalogCond(String columnName, String catalog) { if (catalog == null) { /* Treat null catalog as current */ if (connection.nullCatalogMeansCurrent) { return "(ISNULL(database()) OR (" + columnName + " = database()))"; } return "(1 = 1)"; } if (catalog.isEmpty()) { return "(ISNULL(database()) OR (" + columnName + " = database()))"; } return "(" + columnName + " = " + escapeQuote(catalog) + ")"; }
java
private String catalogCond(String columnName, String catalog) { if (catalog == null) { /* Treat null catalog as current */ if (connection.nullCatalogMeansCurrent) { return "(ISNULL(database()) OR (" + columnName + " = database()))"; } return "(1 = 1)"; } if (catalog.isEmpty()) { return "(ISNULL(database()) OR (" + columnName + " = database()))"; } return "(" + columnName + " = " + escapeQuote(catalog) + ")"; }
[ "private", "String", "catalogCond", "(", "String", "columnName", ",", "String", "catalog", ")", "{", "if", "(", "catalog", "==", "null", ")", "{", "/* Treat null catalog as current */", "if", "(", "connection", ".", "nullCatalogMeansCurrent", ")", "{", "return", ...
Generate part of the information schema query that restricts catalog names In the driver, catalogs is the equivalent to MariaDB schemas. @param columnName - column name in the information schema table @param catalog - catalog name. This driver does not (always) follow JDBC standard for following special values, due to ConnectorJ compatibility 1. empty string ("") - matches current catalog (i.e database). JDBC standard says only tables without catalog should be returned - such tables do not exist in MariaDB. If there is no current catalog, then empty string matches any catalog. 2. null - if nullCatalogMeansCurrent=true (which is the default), then the handling is the same as for "" . i.e return current catalog.JDBC-conforming way would be to match any catalog with null parameter. This can be switched with nullCatalogMeansCurrent=false in the connection URL. @return part of SQL query ,that restricts search for the catalog.
[ "Generate", "part", "of", "the", "information", "schema", "query", "that", "restricts", "catalog", "names", "In", "the", "driver", "catalogs", "is", "the", "equivalent", "to", "MariaDB", "schemas", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java#L502-L515
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java
MariaDbDatabaseMetaData.getPseudoColumns
public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { return connection.createStatement().executeQuery( "SELECT ' ' TABLE_CAT, ' ' TABLE_SCHEM," + "' ' TABLE_NAME, ' ' COLUMN_NAME, 0 DATA_TYPE, 0 COLUMN_SIZE, 0 DECIMAL_DIGITS," + "10 NUM_PREC_RADIX, ' ' COLUMN_USAGE, ' ' REMARKS, 0 CHAR_OCTET_LENGTH, 'YES' IS_NULLABLE FROM DUAL " + "WHERE 1=0"); }
java
public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { return connection.createStatement().executeQuery( "SELECT ' ' TABLE_CAT, ' ' TABLE_SCHEM," + "' ' TABLE_NAME, ' ' COLUMN_NAME, 0 DATA_TYPE, 0 COLUMN_SIZE, 0 DECIMAL_DIGITS," + "10 NUM_PREC_RADIX, ' ' COLUMN_USAGE, ' ' REMARKS, 0 CHAR_OCTET_LENGTH, 'YES' IS_NULLABLE FROM DUAL " + "WHERE 1=0"); }
[ "public", "ResultSet", "getPseudoColumns", "(", "String", "catalog", ",", "String", "schemaPattern", ",", "String", "tableNamePattern", ",", "String", "columnNamePattern", ")", "throws", "SQLException", "{", "return", "connection", ".", "createStatement", "(", ")", ...
Retrieves a description of the pseudo or hidden columns available in a given table within the specified catalog and schema. Pseudo or hidden columns may not always be stored within a table and are not visible in a ResultSet unless they are specified in the query's outermost SELECT list. Pseudo or hidden columns may not necessarily be able to be modified. If there are no pseudo or hidden columns, an empty ResultSet is returned. <P>Only column descriptions matching the catalog, schema, table and column name criteria are returned. They are ordered by <code>TABLE_CAT</code>,<code>TABLE_SCHEM</code>, <code>TABLE_NAME</code> and <code>COLUMN_NAME</code>.</P> <P>Each column description has the following columns:</P> <OL> <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>) <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>) <LI><B>TABLE_NAME</B> String {@code =>} table name <LI><B>COLUMN_NAME</B> String {@code =>} column name <LI><B>DATA_TYPE</B> int {@code =>} SQL type from java.sql.Types <LI><B>COLUMN_SIZE</B> int {@code =>} column size. <LI><B>DECIMAL_DIGITS</B> int {@code =>} the number of fractional digits. Null is returned for data types where DECIMAL_DIGITS is not applicable. <LI><B>NUM_PREC_RADIX</B> int {@code =>} Radix (typically either 10 or 2) <LI><B>COLUMN_USAGE</B> String {@code =>} The allowed usage for the column. The value returned will correspond to the enum name returned by PseudoColumnUsage.name() <LI><B>REMARKS</B> String {@code =>} comment describing column (may be <code>null</code>) <LI><B>CHAR_OCTET_LENGTH</B> int {@code =>} for char types the maximum number of bytes in the column <LI><B>IS_NULLABLE</B> String {@code =>} ISO rules are used to determine the nullability for a column. <UL> <LI> YES --- if the column can include NULLs <LI> NO --- if the column cannot include NULLs <LI> empty string --- if the nullability for the column is unknown </UL> </OL> <p>The COLUMN_SIZE column specifies the column size for the given column. For numeric data, this is the maximum precision. For character data, this is the length in characters. For datetime datatypes, this is the length in characters of the String representation (assuming the maximum allowed precision of the fractional seconds component). For binary data, this is the length in bytes. For the ROWID datatype, this is the length in bytes. Null is returned for data types where the column size is not applicable.</p> @param catalog a catalog name; must match the catalog name as it is stored in the database; "" retrieves those without a catalog; <code>null</code> means that the catalog name should not be used to narrow the search @param schemaPattern a schema name pattern; must match the schema name as it is stored in the database; "" retrieves those without a schema; <code>null</code> means that the schema name should not be used to narrow the search @param tableNamePattern a table name pattern; must match the table name as it is stored in the database @param columnNamePattern a column name pattern; must match the column name as it is stored in the database @return <code>ResultSet</code> - each row is a column description @throws SQLException if a database access error occurs @see PseudoColumnUsage @since 1.7
[ "Retrieves", "a", "description", "of", "the", "pseudo", "or", "hidden", "columns", "available", "in", "a", "given", "table", "within", "the", "specified", "catalog", "and", "schema", ".", "Pseudo", "or", "hidden", "columns", "may", "not", "always", "be", "st...
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java#L1085-L1092
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java
MariaDbDatabaseMetaData.getDatabaseProductName
public String getDatabaseProductName() throws SQLException { if (urlParser.getOptions().useMysqlMetadata) { return "MySQL"; } if (connection.getProtocol().isServerMariaDb() && connection.getProtocol().getServerVersion().toLowerCase(Locale.ROOT).contains("mariadb")) { return "MariaDB"; } return "MySQL"; }
java
public String getDatabaseProductName() throws SQLException { if (urlParser.getOptions().useMysqlMetadata) { return "MySQL"; } if (connection.getProtocol().isServerMariaDb() && connection.getProtocol().getServerVersion().toLowerCase(Locale.ROOT).contains("mariadb")) { return "MariaDB"; } return "MySQL"; }
[ "public", "String", "getDatabaseProductName", "(", ")", "throws", "SQLException", "{", "if", "(", "urlParser", ".", "getOptions", "(", ")", ".", "useMysqlMetadata", ")", "{", "return", "\"MySQL\"", ";", "}", "if", "(", "connection", ".", "getProtocol", "(", ...
Return Server type. MySQL or MariaDB. MySQL can be forced for compatibility with option "useMysqlMetadata" @return server type @throws SQLException in case of socket error.
[ "Return", "Server", "type", ".", "MySQL", "or", "MariaDB", ".", "MySQL", "can", "be", "forced", "for", "compatibility", "with", "option", "useMysqlMetadata" ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java#L1138-L1147
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java
MariaDbDatabaseMetaData.getVersionColumns
public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { String sql = "SELECT 0 SCOPE, ' ' COLUMN_NAME, 0 DATA_TYPE," + " ' ' TYPE_NAME, 0 COLUMN_SIZE, 0 BUFFER_LENGTH," + " 0 DECIMAL_DIGITS, 0 PSEUDO_COLUMN " + " FROM DUAL WHERE 1 = 0"; return executeQuery(sql); }
java
public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { String sql = "SELECT 0 SCOPE, ' ' COLUMN_NAME, 0 DATA_TYPE," + " ' ' TYPE_NAME, 0 COLUMN_SIZE, 0 BUFFER_LENGTH," + " 0 DECIMAL_DIGITS, 0 PSEUDO_COLUMN " + " FROM DUAL WHERE 1 = 0"; return executeQuery(sql); }
[ "public", "ResultSet", "getVersionColumns", "(", "String", "catalog", ",", "String", "schema", ",", "String", "table", ")", "throws", "SQLException", "{", "String", "sql", "=", "\"SELECT 0 SCOPE, ' ' COLUMN_NAME, 0 DATA_TYPE,\"", "+", "\" ' ' TYPE_NAME, 0 COLUMN_SIZE, 0 BUF...
Retrieves a description of a table's columns that are automatically updated when any value in a row is updated. They are unordered. <P>Each column description has the following columns:</p> <OL> <LI><B>SCOPE</B> short {@code =>} is not used <LI><B>COLUMN_NAME</B> String {@code =>} column name <LI><B>DATA_TYPE</B> int {@code =>} SQL data type from <code>java.sql.Types</code> <LI><B>TYPE_NAME</B> String {@code =>} Data source-dependent type name <LI><B>COLUMN_SIZE</B> int {@code =>} precision <LI><B>BUFFER_LENGTH</B> int {@code =>} length of column value in bytes <LI><B>DECIMAL_DIGITS</B> short {@code =>} scale - Null is returned for data types where DECIMAL_DIGITS is not applicable. <LI><B>PSEUDO_COLUMN</B> short {@code =>} whether this is pseudo column like an Oracle ROWID <UL> <LI> versionColumnUnknown - may or may not be pseudo column <LI> versionColumnNotPseudo - is NOT a pseudo column <LI> versionColumnPseudo - is a pseudo column </UL> </OL> <p>The COLUMN_SIZE column represents the specified column size for the given column. For numeric data, this is the maximum precision. For character data, this is the length in characters. For datetime datatypes, this is the length in characters of the String representation (assuming the maximum allowed precision of the fractional seconds component). For binary data, this is the length in bytes. For the ROWID datatype, this is the length in bytes. Null is returned for data types where the column size is not applicable.</p> @param catalog a catalog name; must match the catalog name as it is stored in the database; "" retrieves those without a catalog;<code>null</code> means that the catalog name should not be used to narrow the search @param schema a schema name; must match the schema name as it is stored in the database; "" retrieves those without a schema; <code>null</code> means that the schema name should not be used to narrow the search @param table a table name; must match the table name as it is stored in the database @return a <code>ResultSet</code> object in which each row is a column description @throws SQLException if a database access error occurs
[ "Retrieves", "a", "description", "of", "a", "table", "s", "columns", "that", "are", "automatically", "updated", "when", "any", "value", "in", "a", "row", "is", "updated", ".", "They", "are", "unordered", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDatabaseMetaData.java#L2183-L2191
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/tls/SslFactory.java
SslFactory.getSslSocketFactory
public static SSLSocketFactory getSslSocketFactory(Options options) throws SQLException { TrustManager[] trustManager = null; KeyManager[] keyManager = null; if (options.trustServerCertificate || options.serverSslCert != null || options.trustStore != null) { trustManager = new X509TrustManager[]{new MariaDbX509TrustManager(options)}; } if (options.keyStore != null) { keyManager = new KeyManager[]{ loadClientCerts(options.keyStore, options.keyStorePassword, options.keyPassword, options.keyStoreType)}; } else { String keyStore = System.getProperty("javax.net.ssl.keyStore"); String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); if (keyStore != null) { try { keyManager = new KeyManager[]{ loadClientCerts(keyStore, keyStorePassword, keyStorePassword, options.keyStoreType)}; } catch (SQLException queryException) { keyManager = null; logger.error("Error loading keymanager from system properties", queryException); } } } try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManager, trustManager, null); return sslContext.getSocketFactory(); } catch (KeyManagementException keyManagementEx) { throw ExceptionMapper.connException("Could not initialize SSL context", keyManagementEx); } catch (NoSuchAlgorithmException noSuchAlgorithmEx) { throw ExceptionMapper .connException("SSLContext TLS Algorithm not unknown", noSuchAlgorithmEx); } }
java
public static SSLSocketFactory getSslSocketFactory(Options options) throws SQLException { TrustManager[] trustManager = null; KeyManager[] keyManager = null; if (options.trustServerCertificate || options.serverSslCert != null || options.trustStore != null) { trustManager = new X509TrustManager[]{new MariaDbX509TrustManager(options)}; } if (options.keyStore != null) { keyManager = new KeyManager[]{ loadClientCerts(options.keyStore, options.keyStorePassword, options.keyPassword, options.keyStoreType)}; } else { String keyStore = System.getProperty("javax.net.ssl.keyStore"); String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); if (keyStore != null) { try { keyManager = new KeyManager[]{ loadClientCerts(keyStore, keyStorePassword, keyStorePassword, options.keyStoreType)}; } catch (SQLException queryException) { keyManager = null; logger.error("Error loading keymanager from system properties", queryException); } } } try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManager, trustManager, null); return sslContext.getSocketFactory(); } catch (KeyManagementException keyManagementEx) { throw ExceptionMapper.connException("Could not initialize SSL context", keyManagementEx); } catch (NoSuchAlgorithmException noSuchAlgorithmEx) { throw ExceptionMapper .connException("SSLContext TLS Algorithm not unknown", noSuchAlgorithmEx); } }
[ "public", "static", "SSLSocketFactory", "getSslSocketFactory", "(", "Options", "options", ")", "throws", "SQLException", "{", "TrustManager", "[", "]", "trustManager", "=", "null", ";", "KeyManager", "[", "]", "keyManager", "=", "null", ";", "if", "(", "options"...
Create an SSL factory according to connection string options. @param options connection options @return SSL socket factory @throws SQLException in case of error initializing context.
[ "Create", "an", "SSL", "factory", "according", "to", "connection", "string", "options", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/tls/SslFactory.java#L34-L71
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java
ClientSidePreparedStatement.clearBatch
@Override public void clearBatch() { parameterList.clear(); hasLongData = false; this.parameters = new ParameterHolder[prepareResult.getParamCount()]; }
java
@Override public void clearBatch() { parameterList.clear(); hasLongData = false; this.parameters = new ParameterHolder[prepareResult.getParamCount()]; }
[ "@", "Override", "public", "void", "clearBatch", "(", ")", "{", "parameterList", ".", "clear", "(", ")", ";", "hasLongData", "=", "false", ";", "this", ".", "parameters", "=", "new", "ParameterHolder", "[", "prepareResult", ".", "getParamCount", "(", ")", ...
Clear batch.
[ "Clear", "batch", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java#L277-L282
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java
ClientSidePreparedStatement.executeInternalBatch
private void executeInternalBatch(int size) throws SQLException { executeQueryPrologue(true); results = new Results(this, 0, true, size, false, resultSetScrollType, resultSetConcurrency, autoGeneratedKeys, protocol.getAutoIncrementIncrement()); if (protocol .executeBatchClient(protocol.isMasterConnection(), results, prepareResult, parameterList, hasLongData)) { return; } //send query one by one, reading results for each query before sending another one SQLException exception = null; if (queryTimeout > 0) { for (int batchQueriesCount = 0; batchQueriesCount < size; batchQueriesCount++) { protocol.stopIfInterrupted(); try { protocol.executeQuery(protocol.isMasterConnection(), results, prepareResult, parameterList.get(batchQueriesCount)); } catch (SQLException e) { if (options.continueBatchOnError) { exception = e; } else { throw e; } } } } else { for (int batchQueriesCount = 0; batchQueriesCount < size; batchQueriesCount++) { try { protocol.executeQuery(protocol.isMasterConnection(), results, prepareResult, parameterList.get(batchQueriesCount)); } catch (SQLException e) { if (options.continueBatchOnError) { exception = e; } else { throw e; } } } } if (exception != null) { throw exception; } }
java
private void executeInternalBatch(int size) throws SQLException { executeQueryPrologue(true); results = new Results(this, 0, true, size, false, resultSetScrollType, resultSetConcurrency, autoGeneratedKeys, protocol.getAutoIncrementIncrement()); if (protocol .executeBatchClient(protocol.isMasterConnection(), results, prepareResult, parameterList, hasLongData)) { return; } //send query one by one, reading results for each query before sending another one SQLException exception = null; if (queryTimeout > 0) { for (int batchQueriesCount = 0; batchQueriesCount < size; batchQueriesCount++) { protocol.stopIfInterrupted(); try { protocol.executeQuery(protocol.isMasterConnection(), results, prepareResult, parameterList.get(batchQueriesCount)); } catch (SQLException e) { if (options.continueBatchOnError) { exception = e; } else { throw e; } } } } else { for (int batchQueriesCount = 0; batchQueriesCount < size; batchQueriesCount++) { try { protocol.executeQuery(protocol.isMasterConnection(), results, prepareResult, parameterList.get(batchQueriesCount)); } catch (SQLException e) { if (options.continueBatchOnError) { exception = e; } else { throw e; } } } } if (exception != null) { throw exception; } }
[ "private", "void", "executeInternalBatch", "(", "int", "size", ")", "throws", "SQLException", "{", "executeQueryPrologue", "(", "true", ")", ";", "results", "=", "new", "Results", "(", "this", ",", "0", ",", "true", ",", "size", ",", "false", ",", "resultS...
Choose better way to execute queries according to query and options. @param size parameters number @throws SQLException if any error occur
[ "Choose", "better", "way", "to", "execute", "queries", "according", "to", "query", "and", "options", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java#L355-L401
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java
ClientSidePreparedStatement.setParameter
public void setParameter(final int parameterIndex, final ParameterHolder holder) throws SQLException { if (parameterIndex >= 1 && parameterIndex < prepareResult.getParamCount() + 1) { parameters[parameterIndex - 1] = holder; } else { String error = "Could not set parameter at position " + parameterIndex + " (values was " + holder.toString() + ")\n" + "Query - conn:" + protocol.getServerThreadId() + "(" + (protocol.isMasterConnection() ? "M" : "S") + ") "; if (options.maxQuerySizeToLog > 0) { error += " - \""; if (sqlQuery.length() < options.maxQuerySizeToLog) { error += sqlQuery; } else { error += sqlQuery.substring(0, options.maxQuerySizeToLog) + "..."; } error += "\""; } else { error += " - \"" + sqlQuery + "\""; } logger.error(error); throw ExceptionMapper.getSqlException(error); } }
java
public void setParameter(final int parameterIndex, final ParameterHolder holder) throws SQLException { if (parameterIndex >= 1 && parameterIndex < prepareResult.getParamCount() + 1) { parameters[parameterIndex - 1] = holder; } else { String error = "Could not set parameter at position " + parameterIndex + " (values was " + holder.toString() + ")\n" + "Query - conn:" + protocol.getServerThreadId() + "(" + (protocol.isMasterConnection() ? "M" : "S") + ") "; if (options.maxQuerySizeToLog > 0) { error += " - \""; if (sqlQuery.length() < options.maxQuerySizeToLog) { error += sqlQuery; } else { error += sqlQuery.substring(0, options.maxQuerySizeToLog) + "..."; } error += "\""; } else { error += " - \"" + sqlQuery + "\""; } logger.error(error); throw ExceptionMapper.getSqlException(error); } }
[ "public", "void", "setParameter", "(", "final", "int", "parameterIndex", ",", "final", "ParameterHolder", "holder", ")", "throws", "SQLException", "{", "if", "(", "parameterIndex", ">=", "1", "&&", "parameterIndex", "<", "prepareResult", ".", "getParamCount", "(",...
Set parameter. @param parameterIndex index @param holder parameter holder @throws SQLException if index position doesn't correspond to query parameters
[ "Set", "parameter", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java#L442-L467
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java
ClientSidePreparedStatement.close
@Override public void close() throws SQLException { super.close(); if (connection == null || connection.pooledConnection == null || connection.pooledConnection.noStmtEventListeners()) { return; } connection.pooledConnection.fireStatementClosed(this); connection = null; }
java
@Override public void close() throws SQLException { super.close(); if (connection == null || connection.pooledConnection == null || connection.pooledConnection.noStmtEventListeners()) { return; } connection.pooledConnection.fireStatementClosed(this); connection = null; }
[ "@", "Override", "public", "void", "close", "(", ")", "throws", "SQLException", "{", "super", ".", "close", "(", ")", ";", "if", "(", "connection", "==", "null", "||", "connection", ".", "pooledConnection", "==", "null", "||", "connection", ".", "pooledCon...
Close prepared statement, maybe fire closed-statement events
[ "Close", "prepared", "statement", "maybe", "fire", "closed", "-", "statement", "events" ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/ClientSidePreparedStatement.java#L520-L529
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/output/CompressPacketOutputStream.java
CompressPacketOutputStream.writeEmptyPacket
public void writeEmptyPacket() throws IOException { buf[0] = (byte) 4; buf[1] = (byte) 0x00; buf[2] = (byte) 0x00; buf[3] = (byte) this.compressSeqNo++; buf[4] = (byte) 0x00; buf[5] = (byte) 0x00; buf[6] = (byte) 0x00; buf[7] = (byte) 0x00; buf[8] = (byte) 0x00; buf[9] = (byte) 0x00; buf[10] = (byte) this.seqNo++; out.write(buf, 0, 11); if (traceCache != null) { traceCache.put(new TraceObject(true, COMPRESSED_PROTOCOL_NOT_COMPRESSED_PACKET, Arrays.copyOfRange(buf, 0, 11))); } if (logger.isTraceEnabled()) { logger.trace("send uncompress:{}{}", serverThreadLog, Utils.hexdump(maxQuerySizeToLog, 0, 11, buf)); } }
java
public void writeEmptyPacket() throws IOException { buf[0] = (byte) 4; buf[1] = (byte) 0x00; buf[2] = (byte) 0x00; buf[3] = (byte) this.compressSeqNo++; buf[4] = (byte) 0x00; buf[5] = (byte) 0x00; buf[6] = (byte) 0x00; buf[7] = (byte) 0x00; buf[8] = (byte) 0x00; buf[9] = (byte) 0x00; buf[10] = (byte) this.seqNo++; out.write(buf, 0, 11); if (traceCache != null) { traceCache.put(new TraceObject(true, COMPRESSED_PROTOCOL_NOT_COMPRESSED_PACKET, Arrays.copyOfRange(buf, 0, 11))); } if (logger.isTraceEnabled()) { logger.trace("send uncompress:{}{}", serverThreadLog, Utils.hexdump(maxQuerySizeToLog, 0, 11, buf)); } }
[ "public", "void", "writeEmptyPacket", "(", ")", "throws", "IOException", "{", "buf", "[", "0", "]", "=", "(", "byte", ")", "4", ";", "buf", "[", "1", "]", "=", "(", "byte", ")", "0x00", ";", "buf", "[", "2", "]", "=", "(", "byte", ")", "0x00", ...
Write an empty packet. @throws IOException if socket error occur.
[ "Write", "an", "empty", "packet", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/output/CompressPacketOutputStream.java#L394-L418
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/authentication/DefaultAuthenticationProvider.java
DefaultAuthenticationProvider.processAuthPlugin
public static AuthenticationPlugin processAuthPlugin(String plugin, String password, byte[] authData, Options options) throws SQLException { switch (plugin) { case MYSQL_NATIVE_PASSWORD: return new NativePasswordPlugin(password, authData, options.passwordCharacterEncoding); case MYSQL_OLD_PASSWORD: return new OldPasswordPlugin(password, authData); case MYSQL_CLEAR_PASSWORD: return new ClearPasswordPlugin(password, options.passwordCharacterEncoding); case DIALOG: return new SendPamAuthPacket(password, authData, options.passwordCharacterEncoding); case GSSAPI_CLIENT: return new SendGssApiAuthPacket(authData, options.servicePrincipalName); case MYSQL_ED25519_PASSWORD: return new Ed25519PasswordPlugin(password, authData, options.passwordCharacterEncoding); default: throw new SQLException( "Client does not support authentication protocol requested by server. " + "Consider upgrading MariaDB client. plugin was = " + plugin, "08004", 1251); } }
java
public static AuthenticationPlugin processAuthPlugin(String plugin, String password, byte[] authData, Options options) throws SQLException { switch (plugin) { case MYSQL_NATIVE_PASSWORD: return new NativePasswordPlugin(password, authData, options.passwordCharacterEncoding); case MYSQL_OLD_PASSWORD: return new OldPasswordPlugin(password, authData); case MYSQL_CLEAR_PASSWORD: return new ClearPasswordPlugin(password, options.passwordCharacterEncoding); case DIALOG: return new SendPamAuthPacket(password, authData, options.passwordCharacterEncoding); case GSSAPI_CLIENT: return new SendGssApiAuthPacket(authData, options.servicePrincipalName); case MYSQL_ED25519_PASSWORD: return new Ed25519PasswordPlugin(password, authData, options.passwordCharacterEncoding); default: throw new SQLException( "Client does not support authentication protocol requested by server. " + "Consider upgrading MariaDB client. plugin was = " + plugin, "08004", 1251); } }
[ "public", "static", "AuthenticationPlugin", "processAuthPlugin", "(", "String", "plugin", ",", "String", "password", ",", "byte", "[", "]", "authData", ",", "Options", "options", ")", "throws", "SQLException", "{", "switch", "(", "plugin", ")", "{", "case", "M...
Process AuthenticationSwitch. @param plugin plugin name @param password password @param authData auth data @param options connection string options @return authentication response according to parameters @throws SQLException if error occur.
[ "Process", "AuthenticationSwitch", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/authentication/DefaultAuthenticationProvider.java#L86-L110
train