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/internal/protocol/AuroraProtocol.java
AuroraProtocol.searchProbableMaster
private static void searchProbableMaster(AuroraListener listener, final GlobalStateInfo globalInfo, HostAddress probableMaster) { AuroraProtocol protocol = getNewProtocol(listener.getProxy(), globalInfo, listener.getUrlParser()); try { protocol.setHostAddress(probableMaster); protocol.connect(); listener.removeFromBlacklist(protocol.getHostAddress()); if (listener.isMasterHostFailReconnect() && protocol.isMasterConnection()) { protocol.setMustBeMasterConnection(true); listener.foundActiveMaster(protocol); } else if (listener.isSecondaryHostFailReconnect() && !protocol.isMasterConnection()) { protocol.setMustBeMasterConnection(false); listener.foundActiveSecondary(protocol); } else { protocol.close(); protocol = getNewProtocol(listener.getProxy(), globalInfo, listener.getUrlParser()); } } catch (SQLException e) { listener.addToBlacklist(protocol.getHostAddress()); } }
java
private static void searchProbableMaster(AuroraListener listener, final GlobalStateInfo globalInfo, HostAddress probableMaster) { AuroraProtocol protocol = getNewProtocol(listener.getProxy(), globalInfo, listener.getUrlParser()); try { protocol.setHostAddress(probableMaster); protocol.connect(); listener.removeFromBlacklist(protocol.getHostAddress()); if (listener.isMasterHostFailReconnect() && protocol.isMasterConnection()) { protocol.setMustBeMasterConnection(true); listener.foundActiveMaster(protocol); } else if (listener.isSecondaryHostFailReconnect() && !protocol.isMasterConnection()) { protocol.setMustBeMasterConnection(false); listener.foundActiveSecondary(protocol); } else { protocol.close(); protocol = getNewProtocol(listener.getProxy(), globalInfo, listener.getUrlParser()); } } catch (SQLException e) { listener.addToBlacklist(protocol.getHostAddress()); } }
[ "private", "static", "void", "searchProbableMaster", "(", "AuroraListener", "listener", ",", "final", "GlobalStateInfo", "globalInfo", ",", "HostAddress", "probableMaster", ")", "{", "AuroraProtocol", "protocol", "=", "getNewProtocol", "(", "listener", ".", "getProxy", ...
Connect aurora probable master. Aurora master change in time. The only way to check that a server is a master is to asked him. @param listener aurora failover to call back if master is found @param globalInfo server global variables information @param probableMaster probable master host
[ "Connect", "aurora", "probable", "master", ".", "Aurora", "master", "change", "in", "time", ".", "The", "only", "way", "to", "check", "that", "a", "server", "is", "a", "master", "is", "to", "asked", "him", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AuroraProtocol.java#L89-L115
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AuroraProtocol.java
AuroraProtocol.getNewProtocol
public static AuroraProtocol getNewProtocol(FailoverProxy proxy, final GlobalStateInfo globalInfo, UrlParser urlParser) { AuroraProtocol newProtocol = new AuroraProtocol(urlParser, globalInfo, proxy.lock); newProtocol.setProxy(proxy); return newProtocol; }
java
public static AuroraProtocol getNewProtocol(FailoverProxy proxy, final GlobalStateInfo globalInfo, UrlParser urlParser) { AuroraProtocol newProtocol = new AuroraProtocol(urlParser, globalInfo, proxy.lock); newProtocol.setProxy(proxy); return newProtocol; }
[ "public", "static", "AuroraProtocol", "getNewProtocol", "(", "FailoverProxy", "proxy", ",", "final", "GlobalStateInfo", "globalInfo", ",", "UrlParser", "urlParser", ")", "{", "AuroraProtocol", "newProtocol", "=", "new", "AuroraProtocol", "(", "urlParser", ",", "global...
Initialize new protocol instance. @param proxy proxy @param globalInfo server global variables information @param urlParser connection string data's @return new AuroraProtocol
[ "Initialize", "new", "protocol", "instance", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AuroraProtocol.java#L335-L340
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/dao/CmdInformationBatch.java
CmdInformationBatch.reset
@Override public void reset() { insertIds.clear(); updateCounts.clear(); insertIdNumber = 0; hasException = false; rewritten = false; }
java
@Override public void reset() { insertIds.clear(); updateCounts.clear(); insertIdNumber = 0; hasException = false; rewritten = false; }
[ "@", "Override", "public", "void", "reset", "(", ")", "{", "insertIds", ".", "clear", "(", ")", ";", "updateCounts", ".", "clear", "(", ")", ";", "insertIdNumber", "=", "0", ";", "hasException", "=", "false", ";", "rewritten", "=", "false", ";", "}" ]
Clear error state, used for clear exception after first batch query, when fall back to per-query execution.
[ "Clear", "error", "state", "used", "for", "clear", "exception", "after", "first", "batch", "query", "when", "fall", "back", "to", "per", "-", "query", "execution", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/dao/CmdInformationBatch.java#L98-L105
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java
SelectResultSet.readNextValue
private boolean readNextValue() throws IOException, SQLException { byte[] buf = reader.getPacketArray(false); //is error Packet if (buf[0] == ERROR) { protocol.removeActiveStreamingResult(); protocol.removeHasMoreResults(); protocol.setHasWarnings(false); ErrorPacket errorPacket = new ErrorPacket(new Buffer(buf)); resetVariables(); throw ExceptionMapper.get(errorPacket.getMessage(), errorPacket.getSqlState(), errorPacket.getErrorNumber(), null, false); } //is end of stream if (buf[0] == EOF && ((eofDeprecated && buf.length < 0xffffff) || (!eofDeprecated && buf.length < 8))) { int serverStatus; int warnings; if (!eofDeprecated) { //EOF_Packet warnings = (buf[1] & 0xff) + ((buf[2] & 0xff) << 8); serverStatus = ((buf[3] & 0xff) + ((buf[4] & 0xff) << 8)); //CallableResult has been read from intermediate EOF server_status //and is mandatory because : // // - Call query will have an callable resultSet for OUT parameters // this resultSet must be identified and not listed in JDBC statement.getResultSet() // // - after a callable resultSet, a OK packet is send, // but mysql before 5.7.4 doesn't send MORE_RESULTS_EXISTS flag if (callableResult) { serverStatus |= MORE_RESULTS_EXISTS; } } else { //OK_Packet with a 0xFE header int pos = skipLengthEncodedValue(buf, 1); //skip update count pos = skipLengthEncodedValue(buf, pos); //skip insert id serverStatus = ((buf[pos++] & 0xff) + ((buf[pos++] & 0xff) << 8)); warnings = (buf[pos++] & 0xff) + ((buf[pos] & 0xff) << 8); callableResult = (serverStatus & PS_OUT_PARAMETERS) != 0; } protocol.setServerStatus((short) serverStatus); protocol.setHasWarnings(warnings > 0); if ((serverStatus & MORE_RESULTS_EXISTS) == 0) { protocol.removeActiveStreamingResult(); } resetVariables(); return false; } //this is a result-set row, save it if (dataSize + 1 >= data.length) { growDataArray(); } data[dataSize++] = buf; return true; }
java
private boolean readNextValue() throws IOException, SQLException { byte[] buf = reader.getPacketArray(false); //is error Packet if (buf[0] == ERROR) { protocol.removeActiveStreamingResult(); protocol.removeHasMoreResults(); protocol.setHasWarnings(false); ErrorPacket errorPacket = new ErrorPacket(new Buffer(buf)); resetVariables(); throw ExceptionMapper.get(errorPacket.getMessage(), errorPacket.getSqlState(), errorPacket.getErrorNumber(), null, false); } //is end of stream if (buf[0] == EOF && ((eofDeprecated && buf.length < 0xffffff) || (!eofDeprecated && buf.length < 8))) { int serverStatus; int warnings; if (!eofDeprecated) { //EOF_Packet warnings = (buf[1] & 0xff) + ((buf[2] & 0xff) << 8); serverStatus = ((buf[3] & 0xff) + ((buf[4] & 0xff) << 8)); //CallableResult has been read from intermediate EOF server_status //and is mandatory because : // // - Call query will have an callable resultSet for OUT parameters // this resultSet must be identified and not listed in JDBC statement.getResultSet() // // - after a callable resultSet, a OK packet is send, // but mysql before 5.7.4 doesn't send MORE_RESULTS_EXISTS flag if (callableResult) { serverStatus |= MORE_RESULTS_EXISTS; } } else { //OK_Packet with a 0xFE header int pos = skipLengthEncodedValue(buf, 1); //skip update count pos = skipLengthEncodedValue(buf, pos); //skip insert id serverStatus = ((buf[pos++] & 0xff) + ((buf[pos++] & 0xff) << 8)); warnings = (buf[pos++] & 0xff) + ((buf[pos] & 0xff) << 8); callableResult = (serverStatus & PS_OUT_PARAMETERS) != 0; } protocol.setServerStatus((short) serverStatus); protocol.setHasWarnings(warnings > 0); if ((serverStatus & MORE_RESULTS_EXISTS) == 0) { protocol.removeActiveStreamingResult(); } resetVariables(); return false; } //this is a result-set row, save it if (dataSize + 1 >= data.length) { growDataArray(); } data[dataSize++] = buf; return true; }
[ "private", "boolean", "readNextValue", "(", ")", "throws", "IOException", ",", "SQLException", "{", "byte", "[", "]", "buf", "=", "reader", ".", "getPacketArray", "(", "false", ")", ";", "//is error Packet", "if", "(", "buf", "[", "0", "]", "==", "ERROR", ...
Read next value. @return true if have a new value @throws IOException exception @throws SQLException exception
[ "Read", "next", "value", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java#L430-L492
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java
SelectResultSet.deleteCurrentRowData
protected void deleteCurrentRowData() throws SQLException { //move data System.arraycopy(data, rowPointer + 1, data, rowPointer, dataSize - 1 - rowPointer); data[dataSize - 1] = null; dataSize--; lastRowPointer = -1; previous(); }
java
protected void deleteCurrentRowData() throws SQLException { //move data System.arraycopy(data, rowPointer + 1, data, rowPointer, dataSize - 1 - rowPointer); data[dataSize - 1] = null; dataSize--; lastRowPointer = -1; previous(); }
[ "protected", "void", "deleteCurrentRowData", "(", ")", "throws", "SQLException", "{", "//move data", "System", ".", "arraycopy", "(", "data", ",", "rowPointer", "+", "1", ",", "data", ",", "rowPointer", ",", "dataSize", "-", "1", "-", "rowPointer", ")", ";",...
Delete current data. Position cursor to the previous row. @throws SQLException if previous() fail.
[ "Delete", "current", "data", ".", "Position", "cursor", "to", "the", "previous", "row", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java#L519-L526
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java
SelectResultSet.close
public void close() throws SQLException { isClosed = true; if (!isEof) { lock.lock(); try { while (!isEof) { dataSize = 0; //to avoid storing data readNextValue(); } } catch (SQLException queryException) { throw ExceptionMapper.getException(queryException, null, this.statement, false); } catch (IOException ioe) { throw handleIoException(ioe); } finally { resetVariables(); lock.unlock(); } } resetVariables(); //keep garbage easy for (int i = 0; i < data.length; i++) { data[i] = null; } if (statement != null) { statement.checkCloseOnCompletion(this); statement = null; } }
java
public void close() throws SQLException { isClosed = true; if (!isEof) { lock.lock(); try { while (!isEof) { dataSize = 0; //to avoid storing data readNextValue(); } } catch (SQLException queryException) { throw ExceptionMapper.getException(queryException, null, this.statement, false); } catch (IOException ioe) { throw handleIoException(ioe); } finally { resetVariables(); lock.unlock(); } } resetVariables(); //keep garbage easy for (int i = 0; i < data.length; i++) { data[i] = null; } if (statement != null) { statement.checkCloseOnCompletion(this); statement = null; } }
[ "public", "void", "close", "(", ")", "throws", "SQLException", "{", "isClosed", "=", "true", ";", "if", "(", "!", "isEof", ")", "{", "lock", ".", "lock", "(", ")", ";", "try", "{", "while", "(", "!", "isEof", ")", "{", "dataSize", "=", "0", ";", ...
Close resultSet.
[ "Close", "resultSet", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java#L596-L626
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/CallableProcedureStatement.java
CallableProcedureStatement.nameToIndex
private int nameToIndex(String parameterName) throws SQLException { parameterMetadata.readMetadataFromDbIfRequired(); for (int i = 1; i <= parameterMetadata.getParameterCount(); i++) { String name = parameterMetadata.getName(i); if (name != null && name.equalsIgnoreCase(parameterName)) { return i; } } throw new SQLException("there is no parameter with the name " + parameterName); }
java
private int nameToIndex(String parameterName) throws SQLException { parameterMetadata.readMetadataFromDbIfRequired(); for (int i = 1; i <= parameterMetadata.getParameterCount(); i++) { String name = parameterMetadata.getName(i); if (name != null && name.equalsIgnoreCase(parameterName)) { return i; } } throw new SQLException("there is no parameter with the name " + parameterName); }
[ "private", "int", "nameToIndex", "(", "String", "parameterName", ")", "throws", "SQLException", "{", "parameterMetadata", ".", "readMetadataFromDbIfRequired", "(", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "parameterMetadata", ".", "getParamete...
Convert parameter name to parameter index in the query. @param parameterName name @return index @throws SQLException exception
[ "Convert", "parameter", "name", "to", "parameter", "index", "in", "the", "query", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/CallableProcedureStatement.java#L158-L167
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/CallableProcedureStatement.java
CallableProcedureStatement.nameToOutputIndex
private int nameToOutputIndex(String parameterName) throws SQLException { parameterMetadata.readMetadataFromDbIfRequired(); for (int i = 0; i < parameterMetadata.getParameterCount(); i++) { String name = parameterMetadata.getName(i + 1); if (name != null && name.equalsIgnoreCase(parameterName)) { if (outputParameterMapper[i] == -1) { //this is not an outputParameter throw new SQLException("Parameter '" + parameterName + "' is not declared as output parameter with method registerOutParameter"); } return outputParameterMapper[i]; } } throw new SQLException("there is no parameter with the name " + parameterName); }
java
private int nameToOutputIndex(String parameterName) throws SQLException { parameterMetadata.readMetadataFromDbIfRequired(); for (int i = 0; i < parameterMetadata.getParameterCount(); i++) { String name = parameterMetadata.getName(i + 1); if (name != null && name.equalsIgnoreCase(parameterName)) { if (outputParameterMapper[i] == -1) { //this is not an outputParameter throw new SQLException("Parameter '" + parameterName + "' is not declared as output parameter with method registerOutParameter"); } return outputParameterMapper[i]; } } throw new SQLException("there is no parameter with the name " + parameterName); }
[ "private", "int", "nameToOutputIndex", "(", "String", "parameterName", ")", "throws", "SQLException", "{", "parameterMetadata", ".", "readMetadataFromDbIfRequired", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parameterMetadata", ".", "getPar...
Convert parameter name to output parameter index in the query. @param parameterName name @return index @throws SQLException exception
[ "Convert", "parameter", "name", "to", "output", "parameter", "index", "in", "the", "query", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/CallableProcedureStatement.java#L177-L191
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/CallableProcedureStatement.java
CallableProcedureStatement.indexToOutputIndex
private int indexToOutputIndex(int parameterIndex) throws SQLException { try { if (outputParameterMapper[parameterIndex - 1] == -1) { //this is not an outputParameter throw new SQLException("Parameter in index '" + parameterIndex + "' is not declared as output parameter with method registerOutParameter"); } return outputParameterMapper[parameterIndex - 1]; } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) { if (parameterIndex < 1) { throw new SQLException("Index " + parameterIndex + " must at minimum be 1"); } throw new SQLException("Index value '" + parameterIndex + "' is incorrect. Maximum value is " + params.size()); } }
java
private int indexToOutputIndex(int parameterIndex) throws SQLException { try { if (outputParameterMapper[parameterIndex - 1] == -1) { //this is not an outputParameter throw new SQLException("Parameter in index '" + parameterIndex + "' is not declared as output parameter with method registerOutParameter"); } return outputParameterMapper[parameterIndex - 1]; } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) { if (parameterIndex < 1) { throw new SQLException("Index " + parameterIndex + " must at minimum be 1"); } throw new SQLException("Index value '" + parameterIndex + "' is incorrect. Maximum value is " + params.size()); } }
[ "private", "int", "indexToOutputIndex", "(", "int", "parameterIndex", ")", "throws", "SQLException", "{", "try", "{", "if", "(", "outputParameterMapper", "[", "parameterIndex", "-", "1", "]", "==", "-", "1", ")", "{", "//this is not an outputParameter", "throw", ...
Convert parameter index to corresponding outputIndex. @param parameterIndex index @return index @throws SQLException exception
[ "Convert", "parameter", "index", "to", "corresponding", "outputIndex", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/CallableProcedureStatement.java#L200-L215
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ReaderParameter.java
ReaderParameter.writeTo
public void writeTo(PacketOutputStream pos) throws IOException { pos.write(QUOTE); if (length == Long.MAX_VALUE) { pos.write(reader, true, noBackslashEscapes); } else { pos.write(reader, length, true, noBackslashEscapes); } pos.write(QUOTE); }
java
public void writeTo(PacketOutputStream pos) throws IOException { pos.write(QUOTE); if (length == Long.MAX_VALUE) { pos.write(reader, true, noBackslashEscapes); } else { pos.write(reader, length, true, noBackslashEscapes); } pos.write(QUOTE); }
[ "public", "void", "writeTo", "(", "PacketOutputStream", "pos", ")", "throws", "IOException", "{", "pos", ".", "write", "(", "QUOTE", ")", ";", "if", "(", "length", "==", "Long", ".", "MAX_VALUE", ")", "{", "pos", ".", "write", "(", "reader", ",", "true...
Write reader to database in text format. @param pos database outputStream @throws IOException if any error occur when reading reader
[ "Write", "reader", "to", "database", "in", "text", "format", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/ReaderParameter.java#L89-L97
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.reset
@Override public void reset() throws SQLException { cmdPrologue(); try { writer.startPacket(0); writer.write(COM_RESET_CONNECTION); writer.flush(); getResult(new Results()); //clear prepare statement cache if (options.cachePrepStmts && options.useServerPrepStmts) { serverPrepareStatementCache.clear(); } } catch (SQLException sqlException) { throw logQuery .exceptionWithQuery("COM_RESET_CONNECTION failed.", sqlException, explicitClosed); } catch (IOException e) { throw handleIoException(e); } }
java
@Override public void reset() throws SQLException { cmdPrologue(); try { writer.startPacket(0); writer.write(COM_RESET_CONNECTION); writer.flush(); getResult(new Results()); //clear prepare statement cache if (options.cachePrepStmts && options.useServerPrepStmts) { serverPrepareStatementCache.clear(); } } catch (SQLException sqlException) { throw logQuery .exceptionWithQuery("COM_RESET_CONNECTION failed.", sqlException, explicitClosed); } catch (IOException e) { throw handleIoException(e); } }
[ "@", "Override", "public", "void", "reset", "(", ")", "throws", "SQLException", "{", "cmdPrologue", "(", ")", ";", "try", "{", "writer", ".", "startPacket", "(", "0", ")", ";", "writer", ".", "write", "(", "COM_RESET_CONNECTION", ")", ";", "writer", ".",...
Reset connection state. <ol> <li>Transaction will be rollback</li> <li>transaction isolation will be reset</li> <li>user variables will be removed</li> <li>sessions variables will be reset to global values</li> </ol> @throws SQLException if command failed
[ "Reset", "connection", "state", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L172-L194
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.executeQuery
@Override public void executeQuery(boolean mustExecuteOnMaster, Results results, final String sql) throws SQLException { cmdPrologue(); try { writer.startPacket(0); writer.write(COM_QUERY); writer.write(sql); writer.flush(); getResult(results); } catch (SQLException sqlException) { if ("70100".equals(sqlException.getSQLState()) && 1927 == sqlException.getErrorCode()) { throw handleIoException(sqlException); } throw logQuery.exceptionWithQuery(sql, sqlException, explicitClosed); } catch (IOException e) { throw handleIoException(e); } }
java
@Override public void executeQuery(boolean mustExecuteOnMaster, Results results, final String sql) throws SQLException { cmdPrologue(); try { writer.startPacket(0); writer.write(COM_QUERY); writer.write(sql); writer.flush(); getResult(results); } catch (SQLException sqlException) { if ("70100".equals(sqlException.getSQLState()) && 1927 == sqlException.getErrorCode()) { throw handleIoException(sqlException); } throw logQuery.exceptionWithQuery(sql, sqlException, explicitClosed); } catch (IOException e) { throw handleIoException(e); } }
[ "@", "Override", "public", "void", "executeQuery", "(", "boolean", "mustExecuteOnMaster", ",", "Results", "results", ",", "final", "String", "sql", ")", "throws", "SQLException", "{", "cmdPrologue", "(", ")", ";", "try", "{", "writer", ".", "startPacket", "(",...
Execute query directly to outputStream. @param mustExecuteOnMaster was intended to be launched on master connection @param results result @param sql the query to executeInternal @throws SQLException exception
[ "Execute", "query", "directly", "to", "outputStream", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L216-L238
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.executeQuery
public void executeQuery(boolean mustExecuteOnMaster, Results results, final ClientPrepareResult clientPrepareResult, ParameterHolder[] parameters) throws SQLException { cmdPrologue(); try { if (clientPrepareResult.getParamCount() == 0 && !clientPrepareResult .isQueryMultiValuesRewritable()) { if (clientPrepareResult.getQueryParts().size() == 1) { ComQuery.sendDirect(writer, clientPrepareResult.getQueryParts().get(0)); } else { ComQuery.sendMultiDirect(writer, clientPrepareResult.getQueryParts()); } } else { writer.startPacket(0); ComQuery.sendSubCmd(writer, clientPrepareResult, parameters, -1); writer.flush(); } getResult(results); } catch (SQLException queryException) { throw logQuery.exceptionWithQuery(parameters, queryException, clientPrepareResult); } catch (IOException e) { throw handleIoException(e); } }
java
public void executeQuery(boolean mustExecuteOnMaster, Results results, final ClientPrepareResult clientPrepareResult, ParameterHolder[] parameters) throws SQLException { cmdPrologue(); try { if (clientPrepareResult.getParamCount() == 0 && !clientPrepareResult .isQueryMultiValuesRewritable()) { if (clientPrepareResult.getQueryParts().size() == 1) { ComQuery.sendDirect(writer, clientPrepareResult.getQueryParts().get(0)); } else { ComQuery.sendMultiDirect(writer, clientPrepareResult.getQueryParts()); } } else { writer.startPacket(0); ComQuery.sendSubCmd(writer, clientPrepareResult, parameters, -1); writer.flush(); } getResult(results); } catch (SQLException queryException) { throw logQuery.exceptionWithQuery(parameters, queryException, clientPrepareResult); } catch (IOException e) { throw handleIoException(e); } }
[ "public", "void", "executeQuery", "(", "boolean", "mustExecuteOnMaster", ",", "Results", "results", ",", "final", "ClientPrepareResult", "clientPrepareResult", ",", "ParameterHolder", "[", "]", "parameters", ")", "throws", "SQLException", "{", "cmdPrologue", "(", ")",...
Execute a unique clientPrepareQuery. @param mustExecuteOnMaster was intended to be launched on master connection @param results results @param clientPrepareResult clientPrepareResult @param parameters parameters @throws SQLException exception
[ "Execute", "a", "unique", "clientPrepareQuery", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L270-L295
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.executeBatch
private void executeBatch(Results results, final List<String> queries) throws SQLException { if (!options.useBatchMultiSend) { String sql = null; SQLException exception = null; for (int i = 0; i < queries.size() && !isInterrupted(); i++) { try { sql = queries.get(i); writer.startPacket(0); writer.write(COM_QUERY); writer.write(sql); writer.flush(); getResult(results); } catch (SQLException sqlException) { if (exception == null) { exception = logQuery.exceptionWithQuery(sql, sqlException, explicitClosed); if (!options.continueBatchOnError) { throw exception; } } } catch (IOException e) { if (exception == null) { exception = handleIoException(e); if (!options.continueBatchOnError) { throw exception; } } } } stopIfInterrupted(); if (exception != null) { throw exception; } return; } initializeBatchReader(); new AbstractMultiSend(this, writer, results, queries) { @Override public void sendCmd(PacketOutputStream pos, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int paramCount, BulkStatus status, PrepareResult prepareResult) throws IOException { String sql = queries.get(status.sendCmdCounter); pos.startPacket(0); pos.write(COM_QUERY); pos.write(sql); pos.flush(); } @Override public SQLException handleResultException(SQLException qex, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int currentCounter, int sendCmdCounter, int paramCount, PrepareResult prepareResult) { String sql = queries.get(currentCounter + sendCmdCounter); return logQuery.exceptionWithQuery(sql, qex, explicitClosed); } @Override public int getParamCount() { return -1; } @Override public int getTotalExecutionNumber() { return queries.size(); } }.executeBatch(); }
java
private void executeBatch(Results results, final List<String> queries) throws SQLException { if (!options.useBatchMultiSend) { String sql = null; SQLException exception = null; for (int i = 0; i < queries.size() && !isInterrupted(); i++) { try { sql = queries.get(i); writer.startPacket(0); writer.write(COM_QUERY); writer.write(sql); writer.flush(); getResult(results); } catch (SQLException sqlException) { if (exception == null) { exception = logQuery.exceptionWithQuery(sql, sqlException, explicitClosed); if (!options.continueBatchOnError) { throw exception; } } } catch (IOException e) { if (exception == null) { exception = handleIoException(e); if (!options.continueBatchOnError) { throw exception; } } } } stopIfInterrupted(); if (exception != null) { throw exception; } return; } initializeBatchReader(); new AbstractMultiSend(this, writer, results, queries) { @Override public void sendCmd(PacketOutputStream pos, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int paramCount, BulkStatus status, PrepareResult prepareResult) throws IOException { String sql = queries.get(status.sendCmdCounter); pos.startPacket(0); pos.write(COM_QUERY); pos.write(sql); pos.flush(); } @Override public SQLException handleResultException(SQLException qex, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int currentCounter, int sendCmdCounter, int paramCount, PrepareResult prepareResult) { String sql = queries.get(currentCounter + sendCmdCounter); return logQuery.exceptionWithQuery(sql, qex, explicitClosed); } @Override public int getParamCount() { return -1; } @Override public int getTotalExecutionNumber() { return queries.size(); } }.executeBatch(); }
[ "private", "void", "executeBatch", "(", "Results", "results", ",", "final", "List", "<", "String", ">", "queries", ")", "throws", "SQLException", "{", "if", "(", "!", "options", ".", "useBatchMultiSend", ")", "{", "String", "sql", "=", "null", ";", "SQLExc...
Execute list of queries not rewritable. @param results result object @param queries list of queries @throws SQLException exception
[ "Execute", "list", "of", "queries", "not", "rewritable", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L702-L783
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.prepare
@Override public ServerPrepareResult prepare(String sql, boolean executeOnMaster) throws SQLException { cmdPrologue(); lock.lock(); try { if (options.cachePrepStmts && options.useServerPrepStmts) { ServerPrepareResult pr = serverPrepareStatementCache.get(database + "-" + sql); if (pr != null && pr.incrementShareCounter()) { return pr; } } writer.startPacket(0); writer.write(COM_STMT_PREPARE); writer.write(sql); writer.flush(); ComStmtPrepare comStmtPrepare = new ComStmtPrepare(this, sql); return comStmtPrepare.read(reader, eofDeprecated); } catch (IOException e) { throw handleIoException(e); } finally { lock.unlock(); } }
java
@Override public ServerPrepareResult prepare(String sql, boolean executeOnMaster) throws SQLException { cmdPrologue(); lock.lock(); try { if (options.cachePrepStmts && options.useServerPrepStmts) { ServerPrepareResult pr = serverPrepareStatementCache.get(database + "-" + sql); if (pr != null && pr.incrementShareCounter()) { return pr; } } writer.startPacket(0); writer.write(COM_STMT_PREPARE); writer.write(sql); writer.flush(); ComStmtPrepare comStmtPrepare = new ComStmtPrepare(this, sql); return comStmtPrepare.read(reader, eofDeprecated); } catch (IOException e) { throw handleIoException(e); } finally { lock.unlock(); } }
[ "@", "Override", "public", "ServerPrepareResult", "prepare", "(", "String", "sql", ",", "boolean", "executeOnMaster", ")", "throws", "SQLException", "{", "cmdPrologue", "(", ")", ";", "lock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "options", "....
Prepare query on server side. Will permit to know the parameter number of the query, and permit to send only the data on next results. <p>For failover, two additional information are in the result-set object : - current connection : Since server maintain a state of this prepare statement, all query will be executed on this particular connection. - executeOnMaster : state of current connection when creating this prepareStatement (if was on master, will only be executed on master. If was on a slave, can be execute temporary on master, but we keep this flag, so when a slave is connected back to relaunch this query on slave)</p> @param sql the query @param executeOnMaster state of current connection when creating this prepareStatement @return a ServerPrepareResult object that contain prepare result information. @throws SQLException if any error occur on connection.
[ "Prepare", "query", "on", "server", "side", ".", "Will", "permit", "to", "know", "the", "parameter", "number", "of", "the", "query", "and", "permit", "to", "send", "only", "the", "data", "on", "next", "results", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L801-L828
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.executeBatchRewrite
private void executeBatchRewrite(Results results, final ClientPrepareResult prepareResult, List<ParameterHolder[]> parameterList, boolean rewriteValues) throws SQLException { cmdPrologue(); ParameterHolder[] parameters; int currentIndex = 0; int totalParameterList = parameterList.size(); try { do { currentIndex = ComQuery.sendRewriteCmd(writer, prepareResult.getQueryParts(), currentIndex, prepareResult.getParamCount(), parameterList, rewriteValues); getResult(results); if (Thread.currentThread().isInterrupted()) { throw new SQLException("Interrupted during batch", INTERRUPTED_EXCEPTION.getSqlState(), -1); } } while (currentIndex < totalParameterList); } catch (SQLException sqlEx) { throw logQuery.exceptionWithQuery(sqlEx, prepareResult); } catch (IOException e) { throw handleIoException(e); } finally { results.setRewritten(rewriteValues); } }
java
private void executeBatchRewrite(Results results, final ClientPrepareResult prepareResult, List<ParameterHolder[]> parameterList, boolean rewriteValues) throws SQLException { cmdPrologue(); ParameterHolder[] parameters; int currentIndex = 0; int totalParameterList = parameterList.size(); try { do { currentIndex = ComQuery.sendRewriteCmd(writer, prepareResult.getQueryParts(), currentIndex, prepareResult.getParamCount(), parameterList, rewriteValues); getResult(results); if (Thread.currentThread().isInterrupted()) { throw new SQLException("Interrupted during batch", INTERRUPTED_EXCEPTION.getSqlState(), -1); } } while (currentIndex < totalParameterList); } catch (SQLException sqlEx) { throw logQuery.exceptionWithQuery(sqlEx, prepareResult); } catch (IOException e) { throw handleIoException(e); } finally { results.setRewritten(rewriteValues); } }
[ "private", "void", "executeBatchRewrite", "(", "Results", "results", ",", "final", "ClientPrepareResult", "prepareResult", ",", "List", "<", "ParameterHolder", "[", "]", ">", "parameterList", ",", "boolean", "rewriteValues", ")", "throws", "SQLException", "{", "cmdP...
Specific execution for batch rewrite that has specific query for memory. @param results result @param prepareResult prepareResult @param parameterList parameters @param rewriteValues is rewritable flag @throws SQLException exception
[ "Specific", "execution", "for", "batch", "rewrite", "that", "has", "specific", "query", "for", "memory", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L892-L924
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.executeBatchServer
public boolean executeBatchServer(boolean mustExecuteOnMaster, ServerPrepareResult serverPrepareResult, Results results, String sql, final List<ParameterHolder[]> parametersList, boolean hasLongData) throws SQLException { cmdPrologue(); if (options.useBulkStmts && !hasLongData && results.getAutoGeneratedKeys() == Statement.NO_GENERATED_KEYS && versionGreaterOrEqual(10, 2, 7) && executeBulkBatch(results, sql, serverPrepareResult, parametersList)) { return true; } if (!options.useBatchMultiSend) { return false; } initializeBatchReader(); new AbstractMultiSend(this, writer, results, serverPrepareResult, parametersList, true, sql) { @Override public void sendCmd(PacketOutputStream writer, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int paramCount, BulkStatus status, PrepareResult prepareResult) throws SQLException, IOException { ParameterHolder[] parameters = parametersList.get(status.sendCmdCounter); //validate parameter set if (parameters.length < paramCount) { throw new SQLException("Parameter at position " + (paramCount - 1) + " is not set", "07004"); } //send binary data in a separate stream for (int i = 0; i < paramCount; i++) { if (parameters[i].isLongData()) { writer.startPacket(0); writer.write(COM_STMT_SEND_LONG_DATA); writer.writeInt(statementId); writer.writeShort((short) i); parameters[i].writeBinary(writer); writer.flush(); } } writer.startPacket(0); ComStmtExecute.writeCmd(statementId, parameters, paramCount, parameterTypeHeader, writer, CURSOR_TYPE_NO_CURSOR); writer.flush(); } @Override public SQLException handleResultException(SQLException qex, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int currentCounter, int sendCmdCounter, int paramCount, PrepareResult prepareResult) { return logQuery.exceptionWithQuery(qex, prepareResult); } @Override public int getParamCount() { return getPrepareResult() == null ? parametersList.get(0).length : ((ServerPrepareResult) getPrepareResult()).getParameters().length; } @Override public int getTotalExecutionNumber() { return parametersList.size(); } }.executeBatch(); return true; }
java
public boolean executeBatchServer(boolean mustExecuteOnMaster, ServerPrepareResult serverPrepareResult, Results results, String sql, final List<ParameterHolder[]> parametersList, boolean hasLongData) throws SQLException { cmdPrologue(); if (options.useBulkStmts && !hasLongData && results.getAutoGeneratedKeys() == Statement.NO_GENERATED_KEYS && versionGreaterOrEqual(10, 2, 7) && executeBulkBatch(results, sql, serverPrepareResult, parametersList)) { return true; } if (!options.useBatchMultiSend) { return false; } initializeBatchReader(); new AbstractMultiSend(this, writer, results, serverPrepareResult, parametersList, true, sql) { @Override public void sendCmd(PacketOutputStream writer, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int paramCount, BulkStatus status, PrepareResult prepareResult) throws SQLException, IOException { ParameterHolder[] parameters = parametersList.get(status.sendCmdCounter); //validate parameter set if (parameters.length < paramCount) { throw new SQLException("Parameter at position " + (paramCount - 1) + " is not set", "07004"); } //send binary data in a separate stream for (int i = 0; i < paramCount; i++) { if (parameters[i].isLongData()) { writer.startPacket(0); writer.write(COM_STMT_SEND_LONG_DATA); writer.writeInt(statementId); writer.writeShort((short) i); parameters[i].writeBinary(writer); writer.flush(); } } writer.startPacket(0); ComStmtExecute.writeCmd(statementId, parameters, paramCount, parameterTypeHeader, writer, CURSOR_TYPE_NO_CURSOR); writer.flush(); } @Override public SQLException handleResultException(SQLException qex, Results results, List<ParameterHolder[]> parametersList, List<String> queries, int currentCounter, int sendCmdCounter, int paramCount, PrepareResult prepareResult) { return logQuery.exceptionWithQuery(qex, prepareResult); } @Override public int getParamCount() { return getPrepareResult() == null ? parametersList.get(0).length : ((ServerPrepareResult) getPrepareResult()).getParameters().length; } @Override public int getTotalExecutionNumber() { return parametersList.size(); } }.executeBatch(); return true; }
[ "public", "boolean", "executeBatchServer", "(", "boolean", "mustExecuteOnMaster", ",", "ServerPrepareResult", "serverPrepareResult", ",", "Results", "results", ",", "String", "sql", ",", "final", "List", "<", "ParameterHolder", "[", "]", ">", "parametersList", ",", ...
Execute Prepare if needed, and execute COM_STMT_EXECUTE queries in batch. @param mustExecuteOnMaster must normally be executed on master connection @param serverPrepareResult prepare result. can be null if not prepared. @param results execution results @param sql sql query if needed to be prepared @param parametersList parameter list @param hasLongData has long data (stream) @return executed @throws SQLException if parameter error or connection error occur.
[ "Execute", "Prepare", "if", "needed", "and", "execute", "COM_STMT_EXECUTE", "queries", "in", "batch", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L938-L1011
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.executePreparedQuery
@Override public void executePreparedQuery(boolean mustExecuteOnMaster, ServerPrepareResult serverPrepareResult, Results results, ParameterHolder[] parameters) throws SQLException { cmdPrologue(); try { int parameterCount = serverPrepareResult.getParameters().length; //send binary data in a separate stream for (int i = 0; i < parameterCount; i++) { if (parameters[i].isLongData()) { writer.startPacket(0); writer.write(COM_STMT_SEND_LONG_DATA); writer.writeInt(serverPrepareResult.getStatementId()); writer.writeShort((short) i); parameters[i].writeBinary(writer); writer.flush(); } } //send execute query ComStmtExecute.send(writer, serverPrepareResult.getStatementId(), parameters, parameterCount, serverPrepareResult.getParameterTypeHeader(), CURSOR_TYPE_NO_CURSOR); getResult(results); } catch (SQLException qex) { throw logQuery.exceptionWithQuery(parameters, qex, serverPrepareResult); } catch (IOException e) { throw handleIoException(e); } }
java
@Override public void executePreparedQuery(boolean mustExecuteOnMaster, ServerPrepareResult serverPrepareResult, Results results, ParameterHolder[] parameters) throws SQLException { cmdPrologue(); try { int parameterCount = serverPrepareResult.getParameters().length; //send binary data in a separate stream for (int i = 0; i < parameterCount; i++) { if (parameters[i].isLongData()) { writer.startPacket(0); writer.write(COM_STMT_SEND_LONG_DATA); writer.writeInt(serverPrepareResult.getStatementId()); writer.writeShort((short) i); parameters[i].writeBinary(writer); writer.flush(); } } //send execute query ComStmtExecute.send(writer, serverPrepareResult.getStatementId(), parameters, parameterCount, serverPrepareResult.getParameterTypeHeader(), CURSOR_TYPE_NO_CURSOR); getResult(results); } catch (SQLException qex) { throw logQuery.exceptionWithQuery(parameters, qex, serverPrepareResult); } catch (IOException e) { throw handleIoException(e); } }
[ "@", "Override", "public", "void", "executePreparedQuery", "(", "boolean", "mustExecuteOnMaster", ",", "ServerPrepareResult", "serverPrepareResult", ",", "Results", "results", ",", "ParameterHolder", "[", "]", "parameters", ")", "throws", "SQLException", "{", "cmdProlog...
Execute a query that is already prepared. @param mustExecuteOnMaster must execute on master @param serverPrepareResult prepare result @param results execution result @param parameters parameters @throws SQLException exception
[ "Execute", "a", "query", "that", "is", "already", "prepared", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1022-L1056
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.rollback
public void rollback() throws SQLException { cmdPrologue(); lock.lock(); try { if (inTransaction()) { executeQuery("ROLLBACK"); } } catch (Exception e) { /* eat exception */ } finally { lock.unlock(); } }
java
public void rollback() throws SQLException { cmdPrologue(); lock.lock(); try { if (inTransaction()) { executeQuery("ROLLBACK"); } } catch (Exception e) { /* eat exception */ } finally { lock.unlock(); } }
[ "public", "void", "rollback", "(", ")", "throws", "SQLException", "{", "cmdPrologue", "(", ")", ";", "lock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "inTransaction", "(", ")", ")", "{", "executeQuery", "(", "\"ROLLBACK\"", ")", ";", "}", "...
Rollback transaction.
[ "Rollback", "transaction", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1061-L1077
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.forceReleasePrepareStatement
public boolean forceReleasePrepareStatement(int statementId) throws SQLException { if (lock.tryLock()) { try { checkClose(); try { writer.startPacket(0); writer.write(COM_STMT_CLOSE); writer.writeInt(statementId); writer.flush(); return true; } catch (IOException e) { connected = false; throw new SQLException("Could not deallocate query: " + e.getMessage(), CONNECTION_EXCEPTION.getSqlState(), e); } } finally { lock.unlock(); } } else { //lock is used by another thread (bulk reading) statementIdToRelease = statementId; } return false; }
java
public boolean forceReleasePrepareStatement(int statementId) throws SQLException { if (lock.tryLock()) { try { checkClose(); try { writer.startPacket(0); writer.write(COM_STMT_CLOSE); writer.writeInt(statementId); writer.flush(); return true; } catch (IOException e) { connected = false; throw new SQLException("Could not deallocate query: " + e.getMessage(), CONNECTION_EXCEPTION.getSqlState(), e); } } finally { lock.unlock(); } } else { //lock is used by another thread (bulk reading) statementIdToRelease = statementId; } return false; }
[ "public", "boolean", "forceReleasePrepareStatement", "(", "int", "statementId", ")", "throws", "SQLException", "{", "if", "(", "lock", ".", "tryLock", "(", ")", ")", "{", "try", "{", "checkClose", "(", ")", ";", "try", "{", "writer", ".", "startPacket", "(...
Force release of prepare statement that are not used. This method will be call when adding a new prepare statement in cache, so the packet can be send to server without problem. @param statementId prepared statement Id to remove. @return true if successfully released @throws SQLException if connection exception.
[ "Force", "release", "of", "prepare", "statement", "that", "are", "not", "used", ".", "This", "method", "will", "be", "call", "when", "adding", "a", "new", "prepare", "statement", "in", "cache", "so", "the", "packet", "can", "be", "send", "to", "server", ...
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1087-L1117
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.cancelCurrentQuery
@Override public void cancelCurrentQuery() throws SQLException { try (MasterProtocol copiedProtocol = new MasterProtocol(urlParser, new GlobalStateInfo(), new ReentrantLock())) { copiedProtocol.setHostAddress(getHostAddress()); copiedProtocol.connect(); //no lock, because there is already a query running that possessed the lock. copiedProtocol.executeQuery("KILL QUERY " + serverThreadId); } interrupted = true; }
java
@Override public void cancelCurrentQuery() throws SQLException { try (MasterProtocol copiedProtocol = new MasterProtocol(urlParser, new GlobalStateInfo(), new ReentrantLock())) { copiedProtocol.setHostAddress(getHostAddress()); copiedProtocol.connect(); //no lock, because there is already a query running that possessed the lock. copiedProtocol.executeQuery("KILL QUERY " + serverThreadId); } interrupted = true; }
[ "@", "Override", "public", "void", "cancelCurrentQuery", "(", ")", "throws", "SQLException", "{", "try", "(", "MasterProtocol", "copiedProtocol", "=", "new", "MasterProtocol", "(", "urlParser", ",", "new", "GlobalStateInfo", "(", ")", ",", "new", "ReentrantLock", ...
Cancels the current query - clones the current protocol and executes a query using the new connection. @throws SQLException never thrown
[ "Cancels", "the", "current", "query", "-", "clones", "the", "current", "protocol", "and", "executes", "a", "query", "using", "the", "new", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1270-L1280
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.releasePrepareStatement
@Override public void releasePrepareStatement(ServerPrepareResult serverPrepareResult) throws SQLException { //If prepared cache is enable, the ServerPrepareResult can be shared in many PrepStatement, //so synchronised use count indicator will be decrement. serverPrepareResult.decrementShareCounter(); //deallocate from server if not cached if (serverPrepareResult.canBeDeallocate()) { forceReleasePrepareStatement(serverPrepareResult.getStatementId()); } }
java
@Override public void releasePrepareStatement(ServerPrepareResult serverPrepareResult) throws SQLException { //If prepared cache is enable, the ServerPrepareResult can be shared in many PrepStatement, //so synchronised use count indicator will be decrement. serverPrepareResult.decrementShareCounter(); //deallocate from server if not cached if (serverPrepareResult.canBeDeallocate()) { forceReleasePrepareStatement(serverPrepareResult.getStatementId()); } }
[ "@", "Override", "public", "void", "releasePrepareStatement", "(", "ServerPrepareResult", "serverPrepareResult", ")", "throws", "SQLException", "{", "//If prepared cache is enable, the ServerPrepareResult can be shared in many PrepStatement,", "//so synchronised use count indicator will be...
Deallocate prepare statement if not used anymore. @param serverPrepareResult allocation result @throws SQLException if de-allocation failed.
[ "Deallocate", "prepare", "statement", "if", "not", "used", "anymore", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1308-L1318
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.setTimeout
@Override public void setTimeout(int timeout) throws SocketException { lock.lock(); try { this.socket.setSoTimeout(timeout); } finally { lock.unlock(); } }
java
@Override public void setTimeout(int timeout) throws SocketException { lock.lock(); try { this.socket.setSoTimeout(timeout); } finally { lock.unlock(); } }
[ "@", "Override", "public", "void", "setTimeout", "(", "int", "timeout", ")", "throws", "SocketException", "{", "lock", ".", "lock", "(", ")", ";", "try", "{", "this", ".", "socket", ".", "setSoTimeout", "(", "timeout", ")", ";", "}", "finally", "{", "l...
Sets the connection timeout. @param timeout the timeout, in milliseconds @throws SocketException if there is an error in the underlying protocol, such as a TCP error.
[ "Sets", "the", "connection", "timeout", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1358-L1366
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.setTransactionIsolation
public void setTransactionIsolation(final int level) throws SQLException { cmdPrologue(); lock.lock(); try { String query = "SET SESSION TRANSACTION ISOLATION LEVEL"; switch (level) { case Connection.TRANSACTION_READ_UNCOMMITTED: query += " READ UNCOMMITTED"; break; case Connection.TRANSACTION_READ_COMMITTED: query += " READ COMMITTED"; break; case Connection.TRANSACTION_REPEATABLE_READ: query += " REPEATABLE READ"; break; case Connection.TRANSACTION_SERIALIZABLE: query += " SERIALIZABLE"; break; default: throw new SQLException("Unsupported transaction isolation level"); } executeQuery(query); transactionIsolationLevel = level; } finally { lock.unlock(); } }
java
public void setTransactionIsolation(final int level) throws SQLException { cmdPrologue(); lock.lock(); try { String query = "SET SESSION TRANSACTION ISOLATION LEVEL"; switch (level) { case Connection.TRANSACTION_READ_UNCOMMITTED: query += " READ UNCOMMITTED"; break; case Connection.TRANSACTION_READ_COMMITTED: query += " READ COMMITTED"; break; case Connection.TRANSACTION_REPEATABLE_READ: query += " REPEATABLE READ"; break; case Connection.TRANSACTION_SERIALIZABLE: query += " SERIALIZABLE"; break; default: throw new SQLException("Unsupported transaction isolation level"); } executeQuery(query); transactionIsolationLevel = level; } finally { lock.unlock(); } }
[ "public", "void", "setTransactionIsolation", "(", "final", "int", "level", ")", "throws", "SQLException", "{", "cmdPrologue", "(", ")", ";", "lock", ".", "lock", "(", ")", ";", "try", "{", "String", "query", "=", "\"SET SESSION TRANSACTION ISOLATION LEVEL\"", ";...
Set transaction isolation. @param level transaction level. @throws SQLException if transaction level is unknown
[ "Set", "transaction", "isolation", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1374-L1400
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.readPacket
private void readPacket(Results results) throws SQLException { Buffer buffer; try { buffer = reader.getPacket(true); } catch (IOException e) { throw handleIoException(e); } switch (buffer.getByteAt(0)) { //********************************************************************************************************* //* OK response //********************************************************************************************************* case OK: readOkPacket(buffer, results); break; //********************************************************************************************************* //* ERROR response //********************************************************************************************************* case ERROR: throw readErrorPacket(buffer, results); //********************************************************************************************************* //* LOCAL INFILE response //********************************************************************************************************* case LOCAL_INFILE: readLocalInfilePacket(buffer, results); break; //********************************************************************************************************* //* ResultSet //********************************************************************************************************* default: readResultSet(buffer, results); break; } }
java
private void readPacket(Results results) throws SQLException { Buffer buffer; try { buffer = reader.getPacket(true); } catch (IOException e) { throw handleIoException(e); } switch (buffer.getByteAt(0)) { //********************************************************************************************************* //* OK response //********************************************************************************************************* case OK: readOkPacket(buffer, results); break; //********************************************************************************************************* //* ERROR response //********************************************************************************************************* case ERROR: throw readErrorPacket(buffer, results); //********************************************************************************************************* //* LOCAL INFILE response //********************************************************************************************************* case LOCAL_INFILE: readLocalInfilePacket(buffer, results); break; //********************************************************************************************************* //* ResultSet //********************************************************************************************************* default: readResultSet(buffer, results); break; } }
[ "private", "void", "readPacket", "(", "Results", "results", ")", "throws", "SQLException", "{", "Buffer", "buffer", ";", "try", "{", "buffer", "=", "reader", ".", "getPacket", "(", "true", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw...
Read server response packet. @param results result object @throws SQLException if sub-result connection fail @see <a href="https://mariadb.com/kb/en/mariadb/4-server-response-packets/">server response packets</a>
[ "Read", "server", "response", "packet", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1432-L1471
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.readOkPacket
private void readOkPacket(Buffer buffer, Results results) { buffer.skipByte(); //fieldCount final long updateCount = buffer.getLengthEncodedNumeric(); final long insertId = buffer.getLengthEncodedNumeric(); serverStatus = buffer.readShort(); hasWarnings = (buffer.readShort() > 0); if ((serverStatus & ServerStatus.SERVER_SESSION_STATE_CHANGED) != 0) { handleStateChange(buffer, results); } results.addStats(updateCount, insertId, hasMoreResults()); }
java
private void readOkPacket(Buffer buffer, Results results) { buffer.skipByte(); //fieldCount final long updateCount = buffer.getLengthEncodedNumeric(); final long insertId = buffer.getLengthEncodedNumeric(); serverStatus = buffer.readShort(); hasWarnings = (buffer.readShort() > 0); if ((serverStatus & ServerStatus.SERVER_SESSION_STATE_CHANGED) != 0) { handleStateChange(buffer, results); } results.addStats(updateCount, insertId, hasMoreResults()); }
[ "private", "void", "readOkPacket", "(", "Buffer", "buffer", ",", "Results", "results", ")", "{", "buffer", ".", "skipByte", "(", ")", ";", "//fieldCount", "final", "long", "updateCount", "=", "buffer", ".", "getLengthEncodedNumeric", "(", ")", ";", "final", ...
Read OK_Packet. @param buffer current buffer @param results result object @see <a href="https://mariadb.com/kb/en/mariadb/ok_packet/">OK_Packet</a>
[ "Read", "OK_Packet", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1480-L1493
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.readErrorPacket
private SQLException readErrorPacket(Buffer buffer, Results results) { removeHasMoreResults(); this.hasWarnings = false; buffer.skipByte(); final int errorNumber = buffer.readShort(); String message; String sqlState; if (buffer.readByte() == '#') { sqlState = new String(buffer.readRawBytes(5)); message = buffer.readStringNullEnd(StandardCharsets.UTF_8); } else { // Pre-4.1 message, still can be output in newer versions (e.g with 'Too many connections') buffer.position -= 1; message = new String(buffer.buf, buffer.position, buffer.limit - buffer.position, StandardCharsets.UTF_8); sqlState = "HY000"; } results.addStatsError(false); //force current status to in transaction to ensure rollback/commit, since command may have issue a transaction serverStatus |= ServerStatus.IN_TRANSACTION; removeActiveStreamingResult(); return new SQLException(message, sqlState, errorNumber); }
java
private SQLException readErrorPacket(Buffer buffer, Results results) { removeHasMoreResults(); this.hasWarnings = false; buffer.skipByte(); final int errorNumber = buffer.readShort(); String message; String sqlState; if (buffer.readByte() == '#') { sqlState = new String(buffer.readRawBytes(5)); message = buffer.readStringNullEnd(StandardCharsets.UTF_8); } else { // Pre-4.1 message, still can be output in newer versions (e.g with 'Too many connections') buffer.position -= 1; message = new String(buffer.buf, buffer.position, buffer.limit - buffer.position, StandardCharsets.UTF_8); sqlState = "HY000"; } results.addStatsError(false); //force current status to in transaction to ensure rollback/commit, since command may have issue a transaction serverStatus |= ServerStatus.IN_TRANSACTION; removeActiveStreamingResult(); return new SQLException(message, sqlState, errorNumber); }
[ "private", "SQLException", "readErrorPacket", "(", "Buffer", "buffer", ",", "Results", "results", ")", "{", "removeHasMoreResults", "(", ")", ";", "this", ".", "hasWarnings", "=", "false", ";", "buffer", ".", "skipByte", "(", ")", ";", "final", "int", "error...
Read ERR_Packet. @param buffer current buffer @param results result object @return SQLException if sub-result connection fail @see <a href="https://mariadb.com/kb/en/mariadb/err_packet/">ERR_Packet</a>
[ "Read", "ERR_Packet", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1571-L1595
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.readLocalInfilePacket
private void readLocalInfilePacket(Buffer buffer, Results results) throws SQLException { int seq = 2; buffer.getLengthEncodedNumeric(); //field pos String fileName = buffer.readStringNullEnd(StandardCharsets.UTF_8); try { // Server request the local file (LOCAL DATA LOCAL INFILE) // We do accept general URLs, too. If the localInfileStream is // set, use that. InputStream is; writer.startPacket(seq); if (localInfileInputStream == null) { if (!getUrlParser().getOptions().allowLocalInfile) { writer.writeEmptyPacket(); reader.getPacket(true); throw new SQLException( "Usage of LOCAL INFILE is disabled. To use it enable it via the connection property allowLocalInfile=true", FEATURE_NOT_SUPPORTED.getSqlState(), -1); } //validate all defined interceptors ServiceLoader<LocalInfileInterceptor> loader = ServiceLoader .load(LocalInfileInterceptor.class); for (LocalInfileInterceptor interceptor : loader) { if (!interceptor.validate(fileName)) { writer.writeEmptyPacket(); reader.getPacket(true); throw new SQLException("LOCAL DATA LOCAL INFILE request to send local file named \"" + fileName + "\" not validated by interceptor \"" + interceptor.getClass().getName() + "\""); } } try { URL url = new URL(fileName); is = url.openStream(); } catch (IOException ioe) { try { is = new FileInputStream(fileName); } catch (FileNotFoundException f) { writer.writeEmptyPacket(); reader.getPacket(true); throw new SQLException("Could not send file : " + f.getMessage(), "22000", -1, f); } } } else { is = localInfileInputStream; localInfileInputStream = null; } try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) { writer.startPacket(seq++); writer.write(buf, 0, len); writer.flush(); } writer.writeEmptyPacket(); } catch (IOException ioe) { throw handleIoException(ioe); } finally { is.close(); } getResult(results); } catch (IOException e) { throw handleIoException(e); } }
java
private void readLocalInfilePacket(Buffer buffer, Results results) throws SQLException { int seq = 2; buffer.getLengthEncodedNumeric(); //field pos String fileName = buffer.readStringNullEnd(StandardCharsets.UTF_8); try { // Server request the local file (LOCAL DATA LOCAL INFILE) // We do accept general URLs, too. If the localInfileStream is // set, use that. InputStream is; writer.startPacket(seq); if (localInfileInputStream == null) { if (!getUrlParser().getOptions().allowLocalInfile) { writer.writeEmptyPacket(); reader.getPacket(true); throw new SQLException( "Usage of LOCAL INFILE is disabled. To use it enable it via the connection property allowLocalInfile=true", FEATURE_NOT_SUPPORTED.getSqlState(), -1); } //validate all defined interceptors ServiceLoader<LocalInfileInterceptor> loader = ServiceLoader .load(LocalInfileInterceptor.class); for (LocalInfileInterceptor interceptor : loader) { if (!interceptor.validate(fileName)) { writer.writeEmptyPacket(); reader.getPacket(true); throw new SQLException("LOCAL DATA LOCAL INFILE request to send local file named \"" + fileName + "\" not validated by interceptor \"" + interceptor.getClass().getName() + "\""); } } try { URL url = new URL(fileName); is = url.openStream(); } catch (IOException ioe) { try { is = new FileInputStream(fileName); } catch (FileNotFoundException f) { writer.writeEmptyPacket(); reader.getPacket(true); throw new SQLException("Could not send file : " + f.getMessage(), "22000", -1, f); } } } else { is = localInfileInputStream; localInfileInputStream = null; } try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) { writer.startPacket(seq++); writer.write(buf, 0, len); writer.flush(); } writer.writeEmptyPacket(); } catch (IOException ioe) { throw handleIoException(ioe); } finally { is.close(); } getResult(results); } catch (IOException e) { throw handleIoException(e); } }
[ "private", "void", "readLocalInfilePacket", "(", "Buffer", "buffer", ",", "Results", "results", ")", "throws", "SQLException", "{", "int", "seq", "=", "2", ";", "buffer", ".", "getLengthEncodedNumeric", "(", ")", ";", "//field pos", "String", "fileName", "=", ...
Read Local_infile Packet. @param buffer current buffer @param results result object @throws SQLException if sub-result connection fail @see <a href="https://mariadb.com/kb/en/mariadb/local_infile-packet/">local_infile packet</a>
[ "Read", "Local_infile", "Packet", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1605-L1678
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.readResultSet
private void readResultSet(Buffer buffer, Results results) throws SQLException { long fieldCount = buffer.getLengthEncodedNumeric(); try { //read columns information's ColumnInformation[] ci = new ColumnInformation[(int) fieldCount]; for (int i = 0; i < fieldCount; i++) { ci[i] = new ColumnInformation(reader.getPacket(false)); } boolean callableResult = false; if (!eofDeprecated) { //read EOF packet //EOF status is mandatory because : // - Call query will have an callable resultSet for OUT parameters // -> this resultSet must be identified and not listed in JDBC statement.getResultSet() // - after a callable resultSet, a OK packet is send, but mysql does send the a bad "more result flag" Buffer bufferEof = reader.getPacket(true); if (bufferEof.readByte() != EOF) { //using IOException to close connection, throw new IOException( "Packets out of order when reading field packets, expected was EOF stream." + ((options.enablePacketDebug) ? getTraces() : "Packet contents (hex) = " + Utils.hexdump(options.maxQuerySizeToLog, 0, bufferEof.limit, bufferEof.buf))); } bufferEof.skipBytes(2); //Skip warningCount callableResult = (bufferEof.readShort() & ServerStatus.PS_OUT_PARAMETERS) != 0; } //read resultSet SelectResultSet selectResultSet; if (results.getResultSetConcurrency() == ResultSet.CONCUR_READ_ONLY) { selectResultSet = new SelectResultSet(ci, results, this, reader, callableResult, eofDeprecated); } else { //remove fetch size to permit updating results without creating new connection results.removeFetchSize(); selectResultSet = new UpdatableResultSet(ci, results, this, reader, callableResult, eofDeprecated); } results.addResultSet(selectResultSet, hasMoreResults() || results.getFetchSize() > 0); } catch (IOException e) { throw handleIoException(e); } }
java
private void readResultSet(Buffer buffer, Results results) throws SQLException { long fieldCount = buffer.getLengthEncodedNumeric(); try { //read columns information's ColumnInformation[] ci = new ColumnInformation[(int) fieldCount]; for (int i = 0; i < fieldCount; i++) { ci[i] = new ColumnInformation(reader.getPacket(false)); } boolean callableResult = false; if (!eofDeprecated) { //read EOF packet //EOF status is mandatory because : // - Call query will have an callable resultSet for OUT parameters // -> this resultSet must be identified and not listed in JDBC statement.getResultSet() // - after a callable resultSet, a OK packet is send, but mysql does send the a bad "more result flag" Buffer bufferEof = reader.getPacket(true); if (bufferEof.readByte() != EOF) { //using IOException to close connection, throw new IOException( "Packets out of order when reading field packets, expected was EOF stream." + ((options.enablePacketDebug) ? getTraces() : "Packet contents (hex) = " + Utils.hexdump(options.maxQuerySizeToLog, 0, bufferEof.limit, bufferEof.buf))); } bufferEof.skipBytes(2); //Skip warningCount callableResult = (bufferEof.readShort() & ServerStatus.PS_OUT_PARAMETERS) != 0; } //read resultSet SelectResultSet selectResultSet; if (results.getResultSetConcurrency() == ResultSet.CONCUR_READ_ONLY) { selectResultSet = new SelectResultSet(ci, results, this, reader, callableResult, eofDeprecated); } else { //remove fetch size to permit updating results without creating new connection results.removeFetchSize(); selectResultSet = new UpdatableResultSet(ci, results, this, reader, callableResult, eofDeprecated); } results.addResultSet(selectResultSet, hasMoreResults() || results.getFetchSize() > 0); } catch (IOException e) { throw handleIoException(e); } }
[ "private", "void", "readResultSet", "(", "Buffer", "buffer", ",", "Results", "results", ")", "throws", "SQLException", "{", "long", "fieldCount", "=", "buffer", ".", "getLengthEncodedNumeric", "(", ")", ";", "try", "{", "//read columns information's", "ColumnInforma...
Read ResultSet Packet. @param buffer current buffer @param results result object @throws SQLException if sub-result connection fail @see <a href="https://mariadb.com/kb/en/mariadb/resultset/">resultSet packets</a>
[ "Read", "ResultSet", "Packet", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1688-L1735
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.prolog
public void prolog(long maxRows, boolean hasProxy, MariaDbConnection connection, MariaDbStatement statement) throws SQLException { if (explicitClosed) { throw new SQLException("execute() is called on closed connection"); } //old failover handling if (!hasProxy && shouldReconnectWithoutProxy()) { try { connectWithoutProxy(); } catch (SQLException qe) { ExceptionMapper.throwException(qe, connection, statement); } } try { setMaxRows(maxRows); } catch (SQLException qe) { ExceptionMapper.throwException(qe, connection, statement); } connection.reenableWarnings(); }
java
public void prolog(long maxRows, boolean hasProxy, MariaDbConnection connection, MariaDbStatement statement) throws SQLException { if (explicitClosed) { throw new SQLException("execute() is called on closed connection"); } //old failover handling if (!hasProxy && shouldReconnectWithoutProxy()) { try { connectWithoutProxy(); } catch (SQLException qe) { ExceptionMapper.throwException(qe, connection, statement); } } try { setMaxRows(maxRows); } catch (SQLException qe) { ExceptionMapper.throwException(qe, connection, statement); } connection.reenableWarnings(); }
[ "public", "void", "prolog", "(", "long", "maxRows", ",", "boolean", "hasProxy", ",", "MariaDbConnection", "connection", ",", "MariaDbStatement", "statement", ")", "throws", "SQLException", "{", "if", "(", "explicitClosed", ")", "{", "throw", "new", "SQLException",...
Preparation before command. @param maxRows query max rows @param hasProxy has proxy @param connection current connection @param statement current statement @throws SQLException if any error occur.
[ "Preparation", "before", "command", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1751-L1773
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.handleIoException
public SQLException handleIoException(Exception initialException) { boolean mustReconnect; boolean driverPreventError = false; if (initialException instanceof MaxAllowedPacketException) { mustReconnect = ((MaxAllowedPacketException) initialException).isMustReconnect(); driverPreventError = !mustReconnect; } else { mustReconnect = writer.exceedMaxLength(); } if (mustReconnect) { try { connect(); } catch (SQLException queryException) { connected = false; return new SQLNonTransientConnectionException(initialException.getMessage() + "\nError during reconnection" + getTraces(), CONNECTION_EXCEPTION.getSqlState(), initialException); } try { resetStateAfterFailover(getMaxRows(), getTransactionIsolationLevel(), getDatabase(), getAutocommit()); } catch (SQLException queryException) { return new SQLException("reconnection succeed, but resetting previous state failed", UNDEFINED_SQLSTATE.getSqlState() + getTraces(), initialException); } return new SQLTransientConnectionException("Could not send query: query size is >= to max_allowed_packet (" + writer.getMaxAllowedPacket() + ")" + getTraces(), UNDEFINED_SQLSTATE.getSqlState(), initialException); } if (!driverPreventError) { connected = false; } return new SQLNonTransientConnectionException(initialException.getMessage() + getTraces(), driverPreventError ? UNDEFINED_SQLSTATE.getSqlState() : CONNECTION_EXCEPTION.getSqlState(), initialException); }
java
public SQLException handleIoException(Exception initialException) { boolean mustReconnect; boolean driverPreventError = false; if (initialException instanceof MaxAllowedPacketException) { mustReconnect = ((MaxAllowedPacketException) initialException).isMustReconnect(); driverPreventError = !mustReconnect; } else { mustReconnect = writer.exceedMaxLength(); } if (mustReconnect) { try { connect(); } catch (SQLException queryException) { connected = false; return new SQLNonTransientConnectionException(initialException.getMessage() + "\nError during reconnection" + getTraces(), CONNECTION_EXCEPTION.getSqlState(), initialException); } try { resetStateAfterFailover(getMaxRows(), getTransactionIsolationLevel(), getDatabase(), getAutocommit()); } catch (SQLException queryException) { return new SQLException("reconnection succeed, but resetting previous state failed", UNDEFINED_SQLSTATE.getSqlState() + getTraces(), initialException); } return new SQLTransientConnectionException("Could not send query: query size is >= to max_allowed_packet (" + writer.getMaxAllowedPacket() + ")" + getTraces(), UNDEFINED_SQLSTATE.getSqlState(), initialException); } if (!driverPreventError) { connected = false; } return new SQLNonTransientConnectionException(initialException.getMessage() + getTraces(), driverPreventError ? UNDEFINED_SQLSTATE.getSqlState() : CONNECTION_EXCEPTION.getSqlState(), initialException); }
[ "public", "SQLException", "handleIoException", "(", "Exception", "initialException", ")", "{", "boolean", "mustReconnect", ";", "boolean", "driverPreventError", "=", "false", ";", "if", "(", "initialException", "instanceof", "MaxAllowedPacketException", ")", "{", "mustR...
Handle IoException (reconnect if Exception is due to having send too much data, making server close the connection. <p>There is 3 kind of IOException :</p> <ol> <li> MaxAllowedPacketException : without need of reconnect : thrown when driver don't send packet that would have been too big then error is not a CONNECTION_EXCEPTION</li> <li>packets size is greater than max_allowed_packet (can be checked with writer.isAllowedCmdLength()). Need to reconnect</li> <li>unknown IO error throw a CONNECTION_EXCEPTION</li> </ol> @param initialException initial Io error @return the resulting error to return to client.
[ "Handle", "IoException", "(", "reconnect", "if", "Exception", "is", "due", "to", "having", "send", "too", "much", "data", "making", "server", "close", "the", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1857-L1897
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimeParameter.java
TimeParameter.writeTo
public void writeTo(final PacketOutputStream pos) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(timeZone); String dateString = sdf.format(time); pos.write(QUOTE); pos.write(dateString.getBytes()); int microseconds = (int) (time.getTime() % 1000) * 1000; if (microseconds > 0 && fractionalSeconds) { pos.write('.'); int factor = 100000; while (microseconds > 0) { int dig = microseconds / factor; pos.write('0' + dig); microseconds -= dig * factor; factor /= 10; } } pos.write(QUOTE); }
java
public void writeTo(final PacketOutputStream pos) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(timeZone); String dateString = sdf.format(time); pos.write(QUOTE); pos.write(dateString.getBytes()); int microseconds = (int) (time.getTime() % 1000) * 1000; if (microseconds > 0 && fractionalSeconds) { pos.write('.'); int factor = 100000; while (microseconds > 0) { int dig = microseconds / factor; pos.write('0' + dig); microseconds -= dig * factor; factor /= 10; } } pos.write(QUOTE); }
[ "public", "void", "writeTo", "(", "final", "PacketOutputStream", "pos", ")", "throws", "IOException", "{", "SimpleDateFormat", "sdf", "=", "new", "SimpleDateFormat", "(", "\"HH:mm:ss\"", ")", ";", "sdf", ".", "setTimeZone", "(", "timeZone", ")", ";", "String", ...
Write Time parameter to outputStream. @param pos the stream to write to
[ "Write", "Time", "parameter", "to", "outputStream", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/TimeParameter.java#L88-L107
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/Driver.java
Driver.connect
public Connection connect(final String url, final Properties props) throws SQLException { UrlParser urlParser = UrlParser.parse(url, props); if (urlParser == null || urlParser.getHostAddresses() == null) { return null; } else { return MariaDbConnection.newConnection(urlParser, null); } }
java
public Connection connect(final String url, final Properties props) throws SQLException { UrlParser urlParser = UrlParser.parse(url, props); if (urlParser == null || urlParser.getHostAddresses() == null) { return null; } else { return MariaDbConnection.newConnection(urlParser, null); } }
[ "public", "Connection", "connect", "(", "final", "String", "url", ",", "final", "Properties", "props", ")", "throws", "SQLException", "{", "UrlParser", "urlParser", "=", "UrlParser", ".", "parse", "(", "url", ",", "props", ")", ";", "if", "(", "urlParser", ...
Connect to the given connection string. @param url the url to connect to @return a connection @throws SQLException if it is not possible to connect
[ "Connect", "to", "the", "given", "connection", "string", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/Driver.java#L86-L95
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/Driver.java
Driver.getPropertyInfo
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { if (url != null) { UrlParser urlParser = UrlParser.parse(url, info); if (urlParser == null || urlParser.getOptions() == null) { return new DriverPropertyInfo[0]; } List<DriverPropertyInfo> props = new ArrayList<>(); for (DefaultOptions o : DefaultOptions.values()) { try { Field field = Options.class.getField(o.getOptionName()); Object value = field.get(urlParser.getOptions()); DriverPropertyInfo propertyInfo = new DriverPropertyInfo(field.getName(), value == null ? null : value.toString()); propertyInfo.description = o.getDescription(); propertyInfo.required = o.isRequired(); props.add(propertyInfo); } catch (NoSuchFieldException | IllegalAccessException e) { //eat error } } return props.toArray(new DriverPropertyInfo[props.size()]); } return new DriverPropertyInfo[0]; }
java
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { if (url != null) { UrlParser urlParser = UrlParser.parse(url, info); if (urlParser == null || urlParser.getOptions() == null) { return new DriverPropertyInfo[0]; } List<DriverPropertyInfo> props = new ArrayList<>(); for (DefaultOptions o : DefaultOptions.values()) { try { Field field = Options.class.getField(o.getOptionName()); Object value = field.get(urlParser.getOptions()); DriverPropertyInfo propertyInfo = new DriverPropertyInfo(field.getName(), value == null ? null : value.toString()); propertyInfo.description = o.getDescription(); propertyInfo.required = o.isRequired(); props.add(propertyInfo); } catch (NoSuchFieldException | IllegalAccessException e) { //eat error } } return props.toArray(new DriverPropertyInfo[props.size()]); } return new DriverPropertyInfo[0]; }
[ "public", "DriverPropertyInfo", "[", "]", "getPropertyInfo", "(", "String", "url", ",", "Properties", "info", ")", "throws", "SQLException", "{", "if", "(", "url", "!=", "null", ")", "{", "UrlParser", "urlParser", "=", "UrlParser", ".", "parse", "(", "url", ...
Get the property info. @param url the url to get properties for @param info the info props @return something - not implemented @throws SQLException if there is a problem getting the property info
[ "Get", "the", "property", "info", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/Driver.java#L116-L143
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.initializeConnection
@Override public void initializeConnection() throws SQLException { super.initializeConnection(); try { reconnectFailedConnection(new SearchFilter(true)); } catch (SQLException e) { //initializeConnection failed checkInitialConnection(e); } }
java
@Override public void initializeConnection() throws SQLException { super.initializeConnection(); try { reconnectFailedConnection(new SearchFilter(true)); } catch (SQLException e) { //initializeConnection failed checkInitialConnection(e); } }
[ "@", "Override", "public", "void", "initializeConnection", "(", ")", "throws", "SQLException", "{", "super", ".", "initializeConnection", "(", ")", ";", "try", "{", "reconnectFailedConnection", "(", "new", "SearchFilter", "(", "true", ")", ")", ";", "}", "catc...
Initialize connections. @throws SQLException if a connection error append.
[ "Initialize", "connections", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L166-L175
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.checkWaitingConnection
public void checkWaitingConnection() throws SQLException { if (isSecondaryHostFail()) { proxy.lock.lock(); try { Protocol waitingProtocol = waitNewSecondaryProtocol.getAndSet(null); if (waitingProtocol != null && pingSecondaryProtocol(waitingProtocol)) { lockAndSwitchSecondary(waitingProtocol); } } finally { proxy.lock.unlock(); } } if (isMasterHostFail()) { proxy.lock.lock(); try { Protocol waitingProtocol = waitNewMasterProtocol.getAndSet(null); if (waitingProtocol != null && pingMasterProtocol(waitingProtocol)) { lockAndSwitchMaster(waitingProtocol); } } finally { proxy.lock.unlock(); } } }
java
public void checkWaitingConnection() throws SQLException { if (isSecondaryHostFail()) { proxy.lock.lock(); try { Protocol waitingProtocol = waitNewSecondaryProtocol.getAndSet(null); if (waitingProtocol != null && pingSecondaryProtocol(waitingProtocol)) { lockAndSwitchSecondary(waitingProtocol); } } finally { proxy.lock.unlock(); } } if (isMasterHostFail()) { proxy.lock.lock(); try { Protocol waitingProtocol = waitNewMasterProtocol.getAndSet(null); if (waitingProtocol != null && pingMasterProtocol(waitingProtocol)) { lockAndSwitchMaster(waitingProtocol); } } finally { proxy.lock.unlock(); } } }
[ "public", "void", "checkWaitingConnection", "(", ")", "throws", "SQLException", "{", "if", "(", "isSecondaryHostFail", "(", ")", ")", "{", "proxy", ".", "lock", ".", "lock", "(", ")", ";", "try", "{", "Protocol", "waitingProtocol", "=", "waitNewSecondaryProtoc...
Verify that there is waiting connection that have to replace failing one. If there is replace failed connection with new one. @throws SQLException if error occur
[ "Verify", "that", "there", "is", "waiting", "connection", "that", "have", "to", "replace", "failing", "one", ".", "If", "there", "is", "replace", "failed", "connection", "with", "new", "one", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L439-L463
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.reconnectFailedConnection
public void reconnectFailedConnection(SearchFilter searchFilter) throws SQLException { if (!searchFilter.isInitialConnection() && (isExplicitClosed() || (searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail())) { return; } //check if a connection has been retrieved by failoverLoop during lock if (!searchFilter.isFailoverLoop()) { try { checkWaitingConnection(); if ((searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail()) { return; } } catch (ReconnectDuringTransactionException e) { //don't throw an exception for this specific exception return; } } currentConnectionAttempts.incrementAndGet(); resetOldsBlackListHosts(); //put the list in the following order // - random order not blacklist and not connected host // - random order blacklist host // - connected host List<HostAddress> loopAddress = new LinkedList<>(urlParser.getHostAddresses()); loopAddress.removeAll(getBlacklistKeys()); Collections.shuffle(loopAddress); List<HostAddress> blacklistShuffle = new LinkedList<>(getBlacklistKeys()); blacklistShuffle.retainAll(urlParser.getHostAddresses()); Collections.shuffle(blacklistShuffle); loopAddress.addAll(blacklistShuffle); //put connected at end if (masterProtocol != null && !isMasterHostFail()) { loopAddress.remove(masterProtocol.getHostAddress()); loopAddress.add(masterProtocol.getHostAddress()); } if (secondaryProtocol != null && !isSecondaryHostFail()) { loopAddress.remove(secondaryProtocol.getHostAddress()); loopAddress.add(secondaryProtocol.getHostAddress()); } if ((isMasterHostFail() || isSecondaryHostFail()) || searchFilter.isInitialConnection()) { //while permit to avoid case when succeeded creating a new Master connection //and ping master connection fail a few millissecond after, //resulting a masterConnection not initialized. do { MastersSlavesProtocol.loop(this, globalInfo, loopAddress, searchFilter); //close loop if all connection are retrieved if (!searchFilter.isFailoverLoop()) { try { checkWaitingConnection(); } catch (ReconnectDuringTransactionException e) { //don't throw an exception for this specific exception } } } while (searchFilter.isInitialConnection() && !(masterProtocol != null || (urlParser.getOptions().allowMasterDownConnection && secondaryProtocol != null))); if (searchFilter.isInitialConnection() && masterProtocol == null && currentReadOnlyAsked) { currentProtocol = this.secondaryProtocol; currentReadOnlyAsked = true; } } }
java
public void reconnectFailedConnection(SearchFilter searchFilter) throws SQLException { if (!searchFilter.isInitialConnection() && (isExplicitClosed() || (searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail())) { return; } //check if a connection has been retrieved by failoverLoop during lock if (!searchFilter.isFailoverLoop()) { try { checkWaitingConnection(); if ((searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail()) { return; } } catch (ReconnectDuringTransactionException e) { //don't throw an exception for this specific exception return; } } currentConnectionAttempts.incrementAndGet(); resetOldsBlackListHosts(); //put the list in the following order // - random order not blacklist and not connected host // - random order blacklist host // - connected host List<HostAddress> loopAddress = new LinkedList<>(urlParser.getHostAddresses()); loopAddress.removeAll(getBlacklistKeys()); Collections.shuffle(loopAddress); List<HostAddress> blacklistShuffle = new LinkedList<>(getBlacklistKeys()); blacklistShuffle.retainAll(urlParser.getHostAddresses()); Collections.shuffle(blacklistShuffle); loopAddress.addAll(blacklistShuffle); //put connected at end if (masterProtocol != null && !isMasterHostFail()) { loopAddress.remove(masterProtocol.getHostAddress()); loopAddress.add(masterProtocol.getHostAddress()); } if (secondaryProtocol != null && !isSecondaryHostFail()) { loopAddress.remove(secondaryProtocol.getHostAddress()); loopAddress.add(secondaryProtocol.getHostAddress()); } if ((isMasterHostFail() || isSecondaryHostFail()) || searchFilter.isInitialConnection()) { //while permit to avoid case when succeeded creating a new Master connection //and ping master connection fail a few millissecond after, //resulting a masterConnection not initialized. do { MastersSlavesProtocol.loop(this, globalInfo, loopAddress, searchFilter); //close loop if all connection are retrieved if (!searchFilter.isFailoverLoop()) { try { checkWaitingConnection(); } catch (ReconnectDuringTransactionException e) { //don't throw an exception for this specific exception } } } while (searchFilter.isInitialConnection() && !(masterProtocol != null || (urlParser.getOptions().allowMasterDownConnection && secondaryProtocol != null))); if (searchFilter.isInitialConnection() && masterProtocol == null && currentReadOnlyAsked) { currentProtocol = this.secondaryProtocol; currentReadOnlyAsked = true; } } }
[ "public", "void", "reconnectFailedConnection", "(", "SearchFilter", "searchFilter", ")", "throws", "SQLException", "{", "if", "(", "!", "searchFilter", ".", "isInitialConnection", "(", ")", "&&", "(", "isExplicitClosed", "(", ")", "||", "(", "searchFilter", ".", ...
Loop to connect. @throws SQLException if there is any error during reconnection
[ "Loop", "to", "connect", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L471-L544
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.foundActiveMaster
public void foundActiveMaster(Protocol newMasterProtocol) { if (isMasterHostFail()) { if (isExplicitClosed()) { newMasterProtocol.close(); return; } if (!waitNewMasterProtocol.compareAndSet(null, newMasterProtocol)) { newMasterProtocol.close(); } } else { newMasterProtocol.close(); } }
java
public void foundActiveMaster(Protocol newMasterProtocol) { if (isMasterHostFail()) { if (isExplicitClosed()) { newMasterProtocol.close(); return; } if (!waitNewMasterProtocol.compareAndSet(null, newMasterProtocol)) { newMasterProtocol.close(); } } else { newMasterProtocol.close(); } }
[ "public", "void", "foundActiveMaster", "(", "Protocol", "newMasterProtocol", ")", "{", "if", "(", "isMasterHostFail", "(", ")", ")", "{", "if", "(", "isExplicitClosed", "(", ")", ")", "{", "newMasterProtocol", ".", "close", "(", ")", ";", "return", ";", "}...
Method called when a new Master connection is found after a fallback. @param newMasterProtocol the new active connection
[ "Method", "called", "when", "a", "new", "Master", "connection", "is", "found", "after", "a", "fallback", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L551-L564
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.lockAndSwitchMaster
public void lockAndSwitchMaster(Protocol newMasterProtocol) throws ReconnectDuringTransactionException { if (masterProtocol != null && !masterProtocol.isClosed()) { masterProtocol.close(); } if (!currentReadOnlyAsked || isSecondaryHostFail()) { //actually on a secondary read-only because master was unknown. //So select master as currentConnection if (currentProtocol != null) { try { syncConnection(currentProtocol, newMasterProtocol); } catch (Exception e) { //Some error append during connection parameter synchronisation } } //switching current connection to master connection currentProtocol = newMasterProtocol; } boolean inTransaction = this.masterProtocol != null && this.masterProtocol.inTransaction(); this.masterProtocol = newMasterProtocol; resetMasterFailoverData(); if (inTransaction) { //master connection was down, so has been change for a new active connection //problem was there was an active connection -> must throw exception so client known it throw new ReconnectDuringTransactionException( "Connection reconnect automatically during an active transaction", 1401, "25S03"); } }
java
public void lockAndSwitchMaster(Protocol newMasterProtocol) throws ReconnectDuringTransactionException { if (masterProtocol != null && !masterProtocol.isClosed()) { masterProtocol.close(); } if (!currentReadOnlyAsked || isSecondaryHostFail()) { //actually on a secondary read-only because master was unknown. //So select master as currentConnection if (currentProtocol != null) { try { syncConnection(currentProtocol, newMasterProtocol); } catch (Exception e) { //Some error append during connection parameter synchronisation } } //switching current connection to master connection currentProtocol = newMasterProtocol; } boolean inTransaction = this.masterProtocol != null && this.masterProtocol.inTransaction(); this.masterProtocol = newMasterProtocol; resetMasterFailoverData(); if (inTransaction) { //master connection was down, so has been change for a new active connection //problem was there was an active connection -> must throw exception so client known it throw new ReconnectDuringTransactionException( "Connection reconnect automatically during an active transaction", 1401, "25S03"); } }
[ "public", "void", "lockAndSwitchMaster", "(", "Protocol", "newMasterProtocol", ")", "throws", "ReconnectDuringTransactionException", "{", "if", "(", "masterProtocol", "!=", "null", "&&", "!", "masterProtocol", ".", "isClosed", "(", ")", ")", "{", "masterProtocol", "...
Use the parameter newMasterProtocol as new current master connection. <i>Lock must be set</i> @param newMasterProtocol new master connection @throws ReconnectDuringTransactionException if there was an active transaction.
[ "Use", "the", "parameter", "newMasterProtocol", "as", "new", "current", "master", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L574-L603
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.foundActiveSecondary
public void foundActiveSecondary(Protocol newSecondaryProtocol) throws SQLException { if (isSecondaryHostFail()) { if (isExplicitClosed()) { newSecondaryProtocol.close(); return; } if (proxy.lock.tryLock()) { try { lockAndSwitchSecondary(newSecondaryProtocol); } finally { proxy.lock.unlock(); } } else { if (!waitNewSecondaryProtocol.compareAndSet(null, newSecondaryProtocol)) { newSecondaryProtocol.close(); } } } else { newSecondaryProtocol.close(); } }
java
public void foundActiveSecondary(Protocol newSecondaryProtocol) throws SQLException { if (isSecondaryHostFail()) { if (isExplicitClosed()) { newSecondaryProtocol.close(); return; } if (proxy.lock.tryLock()) { try { lockAndSwitchSecondary(newSecondaryProtocol); } finally { proxy.lock.unlock(); } } else { if (!waitNewSecondaryProtocol.compareAndSet(null, newSecondaryProtocol)) { newSecondaryProtocol.close(); } } } else { newSecondaryProtocol.close(); } }
[ "public", "void", "foundActiveSecondary", "(", "Protocol", "newSecondaryProtocol", ")", "throws", "SQLException", "{", "if", "(", "isSecondaryHostFail", "(", ")", ")", "{", "if", "(", "isExplicitClosed", "(", ")", ")", "{", "newSecondaryProtocol", ".", "close", ...
Method called when a new secondary connection is found after a fallback. @param newSecondaryProtocol the new active connection @throws SQLException if switch failed
[ "Method", "called", "when", "a", "new", "secondary", "connection", "is", "found", "after", "a", "fallback", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L611-L632
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.lockAndSwitchSecondary
public void lockAndSwitchSecondary(Protocol newSecondaryProtocol) throws SQLException { if (secondaryProtocol != null && !secondaryProtocol.isClosed()) { secondaryProtocol.close(); } //if asked to be on read only connection, switching to this new connection if (currentReadOnlyAsked || (urlParser.getOptions().failOnReadOnly && !currentReadOnlyAsked && isMasterHostFail())) { if (currentProtocol == null) { try { syncConnection(currentProtocol, newSecondaryProtocol); } catch (Exception e) { //Some error append during connection parameter synchronisation } } currentProtocol = newSecondaryProtocol; } //set new found connection as slave connection. this.secondaryProtocol = newSecondaryProtocol; if (urlParser.getOptions().assureReadOnly) { setSessionReadOnly(true, this.secondaryProtocol); } resetSecondaryFailoverData(); }
java
public void lockAndSwitchSecondary(Protocol newSecondaryProtocol) throws SQLException { if (secondaryProtocol != null && !secondaryProtocol.isClosed()) { secondaryProtocol.close(); } //if asked to be on read only connection, switching to this new connection if (currentReadOnlyAsked || (urlParser.getOptions().failOnReadOnly && !currentReadOnlyAsked && isMasterHostFail())) { if (currentProtocol == null) { try { syncConnection(currentProtocol, newSecondaryProtocol); } catch (Exception e) { //Some error append during connection parameter synchronisation } } currentProtocol = newSecondaryProtocol; } //set new found connection as slave connection. this.secondaryProtocol = newSecondaryProtocol; if (urlParser.getOptions().assureReadOnly) { setSessionReadOnly(true, this.secondaryProtocol); } resetSecondaryFailoverData(); }
[ "public", "void", "lockAndSwitchSecondary", "(", "Protocol", "newSecondaryProtocol", ")", "throws", "SQLException", "{", "if", "(", "secondaryProtocol", "!=", "null", "&&", "!", "secondaryProtocol", ".", "isClosed", "(", ")", ")", "{", "secondaryProtocol", ".", "c...
Use the parameter newSecondaryProtocol as new current secondary connection. @param newSecondaryProtocol new secondary connection @throws SQLException if an error occur during setting session read-only
[ "Use", "the", "parameter", "newSecondaryProtocol", "as", "new", "current", "secondary", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L640-L665
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.primaryFail
public HandleErrorResult primaryFail(Method method, Object[] args, boolean killCmd) { boolean alreadyClosed = masterProtocol == null || !masterProtocol.isConnected(); boolean inTransaction = masterProtocol != null && masterProtocol.inTransaction(); //in case of SocketTimeoutException due to having set socketTimeout, must force connection close if (masterProtocol != null && masterProtocol.isConnected()) { masterProtocol.close(); } //fail on slave if parameter permit so if (urlParser.getOptions().failOnReadOnly && !isSecondaryHostFail()) { try { if (this.secondaryProtocol != null && this.secondaryProtocol.ping()) { //switching to secondary connection proxy.lock.lock(); try { if (masterProtocol != null) { syncConnection(masterProtocol, this.secondaryProtocol); } currentProtocol = this.secondaryProtocol; } finally { proxy.lock.unlock(); } FailoverLoop.addListener(this); try { return relaunchOperation(method, args); } catch (Exception e) { //relaunchOperation failed } return new HandleErrorResult(); } } catch (Exception e) { if (setSecondaryHostFail()) { blackListAndCloseConnection(this.secondaryProtocol); } } } try { reconnectFailedConnection(new SearchFilter(true, urlParser.getOptions().failOnReadOnly)); handleFailLoop(); if (currentProtocol != null) { if (killCmd) { return new HandleErrorResult(true, false); } if (currentReadOnlyAsked || alreadyClosed || !inTransaction && isQueryRelaunchable(method, args)) { //connection was not in transaction //can relaunch query logger.info("Connection to master lost, new master {}, conn={} found" + ", query type permit to be re-execute on new server without throwing exception", currentProtocol.getHostAddress(), currentProtocol.getServerThreadId()); return relaunchOperation(method, args); } //throw Exception because must inform client, even if connection is reconnected return new HandleErrorResult(true); } else { setMasterHostFail(); FailoverLoop.removeListener(this); return new HandleErrorResult(); } } catch (Exception e) { //we will throw a Connection exception that will close connection if (e.getCause() != null && proxy.hasToHandleFailover((SQLException) e.getCause()) && currentProtocol != null && currentProtocol.isConnected()) { currentProtocol.close(); } setMasterHostFail(); FailoverLoop.removeListener(this); return new HandleErrorResult(); } }
java
public HandleErrorResult primaryFail(Method method, Object[] args, boolean killCmd) { boolean alreadyClosed = masterProtocol == null || !masterProtocol.isConnected(); boolean inTransaction = masterProtocol != null && masterProtocol.inTransaction(); //in case of SocketTimeoutException due to having set socketTimeout, must force connection close if (masterProtocol != null && masterProtocol.isConnected()) { masterProtocol.close(); } //fail on slave if parameter permit so if (urlParser.getOptions().failOnReadOnly && !isSecondaryHostFail()) { try { if (this.secondaryProtocol != null && this.secondaryProtocol.ping()) { //switching to secondary connection proxy.lock.lock(); try { if (masterProtocol != null) { syncConnection(masterProtocol, this.secondaryProtocol); } currentProtocol = this.secondaryProtocol; } finally { proxy.lock.unlock(); } FailoverLoop.addListener(this); try { return relaunchOperation(method, args); } catch (Exception e) { //relaunchOperation failed } return new HandleErrorResult(); } } catch (Exception e) { if (setSecondaryHostFail()) { blackListAndCloseConnection(this.secondaryProtocol); } } } try { reconnectFailedConnection(new SearchFilter(true, urlParser.getOptions().failOnReadOnly)); handleFailLoop(); if (currentProtocol != null) { if (killCmd) { return new HandleErrorResult(true, false); } if (currentReadOnlyAsked || alreadyClosed || !inTransaction && isQueryRelaunchable(method, args)) { //connection was not in transaction //can relaunch query logger.info("Connection to master lost, new master {}, conn={} found" + ", query type permit to be re-execute on new server without throwing exception", currentProtocol.getHostAddress(), currentProtocol.getServerThreadId()); return relaunchOperation(method, args); } //throw Exception because must inform client, even if connection is reconnected return new HandleErrorResult(true); } else { setMasterHostFail(); FailoverLoop.removeListener(this); return new HandleErrorResult(); } } catch (Exception e) { //we will throw a Connection exception that will close connection if (e.getCause() != null && proxy.hasToHandleFailover((SQLException) e.getCause()) && currentProtocol != null && currentProtocol.isConnected()) { currentProtocol.close(); } setMasterHostFail(); FailoverLoop.removeListener(this); return new HandleErrorResult(); } }
[ "public", "HandleErrorResult", "primaryFail", "(", "Method", "method", ",", "Object", "[", "]", "args", ",", "boolean", "killCmd", ")", "{", "boolean", "alreadyClosed", "=", "masterProtocol", "==", "null", "||", "!", "masterProtocol", ".", "isConnected", "(", ...
To handle the newly detected failover on the master connection. @param method the initial called method @param args the initial args @param killCmd is the fail due to a KILL cmd @return an object to indicate if the previous Exception must be thrown, or the object resulting if a failover worked
[ "To", "handle", "the", "newly", "detected", "failover", "on", "the", "master", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L781-L857
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.reconnect
public void reconnect() throws SQLException { SearchFilter filter; boolean inTransaction = false; if (currentReadOnlyAsked) { filter = new SearchFilter(true, true); } else { inTransaction = masterProtocol != null && masterProtocol.inTransaction(); filter = new SearchFilter(true, urlParser.getOptions().failOnReadOnly); } reconnectFailedConnection(filter); handleFailLoop(); if (inTransaction) { throw new ReconnectDuringTransactionException( "Connection reconnect automatically during an active transaction", 1401, "25S03"); } }
java
public void reconnect() throws SQLException { SearchFilter filter; boolean inTransaction = false; if (currentReadOnlyAsked) { filter = new SearchFilter(true, true); } else { inTransaction = masterProtocol != null && masterProtocol.inTransaction(); filter = new SearchFilter(true, urlParser.getOptions().failOnReadOnly); } reconnectFailedConnection(filter); handleFailLoop(); if (inTransaction) { throw new ReconnectDuringTransactionException( "Connection reconnect automatically during an active transaction", 1401, "25S03"); } }
[ "public", "void", "reconnect", "(", ")", "throws", "SQLException", "{", "SearchFilter", "filter", ";", "boolean", "inTransaction", "=", "false", ";", "if", "(", "currentReadOnlyAsked", ")", "{", "filter", "=", "new", "SearchFilter", "(", "true", ",", "true", ...
Reconnect failed connection. @throws SQLException if reconnection has failed
[ "Reconnect", "failed", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L876-L891
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.pingSecondaryProtocol
private boolean pingSecondaryProtocol(Protocol protocol) { try { if (protocol != null && protocol.isConnected() && protocol.ping()) { return true; } } catch (Exception e) { protocol.close(); if (setSecondaryHostFail()) { addToBlacklist(protocol.getHostAddress()); } } return false; }
java
private boolean pingSecondaryProtocol(Protocol protocol) { try { if (protocol != null && protocol.isConnected() && protocol.ping()) { return true; } } catch (Exception e) { protocol.close(); if (setSecondaryHostFail()) { addToBlacklist(protocol.getHostAddress()); } } return false; }
[ "private", "boolean", "pingSecondaryProtocol", "(", "Protocol", "protocol", ")", "{", "try", "{", "if", "(", "protocol", "!=", "null", "&&", "protocol", ".", "isConnected", "(", ")", "&&", "protocol", ".", "ping", "(", ")", ")", "{", "return", "true", ";...
Ping secondary protocol. ! lock must be set ! @param protocol socket to ping @return true if ping is valid.
[ "Ping", "secondary", "protocol", ".", "!", "lock", "must", "be", "set", "!" ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L899-L912
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.secondaryFail
public HandleErrorResult secondaryFail(Method method, Object[] args, boolean killCmd) throws Throwable { proxy.lock.lock(); try { if (pingSecondaryProtocol(this.secondaryProtocol)) { return relaunchOperation(method, args); } } finally { proxy.lock.unlock(); } if (!isMasterHostFail()) { try { //check that master is on before switching to him if (masterProtocol != null && masterProtocol.isValid(1000)) { //switching to master connection syncConnection(secondaryProtocol, masterProtocol); proxy.lock.lock(); try { currentProtocol = masterProtocol; } finally { proxy.lock.unlock(); } FailoverLoop.addListener(this); logger.info("Connection to slave lost, using master connection" + ", query is re-execute on master server without throwing exception"); return relaunchOperation(method, args); //now that we are on master, relaunched result if the result was not crashing the master } } catch (Exception e) { //ping fail on master if (setMasterHostFail()) { blackListAndCloseConnection(masterProtocol); } } } try { reconnectFailedConnection(new SearchFilter(true, true)); handleFailLoop(); if (isSecondaryHostFail()) { syncConnection(this.secondaryProtocol, this.masterProtocol); proxy.lock.lock(); try { currentProtocol = this.masterProtocol; } finally { proxy.lock.unlock(); } } if (killCmd) { return new HandleErrorResult(true, false); } logger.info("Connection to slave lost, new slave {}, conn={} found" + ", query is re-execute on new server without throwing exception", currentProtocol.getHostAddress(), currentProtocol.getServerThreadId()); return relaunchOperation(method, args); //now that we are reconnect, relaunched result if the result was not crashing the node } catch (Exception ee) { //we will throw a Connection exception that will close connection FailoverLoop.removeListener(this); return new HandleErrorResult(); } }
java
public HandleErrorResult secondaryFail(Method method, Object[] args, boolean killCmd) throws Throwable { proxy.lock.lock(); try { if (pingSecondaryProtocol(this.secondaryProtocol)) { return relaunchOperation(method, args); } } finally { proxy.lock.unlock(); } if (!isMasterHostFail()) { try { //check that master is on before switching to him if (masterProtocol != null && masterProtocol.isValid(1000)) { //switching to master connection syncConnection(secondaryProtocol, masterProtocol); proxy.lock.lock(); try { currentProtocol = masterProtocol; } finally { proxy.lock.unlock(); } FailoverLoop.addListener(this); logger.info("Connection to slave lost, using master connection" + ", query is re-execute on master server without throwing exception"); return relaunchOperation(method, args); //now that we are on master, relaunched result if the result was not crashing the master } } catch (Exception e) { //ping fail on master if (setMasterHostFail()) { blackListAndCloseConnection(masterProtocol); } } } try { reconnectFailedConnection(new SearchFilter(true, true)); handleFailLoop(); if (isSecondaryHostFail()) { syncConnection(this.secondaryProtocol, this.masterProtocol); proxy.lock.lock(); try { currentProtocol = this.masterProtocol; } finally { proxy.lock.unlock(); } } if (killCmd) { return new HandleErrorResult(true, false); } logger.info("Connection to slave lost, new slave {}, conn={} found" + ", query is re-execute on new server without throwing exception", currentProtocol.getHostAddress(), currentProtocol.getServerThreadId()); return relaunchOperation(method, args); //now that we are reconnect, relaunched result if the result was not crashing the node } catch (Exception ee) { //we will throw a Connection exception that will close connection FailoverLoop.removeListener(this); return new HandleErrorResult(); } }
[ "public", "HandleErrorResult", "secondaryFail", "(", "Method", "method", ",", "Object", "[", "]", "args", ",", "boolean", "killCmd", ")", "throws", "Throwable", "{", "proxy", ".", "lock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "pingSecondaryPro...
To handle the newly detected failover on the secondary connection. @param method the initial called method @param args the initial args @param killCmd is fail due to a KILL command @return an object to indicate if the previous Exception must be thrown, or the object resulting if a failover worked @throws Throwable if failover has not catch error
[ "To", "handle", "the", "newly", "detected", "failover", "on", "the", "secondary", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L924-L989
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java
MastersSlavesListener.connectedHosts
public List<HostAddress> connectedHosts() { List<HostAddress> usedHost = new ArrayList<>(); if (isMasterHostFail()) { Protocol masterProtocol = waitNewMasterProtocol.get(); if (masterProtocol != null) { usedHost.add(masterProtocol.getHostAddress()); } } else { usedHost.add(masterProtocol.getHostAddress()); } if (isSecondaryHostFail()) { Protocol secondProtocol = waitNewSecondaryProtocol.get(); if (secondProtocol != null) { usedHost.add(secondProtocol.getHostAddress()); } } else { usedHost.add(secondaryProtocol.getHostAddress()); } return usedHost; }
java
public List<HostAddress> connectedHosts() { List<HostAddress> usedHost = new ArrayList<>(); if (isMasterHostFail()) { Protocol masterProtocol = waitNewMasterProtocol.get(); if (masterProtocol != null) { usedHost.add(masterProtocol.getHostAddress()); } } else { usedHost.add(masterProtocol.getHostAddress()); } if (isSecondaryHostFail()) { Protocol secondProtocol = waitNewSecondaryProtocol.get(); if (secondProtocol != null) { usedHost.add(secondProtocol.getHostAddress()); } } else { usedHost.add(secondaryProtocol.getHostAddress()); } return usedHost; }
[ "public", "List", "<", "HostAddress", ">", "connectedHosts", "(", ")", "{", "List", "<", "HostAddress", ">", "usedHost", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "isMasterHostFail", "(", ")", ")", "{", "Protocol", "masterProtocol", "=", "...
List current connected HostAddress. @return hostAddress List.
[ "List", "current", "connected", "HostAddress", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersSlavesListener.java#L1072-L1094
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersSlavesListener.java
AbstractMastersSlavesListener.handleFailover
public HandleErrorResult handleFailover(SQLException qe, Method method, Object[] args, Protocol protocol) throws Throwable { if (isExplicitClosed()) { throw new SQLException("Connection has been closed !"); } //check that failover is due to kill command boolean killCmd = qe != null && qe.getSQLState() != null && qe.getSQLState().equals("70100") && 1927 == qe.getErrorCode(); if (protocol != null) { if (protocol.mustBeMasterConnection()) { if (!protocol.isMasterConnection()) { logger.warn("SQL Primary node [{}, conn={}] is now in read-only mode. Exception : {}", this.currentProtocol.getHostAddress().toString(), this.currentProtocol.getServerThreadId(), qe.getMessage()); } else if (setMasterHostFail()) { logger.warn("SQL Primary node [{}, conn={}] connection fail. Reason : {}", this.currentProtocol.getHostAddress().toString(), this.currentProtocol.getServerThreadId(), qe.getMessage()); addToBlacklist(protocol.getHostAddress()); } return primaryFail(method, args, killCmd); } else { if (setSecondaryHostFail()) { logger.warn("SQL secondary node [{}, conn={}] connection fail. Reason : {}", this.currentProtocol.getHostAddress().toString(), this.currentProtocol.getServerThreadId(), qe.getMessage()); addToBlacklist(protocol.getHostAddress()); } return secondaryFail(method, args, killCmd); } } else { return primaryFail(method, args, killCmd); } }
java
public HandleErrorResult handleFailover(SQLException qe, Method method, Object[] args, Protocol protocol) throws Throwable { if (isExplicitClosed()) { throw new SQLException("Connection has been closed !"); } //check that failover is due to kill command boolean killCmd = qe != null && qe.getSQLState() != null && qe.getSQLState().equals("70100") && 1927 == qe.getErrorCode(); if (protocol != null) { if (protocol.mustBeMasterConnection()) { if (!protocol.isMasterConnection()) { logger.warn("SQL Primary node [{}, conn={}] is now in read-only mode. Exception : {}", this.currentProtocol.getHostAddress().toString(), this.currentProtocol.getServerThreadId(), qe.getMessage()); } else if (setMasterHostFail()) { logger.warn("SQL Primary node [{}, conn={}] connection fail. Reason : {}", this.currentProtocol.getHostAddress().toString(), this.currentProtocol.getServerThreadId(), qe.getMessage()); addToBlacklist(protocol.getHostAddress()); } return primaryFail(method, args, killCmd); } else { if (setSecondaryHostFail()) { logger.warn("SQL secondary node [{}, conn={}] connection fail. Reason : {}", this.currentProtocol.getHostAddress().toString(), this.currentProtocol.getServerThreadId(), qe.getMessage()); addToBlacklist(protocol.getHostAddress()); } return secondaryFail(method, args, killCmd); } } else { return primaryFail(method, args, killCmd); } }
[ "public", "HandleErrorResult", "handleFailover", "(", "SQLException", "qe", ",", "Method", "method", ",", "Object", "[", "]", "args", ",", "Protocol", "protocol", ")", "throws", "Throwable", "{", "if", "(", "isExplicitClosed", "(", ")", ")", "{", "throw", "n...
Handle failover on master or slave connection. @param method called method @param args methods parameters @param protocol current protocol @return HandleErrorResult object to indicate if query has finally been relaunched or exception if not. @throws Throwable if method with parameters doesn't exist
[ "Handle", "failover", "on", "master", "or", "slave", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersSlavesListener.java#L96-L137
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersSlavesListener.java
AbstractMastersSlavesListener.setSecondaryHostFail
public boolean setSecondaryHostFail() { if (secondaryHostFail.compareAndSet(false, true)) { secondaryHostFailNanos = System.nanoTime(); currentConnectionAttempts.set(0); return true; } return false; }
java
public boolean setSecondaryHostFail() { if (secondaryHostFail.compareAndSet(false, true)) { secondaryHostFailNanos = System.nanoTime(); currentConnectionAttempts.set(0); return true; } return false; }
[ "public", "boolean", "setSecondaryHostFail", "(", ")", "{", "if", "(", "secondaryHostFail", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "secondaryHostFailNanos", "=", "System", ".", "nanoTime", "(", ")", ";", "currentConnectionAttempts", ".",...
Set slave connection lost variables. @return true if fail wasn't seen before
[ "Set", "slave", "connection", "lost", "variables", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/AbstractMastersSlavesListener.java#L171-L178
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/io/TraceObject.java
TraceObject.remove
public void remove() { for (int i = 0; i < buf.length; i++) { buf[i] = null;// force null for easier garbage } buf = null; }
java
public void remove() { for (int i = 0; i < buf.length; i++) { buf[i] = null;// force null for easier garbage } buf = null; }
[ "public", "void", "remove", "(", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "buf", ".", "length", ";", "i", "++", ")", "{", "buf", "[", "i", "]", "=", "null", ";", "// force null for easier garbage", "}", "buf", "=", "null", ";", ...
Clear trace array for easy garbage.
[ "Clear", "trace", "array", "for", "easy", "garbage", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/io/TraceObject.java#L82-L87
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbDataSource.java
MariaDbDataSource.getPooledConnection
public PooledConnection getPooledConnection(String user, String password) throws SQLException { return new MariaDbPooledConnection((MariaDbConnection) getConnection(user, password)); }
java
public PooledConnection getPooledConnection(String user, String password) throws SQLException { return new MariaDbPooledConnection((MariaDbConnection) getConnection(user, password)); }
[ "public", "PooledConnection", "getPooledConnection", "(", "String", "user", ",", "String", "password", ")", "throws", "SQLException", "{", "return", "new", "MariaDbPooledConnection", "(", "(", "MariaDbConnection", ")", "getConnection", "(", "user", ",", "password", ...
Attempts to establish a physical database connection that can be used as a pooled connection. @param user the database user on whose behalf the connection is being made @param password the user's password @return a <code>PooledConnection</code> object that is a physical connection to the database that this <code>ConnectionPoolDataSource</code> object represents @throws SQLException if a database access error occurs
[ "Attempts", "to", "establish", "a", "physical", "database", "connection", "that", "can", "be", "used", "as", "a", "pooled", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbDataSource.java#L464-L466
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java
MastersFailoverListener.initializeConnection
@Override public void initializeConnection() throws SQLException { super.initializeConnection(); this.currentProtocol = null; //launching initial loop reconnectFailedConnection(new SearchFilter(true, false)); resetMasterFailoverData(); }
java
@Override public void initializeConnection() throws SQLException { super.initializeConnection(); this.currentProtocol = null; //launching initial loop reconnectFailedConnection(new SearchFilter(true, false)); resetMasterFailoverData(); }
[ "@", "Override", "public", "void", "initializeConnection", "(", ")", "throws", "SQLException", "{", "super", ".", "initializeConnection", "(", ")", ";", "this", ".", "currentProtocol", "=", "null", ";", "//launching initial loop", "reconnectFailedConnection", "(", "...
Connect to database. @throws SQLException if connection is on error.
[ "Connect", "to", "database", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java#L97-L104
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java
MastersFailoverListener.preExecute
public void preExecute() throws SQLException { lastQueryNanos = System.nanoTime(); //if connection is closed or failed on slave if (this.currentProtocol != null && this.currentProtocol.isClosed()) { preAutoReconnect(); } }
java
public void preExecute() throws SQLException { lastQueryNanos = System.nanoTime(); //if connection is closed or failed on slave if (this.currentProtocol != null && this.currentProtocol.isClosed()) { preAutoReconnect(); } }
[ "public", "void", "preExecute", "(", ")", "throws", "SQLException", "{", "lastQueryNanos", "=", "System", ".", "nanoTime", "(", ")", ";", "//if connection is closed or failed on slave", "if", "(", "this", ".", "currentProtocol", "!=", "null", "&&", "this", ".", ...
Before executing query, reconnect if connection is closed, and autoReconnect option is set. @throws SQLException if connection has been explicitly closed.
[ "Before", "executing", "query", "reconnect", "if", "connection", "is", "closed", "and", "autoReconnect", "option", "is", "set", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java#L111-L117
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java
MastersFailoverListener.reconnectFailedConnection
@Override public void reconnectFailedConnection(SearchFilter searchFilter) throws SQLException { proxy.lock.lock(); try { if (!searchFilter.isInitialConnection() && (isExplicitClosed() || !isMasterHostFail())) { return; } currentConnectionAttempts.incrementAndGet(); resetOldsBlackListHosts(); List<HostAddress> loopAddress = new LinkedList<>(urlParser.getHostAddresses()); if (HaMode.FAILOVER.equals(mode)) { //put the list in the following order // - random order not connected host // - random order blacklist host // - random order connected host loopAddress.removeAll(getBlacklistKeys()); Collections.shuffle(loopAddress); List<HostAddress> blacklistShuffle = new LinkedList<>(getBlacklistKeys()); blacklistShuffle.retainAll(urlParser.getHostAddresses()); Collections.shuffle(blacklistShuffle); loopAddress.addAll(blacklistShuffle); } else { //order in sequence loopAddress.removeAll(getBlacklistKeys()); loopAddress.addAll(getBlacklistKeys()); loopAddress.retainAll(urlParser.getHostAddresses()); } //put connected at end if (currentProtocol != null && !isMasterHostFail()) { loopAddress.remove(currentProtocol.getHostAddress()); //loopAddress.add(currentProtocol.getHostAddress()); } MasterProtocol.loop(this, globalInfo, loopAddress, searchFilter); //close loop if all connection are retrieved if (!isMasterHostFail()) { FailoverLoop.removeListener(this); } //if no error, reset failover variables resetMasterFailoverData(); } finally { proxy.lock.unlock(); } }
java
@Override public void reconnectFailedConnection(SearchFilter searchFilter) throws SQLException { proxy.lock.lock(); try { if (!searchFilter.isInitialConnection() && (isExplicitClosed() || !isMasterHostFail())) { return; } currentConnectionAttempts.incrementAndGet(); resetOldsBlackListHosts(); List<HostAddress> loopAddress = new LinkedList<>(urlParser.getHostAddresses()); if (HaMode.FAILOVER.equals(mode)) { //put the list in the following order // - random order not connected host // - random order blacklist host // - random order connected host loopAddress.removeAll(getBlacklistKeys()); Collections.shuffle(loopAddress); List<HostAddress> blacklistShuffle = new LinkedList<>(getBlacklistKeys()); blacklistShuffle.retainAll(urlParser.getHostAddresses()); Collections.shuffle(blacklistShuffle); loopAddress.addAll(blacklistShuffle); } else { //order in sequence loopAddress.removeAll(getBlacklistKeys()); loopAddress.addAll(getBlacklistKeys()); loopAddress.retainAll(urlParser.getHostAddresses()); } //put connected at end if (currentProtocol != null && !isMasterHostFail()) { loopAddress.remove(currentProtocol.getHostAddress()); //loopAddress.add(currentProtocol.getHostAddress()); } MasterProtocol.loop(this, globalInfo, loopAddress, searchFilter); //close loop if all connection are retrieved if (!isMasterHostFail()) { FailoverLoop.removeListener(this); } //if no error, reset failover variables resetMasterFailoverData(); } finally { proxy.lock.unlock(); } }
[ "@", "Override", "public", "void", "reconnectFailedConnection", "(", "SearchFilter", "searchFilter", ")", "throws", "SQLException", "{", "proxy", ".", "lock", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "!", "searchFilter", ".", "isInitialConnection", "...
Loop to connect failed hosts. @param searchFilter search parameters. @throws SQLException if there is any error during reconnection
[ "Loop", "to", "connect", "failed", "hosts", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java#L191-L239
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java
MastersFailoverListener.switchReadOnlyConnection
public void switchReadOnlyConnection(Boolean mustBeReadOnly) throws SQLException { if (urlParser.getOptions().assureReadOnly && currentReadOnlyAsked != mustBeReadOnly) { proxy.lock.lock(); try { // verify not updated now that hold lock, double check safe due to volatile if (currentReadOnlyAsked != mustBeReadOnly) { currentReadOnlyAsked = mustBeReadOnly; setSessionReadOnly(mustBeReadOnly, currentProtocol); } } finally { proxy.lock.unlock(); } } }
java
public void switchReadOnlyConnection(Boolean mustBeReadOnly) throws SQLException { if (urlParser.getOptions().assureReadOnly && currentReadOnlyAsked != mustBeReadOnly) { proxy.lock.lock(); try { // verify not updated now that hold lock, double check safe due to volatile if (currentReadOnlyAsked != mustBeReadOnly) { currentReadOnlyAsked = mustBeReadOnly; setSessionReadOnly(mustBeReadOnly, currentProtocol); } } finally { proxy.lock.unlock(); } } }
[ "public", "void", "switchReadOnlyConnection", "(", "Boolean", "mustBeReadOnly", ")", "throws", "SQLException", "{", "if", "(", "urlParser", ".", "getOptions", "(", ")", ".", "assureReadOnly", "&&", "currentReadOnlyAsked", "!=", "mustBeReadOnly", ")", "{", "proxy", ...
Force session to read-only according to options. @param mustBeReadOnly is read-only flag @throws SQLException if a connection error occur
[ "Force", "session", "to", "read", "-", "only", "according", "to", "options", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java#L247-L260
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java
MastersFailoverListener.foundActiveMaster
@Override public void foundActiveMaster(Protocol protocol) throws SQLException { if (isExplicitClosed()) { proxy.lock.lock(); try { protocol.close(); } finally { proxy.lock.unlock(); } return; } syncConnection(this.currentProtocol, protocol); proxy.lock.lock(); try { if (currentProtocol != null && !currentProtocol.isClosed()) { currentProtocol.close(); } currentProtocol = protocol; } finally { proxy.lock.unlock(); } resetMasterFailoverData(); FailoverLoop.removeListener(this); }
java
@Override public void foundActiveMaster(Protocol protocol) throws SQLException { if (isExplicitClosed()) { proxy.lock.lock(); try { protocol.close(); } finally { proxy.lock.unlock(); } return; } syncConnection(this.currentProtocol, protocol); proxy.lock.lock(); try { if (currentProtocol != null && !currentProtocol.isClosed()) { currentProtocol.close(); } currentProtocol = protocol; } finally { proxy.lock.unlock(); } resetMasterFailoverData(); FailoverLoop.removeListener(this); }
[ "@", "Override", "public", "void", "foundActiveMaster", "(", "Protocol", "protocol", ")", "throws", "SQLException", "{", "if", "(", "isExplicitClosed", "(", ")", ")", "{", "proxy", ".", "lock", ".", "lock", "(", ")", ";", "try", "{", "protocol", ".", "cl...
method called when a new Master connection is found after a fallback. @param protocol the new active connection
[ "method", "called", "when", "a", "new", "Master", "connection", "is", "found", "after", "a", "fallback", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java#L267-L291
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java
MastersFailoverListener.reconnect
public void reconnect() throws SQLException { boolean inTransaction = currentProtocol != null && currentProtocol.inTransaction(); reconnectFailedConnection(new SearchFilter(true, false)); handleFailLoop(); if (inTransaction) { throw new ReconnectDuringTransactionException( "Connection reconnect automatically during an active transaction", 1401, "25S03"); } }
java
public void reconnect() throws SQLException { boolean inTransaction = currentProtocol != null && currentProtocol.inTransaction(); reconnectFailedConnection(new SearchFilter(true, false)); handleFailLoop(); if (inTransaction) { throw new ReconnectDuringTransactionException( "Connection reconnect automatically during an active transaction", 1401, "25S03"); } }
[ "public", "void", "reconnect", "(", ")", "throws", "SQLException", "{", "boolean", "inTransaction", "=", "currentProtocol", "!=", "null", "&&", "currentProtocol", ".", "inTransaction", "(", ")", ";", "reconnectFailedConnection", "(", "new", "SearchFilter", "(", "t...
Try to reconnect connection. @throws SQLException if reconnect a new connection but there was an active transaction.
[ "Try", "to", "reconnect", "connection", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/failover/impl/MastersFailoverListener.java#L298-L306
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/authentication/gssapi/StandardGssapiAuthentication.java
StandardGssapiAuthentication.authenticate
public void authenticate(final PacketOutputStream out, final PacketInputStream in, final AtomicInteger sequence, final String servicePrincipalName, String mechanisms) throws SQLException, IOException { if ("".equals(servicePrincipalName)) { throw new SQLException("No principal name defined on server. " + "Please set server variable \"gssapi-principal-name\" or set option \"servicePrincipalName\"", "28000"); } if (System.getProperty("java.security.auth.login.config") == null) { final File jaasConfFile; try { jaasConfFile = File.createTempFile("jaas.conf", null); try (PrintStream bos = new PrintStream(new FileOutputStream(jaasConfFile))) { bos.print("Krb5ConnectorContext {\n" + "com.sun.security.auth.module.Krb5LoginModule required " + "useTicketCache=true " + "debug=true " + "renewTGT=true " + "doNotPrompt=true; };"); } jaasConfFile.deleteOnExit(); } catch (final IOException ex) { throw new UncheckedIOException(ex); } System.setProperty("java.security.auth.login.config", jaasConfFile.getCanonicalPath()); } try { LoginContext loginContext = new LoginContext("Krb5ConnectorContext"); // attempt authentication loginContext.login(); final Subject mySubject = loginContext.getSubject(); if (!mySubject.getPrincipals().isEmpty()) { try { PrivilegedExceptionAction<Void> action = () -> { try { Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2"); GSSManager manager = GSSManager.getInstance(); GSSName peerName = manager.createName(servicePrincipalName, GSSName.NT_USER_NAME); GSSContext context = manager.createContext(peerName, krb5Mechanism, null, GSSContext.DEFAULT_LIFETIME); context.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken; while (!context.isEstablished()) { outToken = context.initSecContext(inToken, 0, inToken.length); // Send a token to the peer if one was generated by acceptSecContext if (outToken != null) { out.startPacket(sequence.incrementAndGet()); out.write(outToken); out.flush(); } if (!context.isEstablished()) { Buffer buffer = in.getPacket(true); sequence.set(in.getLastPacketSeq()); inToken = buffer.readRawBytes(buffer.remaining()); } } } catch (GSSException le) { throw new SQLException("GSS-API authentication exception", "28000", 1045, le); } return null; }; Subject.doAs(mySubject, action); } catch (PrivilegedActionException exception) { throw new SQLException("GSS-API authentication exception", "28000", 1045, exception); } } else { throw new SQLException("GSS-API authentication exception : no credential cache not found.", "28000", 1045); } } catch (LoginException le) { throw new SQLException("GSS-API authentication exception", "28000", 1045, le); } }
java
public void authenticate(final PacketOutputStream out, final PacketInputStream in, final AtomicInteger sequence, final String servicePrincipalName, String mechanisms) throws SQLException, IOException { if ("".equals(servicePrincipalName)) { throw new SQLException("No principal name defined on server. " + "Please set server variable \"gssapi-principal-name\" or set option \"servicePrincipalName\"", "28000"); } if (System.getProperty("java.security.auth.login.config") == null) { final File jaasConfFile; try { jaasConfFile = File.createTempFile("jaas.conf", null); try (PrintStream bos = new PrintStream(new FileOutputStream(jaasConfFile))) { bos.print("Krb5ConnectorContext {\n" + "com.sun.security.auth.module.Krb5LoginModule required " + "useTicketCache=true " + "debug=true " + "renewTGT=true " + "doNotPrompt=true; };"); } jaasConfFile.deleteOnExit(); } catch (final IOException ex) { throw new UncheckedIOException(ex); } System.setProperty("java.security.auth.login.config", jaasConfFile.getCanonicalPath()); } try { LoginContext loginContext = new LoginContext("Krb5ConnectorContext"); // attempt authentication loginContext.login(); final Subject mySubject = loginContext.getSubject(); if (!mySubject.getPrincipals().isEmpty()) { try { PrivilegedExceptionAction<Void> action = () -> { try { Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2"); GSSManager manager = GSSManager.getInstance(); GSSName peerName = manager.createName(servicePrincipalName, GSSName.NT_USER_NAME); GSSContext context = manager.createContext(peerName, krb5Mechanism, null, GSSContext.DEFAULT_LIFETIME); context.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken; while (!context.isEstablished()) { outToken = context.initSecContext(inToken, 0, inToken.length); // Send a token to the peer if one was generated by acceptSecContext if (outToken != null) { out.startPacket(sequence.incrementAndGet()); out.write(outToken); out.flush(); } if (!context.isEstablished()) { Buffer buffer = in.getPacket(true); sequence.set(in.getLastPacketSeq()); inToken = buffer.readRawBytes(buffer.remaining()); } } } catch (GSSException le) { throw new SQLException("GSS-API authentication exception", "28000", 1045, le); } return null; }; Subject.doAs(mySubject, action); } catch (PrivilegedActionException exception) { throw new SQLException("GSS-API authentication exception", "28000", 1045, exception); } } else { throw new SQLException("GSS-API authentication exception : no credential cache not found.", "28000", 1045); } } catch (LoginException le) { throw new SQLException("GSS-API authentication exception", "28000", 1045, le); } }
[ "public", "void", "authenticate", "(", "final", "PacketOutputStream", "out", ",", "final", "PacketInputStream", "in", ",", "final", "AtomicInteger", "sequence", ",", "final", "String", "servicePrincipalName", ",", "String", "mechanisms", ")", "throws", "SQLException",...
Process default GSS plugin authentication. @param out out stream @param in in stream @param sequence packet sequence @param servicePrincipalName service principal name @param mechanisms gssapi mechanism @throws IOException if socket error @throws SQLException in any Exception occur
[ "Process", "default", "GSS", "plugin", "authentication", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/authentication/gssapi/StandardGssapiAuthentication.java#L89-L172
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/SendHandshakeResponsePacket.java
SendHandshakeResponsePacket.send
public static void send(final PacketOutputStream pos, final String username, final String password, final HostAddress currentHost, final String database, final long clientCapabilities, final long serverCapabilities, final byte serverLanguage, final byte packetSeq, final Options options, final ReadInitialHandShakePacket greetingPacket) throws IOException { pos.startPacket(packetSeq); final byte[] authData; switch (greetingPacket.getPluginName()) { case "": //CONJ-274 : permit connection mysql 5.1 db case DefaultAuthenticationProvider.MYSQL_NATIVE_PASSWORD: pos.permitTrace(false); try { authData = Utils.encryptPassword(password, greetingPacket.getSeed(), options.passwordCharacterEncoding); break; } catch (NoSuchAlgorithmException e) { //cannot occur : throw new IOException("Unknown algorithm SHA-1. Cannot encrypt password", e); } case DefaultAuthenticationProvider.MYSQL_CLEAR_PASSWORD: pos.permitTrace(false); if (options.passwordCharacterEncoding != null && !options.passwordCharacterEncoding .isEmpty()) { authData = password.getBytes(options.passwordCharacterEncoding); } else { authData = password.getBytes(); } break; default: authData = new byte[0]; } pos.writeInt((int) clientCapabilities); pos.writeInt(1024 * 1024 * 1024); pos.write(serverLanguage); //1 pos.writeBytes((byte) 0, 19); //19 pos.writeInt((int) (clientCapabilities >> 32)); //Maria extended flag if (username == null || username.isEmpty()) { pos.write(System.getProperty("user.name").getBytes()); //to permit SSO } else { pos.write(username.getBytes()); //strlen username } pos.write((byte) 0); //1 if ((serverCapabilities & MariaDbServerCapabilities.PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0) { pos.writeFieldLength(authData.length); pos.write(authData); } else if ((serverCapabilities & MariaDbServerCapabilities.SECURE_CONNECTION) != 0) { pos.write((byte) authData.length); pos.write(authData); } else { pos.write(authData); pos.write((byte) 0); } if ((serverCapabilities & MariaDbServerCapabilities.CONNECT_WITH_DB) != 0) { pos.write(database); pos.write((byte) 0); } if ((serverCapabilities & MariaDbServerCapabilities.PLUGIN_AUTH) != 0) { pos.write(greetingPacket.getPluginName()); pos.write((byte) 0); } if ((serverCapabilities & MariaDbServerCapabilities.CONNECT_ATTRS) != 0) { writeConnectAttributes(pos, options.connectionAttributes, currentHost); } pos.flush(); pos.permitTrace(true); }
java
public static void send(final PacketOutputStream pos, final String username, final String password, final HostAddress currentHost, final String database, final long clientCapabilities, final long serverCapabilities, final byte serverLanguage, final byte packetSeq, final Options options, final ReadInitialHandShakePacket greetingPacket) throws IOException { pos.startPacket(packetSeq); final byte[] authData; switch (greetingPacket.getPluginName()) { case "": //CONJ-274 : permit connection mysql 5.1 db case DefaultAuthenticationProvider.MYSQL_NATIVE_PASSWORD: pos.permitTrace(false); try { authData = Utils.encryptPassword(password, greetingPacket.getSeed(), options.passwordCharacterEncoding); break; } catch (NoSuchAlgorithmException e) { //cannot occur : throw new IOException("Unknown algorithm SHA-1. Cannot encrypt password", e); } case DefaultAuthenticationProvider.MYSQL_CLEAR_PASSWORD: pos.permitTrace(false); if (options.passwordCharacterEncoding != null && !options.passwordCharacterEncoding .isEmpty()) { authData = password.getBytes(options.passwordCharacterEncoding); } else { authData = password.getBytes(); } break; default: authData = new byte[0]; } pos.writeInt((int) clientCapabilities); pos.writeInt(1024 * 1024 * 1024); pos.write(serverLanguage); //1 pos.writeBytes((byte) 0, 19); //19 pos.writeInt((int) (clientCapabilities >> 32)); //Maria extended flag if (username == null || username.isEmpty()) { pos.write(System.getProperty("user.name").getBytes()); //to permit SSO } else { pos.write(username.getBytes()); //strlen username } pos.write((byte) 0); //1 if ((serverCapabilities & MariaDbServerCapabilities.PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0) { pos.writeFieldLength(authData.length); pos.write(authData); } else if ((serverCapabilities & MariaDbServerCapabilities.SECURE_CONNECTION) != 0) { pos.write((byte) authData.length); pos.write(authData); } else { pos.write(authData); pos.write((byte) 0); } if ((serverCapabilities & MariaDbServerCapabilities.CONNECT_WITH_DB) != 0) { pos.write(database); pos.write((byte) 0); } if ((serverCapabilities & MariaDbServerCapabilities.PLUGIN_AUTH) != 0) { pos.write(greetingPacket.getPluginName()); pos.write((byte) 0); } if ((serverCapabilities & MariaDbServerCapabilities.CONNECT_ATTRS) != 0) { writeConnectAttributes(pos, options.connectionAttributes, currentHost); } pos.flush(); pos.permitTrace(true); }
[ "public", "static", "void", "send", "(", "final", "PacketOutputStream", "pos", ",", "final", "String", "username", ",", "final", "String", "password", ",", "final", "HostAddress", "currentHost", ",", "final", "String", "database", ",", "final", "long", "clientCa...
Send handshake response packet. @param pos output stream @param username user name @param password password @param currentHost current hostname @param database database name @param clientCapabilities client capabilities @param serverCapabilities server capabilities @param serverLanguage server language (utf8 / utf8mb4 collation) @param packetSeq packet sequence @param options user options @param greetingPacket server handshake packet information @throws IOException if socket exception occur @see <a href="https://mariadb.com/kb/en/mariadb/1-connecting-connecting/#handshake-response-packet">protocol documentation</a>
[ "Send", "handshake", "response", "packet", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/SendHandshakeResponsePacket.java#L105-L187
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/HostAddress.java
HostAddress.parse
public static List<HostAddress> parse(String spec, HaMode haMode) { if (spec == null) { throw new IllegalArgumentException("Invalid connection URL, host address must not be empty "); } if ("".equals(spec)) { return new ArrayList<>(0); } String[] tokens = spec.trim().split(","); int size = tokens.length; List<HostAddress> arr = new ArrayList<>(size); // Aurora using cluster end point mustn't have any other host if (haMode == HaMode.AURORA) { Pattern clusterPattern = Pattern .compile("(.+)\\.cluster-([a-z0-9]+\\.[a-z0-9\\-]+\\.rds\\.amazonaws\\.com)", Pattern.CASE_INSENSITIVE); Matcher matcher = clusterPattern.matcher(spec); if (!matcher.find()) { logger.warn("Aurora recommended connection URL must only use cluster end-point like " + "\"jdbc:mariadb:aurora://xx.cluster-yy.zz.rds.amazonaws.com\". " + "Using end-point permit auto-discovery of new replicas"); } } for (String token : tokens) { if (token.startsWith("address=")) { arr.add(parseParameterHostAddress(token)); } else { arr.add(parseSimpleHostAddress(token)); } } if (haMode == HaMode.REPLICATION) { for (int i = 0; i < size; i++) { if (i == 0 && arr.get(i).type == null) { arr.get(i).type = ParameterConstant.TYPE_MASTER; } else if (i != 0 && arr.get(i).type == null) { arr.get(i).type = ParameterConstant.TYPE_SLAVE; } } } return arr; }
java
public static List<HostAddress> parse(String spec, HaMode haMode) { if (spec == null) { throw new IllegalArgumentException("Invalid connection URL, host address must not be empty "); } if ("".equals(spec)) { return new ArrayList<>(0); } String[] tokens = spec.trim().split(","); int size = tokens.length; List<HostAddress> arr = new ArrayList<>(size); // Aurora using cluster end point mustn't have any other host if (haMode == HaMode.AURORA) { Pattern clusterPattern = Pattern .compile("(.+)\\.cluster-([a-z0-9]+\\.[a-z0-9\\-]+\\.rds\\.amazonaws\\.com)", Pattern.CASE_INSENSITIVE); Matcher matcher = clusterPattern.matcher(spec); if (!matcher.find()) { logger.warn("Aurora recommended connection URL must only use cluster end-point like " + "\"jdbc:mariadb:aurora://xx.cluster-yy.zz.rds.amazonaws.com\". " + "Using end-point permit auto-discovery of new replicas"); } } for (String token : tokens) { if (token.startsWith("address=")) { arr.add(parseParameterHostAddress(token)); } else { arr.add(parseSimpleHostAddress(token)); } } if (haMode == HaMode.REPLICATION) { for (int i = 0; i < size; i++) { if (i == 0 && arr.get(i).type == null) { arr.get(i).type = ParameterConstant.TYPE_MASTER; } else if (i != 0 && arr.get(i).type == null) { arr.get(i).type = ParameterConstant.TYPE_SLAVE; } } } return arr; }
[ "public", "static", "List", "<", "HostAddress", ">", "parse", "(", "String", "spec", ",", "HaMode", "haMode", ")", "{", "if", "(", "spec", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid connection URL, host address must not be ...
parse - parse server addresses from the URL fragment. @param spec list of endpoints in one of the forms 1 - host1,....,hostN:port (missing port default to MariaDB default 3306 2 - host:port,...,host:port @param haMode High availability mode @return parsed endpoints
[ "parse", "-", "parse", "server", "addresses", "from", "the", "URL", "fragment", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/HostAddress.java#L109-L152
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DateParameter.java
DateParameter.writeTo
public void writeTo(final PacketOutputStream os) throws IOException { os.write(QUOTE); os.write(dateByteFormat()); os.write(QUOTE); }
java
public void writeTo(final PacketOutputStream os) throws IOException { os.write(QUOTE); os.write(dateByteFormat()); os.write(QUOTE); }
[ "public", "void", "writeTo", "(", "final", "PacketOutputStream", "os", ")", "throws", "IOException", "{", "os", ".", "write", "(", "QUOTE", ")", ";", "os", ".", "write", "(", "dateByteFormat", "(", ")", ")", ";", "os", ".", "write", "(", "QUOTE", ")", ...
Write to server OutputStream in text protocol. @param os output buffer
[ "Write", "to", "server", "OutputStream", "in", "text", "protocol", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/parameters/DateParameter.java#L89-L93
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java
ComStmtPrepare.read
public ServerPrepareResult read(PacketInputStream reader, boolean eofDeprecated) throws IOException, SQLException { Buffer buffer = reader.getPacket(true); byte firstByte = buffer.getByteAt(buffer.position); if (firstByte == ERROR) { throw buildErrorException(buffer); } if (firstByte == OK) { /* Prepared Statement OK */ buffer.readByte(); /* skip field count */ final int statementId = buffer.readInt(); final int numColumns = buffer.readShort() & 0xffff; final int numParams = buffer.readShort() & 0xffff; ColumnInformation[] params = new ColumnInformation[numParams]; ColumnInformation[] columns = new ColumnInformation[numColumns]; if (numParams > 0) { for (int i = 0; i < numParams; i++) { params[i] = new ColumnInformation(reader.getPacket(false)); } if (numColumns > 0) { if (!eofDeprecated) { protocol.skipEofPacket(); } for (int i = 0; i < numColumns; i++) { columns[i] = new ColumnInformation(reader.getPacket(false)); } } if (!eofDeprecated) { protocol.readEofPacket(); } } else { if (numColumns > 0) { for (int i = 0; i < numColumns; i++) { columns[i] = new ColumnInformation(reader.getPacket(false)); } if (!eofDeprecated) { protocol.readEofPacket(); } } else { //read warning only if no param / columns, because will be overwritten by EOF warning data buffer.readByte(); // reserved protocol.setHasWarnings(buffer.readShort() > 0); } } ServerPrepareResult serverPrepareResult = new ServerPrepareResult(sql, statementId, columns, params, protocol); if (protocol.getOptions().cachePrepStmts && protocol.getOptions().useServerPrepStmts && sql != null && sql.length() < protocol.getOptions().prepStmtCacheSqlLimit) { String key = protocol.getDatabase() + "-" + sql; ServerPrepareResult cachedServerPrepareResult = protocol .addPrepareInCache(key, serverPrepareResult); return cachedServerPrepareResult != null ? cachedServerPrepareResult : serverPrepareResult; } return serverPrepareResult; } else { throw new SQLException("Unexpected packet returned by server, first byte " + firstByte); } }
java
public ServerPrepareResult read(PacketInputStream reader, boolean eofDeprecated) throws IOException, SQLException { Buffer buffer = reader.getPacket(true); byte firstByte = buffer.getByteAt(buffer.position); if (firstByte == ERROR) { throw buildErrorException(buffer); } if (firstByte == OK) { /* Prepared Statement OK */ buffer.readByte(); /* skip field count */ final int statementId = buffer.readInt(); final int numColumns = buffer.readShort() & 0xffff; final int numParams = buffer.readShort() & 0xffff; ColumnInformation[] params = new ColumnInformation[numParams]; ColumnInformation[] columns = new ColumnInformation[numColumns]; if (numParams > 0) { for (int i = 0; i < numParams; i++) { params[i] = new ColumnInformation(reader.getPacket(false)); } if (numColumns > 0) { if (!eofDeprecated) { protocol.skipEofPacket(); } for (int i = 0; i < numColumns; i++) { columns[i] = new ColumnInformation(reader.getPacket(false)); } } if (!eofDeprecated) { protocol.readEofPacket(); } } else { if (numColumns > 0) { for (int i = 0; i < numColumns; i++) { columns[i] = new ColumnInformation(reader.getPacket(false)); } if (!eofDeprecated) { protocol.readEofPacket(); } } else { //read warning only if no param / columns, because will be overwritten by EOF warning data buffer.readByte(); // reserved protocol.setHasWarnings(buffer.readShort() > 0); } } ServerPrepareResult serverPrepareResult = new ServerPrepareResult(sql, statementId, columns, params, protocol); if (protocol.getOptions().cachePrepStmts && protocol.getOptions().useServerPrepStmts && sql != null && sql.length() < protocol.getOptions().prepStmtCacheSqlLimit) { String key = protocol.getDatabase() + "-" + sql; ServerPrepareResult cachedServerPrepareResult = protocol .addPrepareInCache(key, serverPrepareResult); return cachedServerPrepareResult != null ? cachedServerPrepareResult : serverPrepareResult; } return serverPrepareResult; } else { throw new SQLException("Unexpected packet returned by server, first byte " + firstByte); } }
[ "public", "ServerPrepareResult", "read", "(", "PacketInputStream", "reader", ",", "boolean", "eofDeprecated", ")", "throws", "IOException", ",", "SQLException", "{", "Buffer", "buffer", "=", "reader", ".", "getPacket", "(", "true", ")", ";", "byte", "firstByte", ...
Read COM_PREPARE_RESULT. @param reader inputStream @param eofDeprecated are EOF_packet deprecated @return ServerPrepareResult prepare result @throws IOException if connection has error @throws SQLException if server answer with error.
[ "Read", "COM_PREPARE_RESULT", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/ComStmtPrepare.java#L101-L168
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/MastersSlavesProtocol.java
MastersSlavesProtocol.resetHostList
private static void resetHostList(MastersSlavesListener listener, Deque<HostAddress> loopAddresses) { //if all servers have been connected without result //add back all servers List<HostAddress> servers = new ArrayList<>(); servers.addAll(listener.getUrlParser().getHostAddresses()); Collections.shuffle(servers); //remove current connected hosts to avoid reconnect them servers.removeAll(listener.connectedHosts()); loopAddresses.clear(); loopAddresses.addAll(servers); }
java
private static void resetHostList(MastersSlavesListener listener, Deque<HostAddress> loopAddresses) { //if all servers have been connected without result //add back all servers List<HostAddress> servers = new ArrayList<>(); servers.addAll(listener.getUrlParser().getHostAddresses()); Collections.shuffle(servers); //remove current connected hosts to avoid reconnect them servers.removeAll(listener.connectedHosts()); loopAddresses.clear(); loopAddresses.addAll(servers); }
[ "private", "static", "void", "resetHostList", "(", "MastersSlavesListener", "listener", ",", "Deque", "<", "HostAddress", ">", "loopAddresses", ")", "{", "//if all servers have been connected without result", "//add back all servers", "List", "<", "HostAddress", ">", "serve...
Reinitialize loopAddresses with all servers in randomize order. @param listener current listener @param loopAddresses the list to reinitialize
[ "Reinitialize", "loopAddresses", "with", "all", "servers", "in", "randomize", "order", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/MastersSlavesProtocol.java#L202-L215
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java
MariaDbPooledConnection.fireStatementClosed
public void fireStatementClosed(Statement st) { if (st instanceof PreparedStatement) { StatementEvent event = new StatementEvent(this, (PreparedStatement) st); for (StatementEventListener listener : statementEventListeners) { listener.statementClosed(event); } } }
java
public void fireStatementClosed(Statement st) { if (st instanceof PreparedStatement) { StatementEvent event = new StatementEvent(this, (PreparedStatement) st); for (StatementEventListener listener : statementEventListeners) { listener.statementClosed(event); } } }
[ "public", "void", "fireStatementClosed", "(", "Statement", "st", ")", "{", "if", "(", "st", "instanceof", "PreparedStatement", ")", "{", "StatementEvent", "event", "=", "new", "StatementEvent", "(", "this", ",", "(", "PreparedStatement", ")", "st", ")", ";", ...
Fire statement close event to listeners. @param st statement
[ "Fire", "statement", "close", "event", "to", "listeners", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java#L189-L196
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java
MariaDbPooledConnection.fireStatementErrorOccured
public void fireStatementErrorOccured(Statement st, SQLException ex) { if (st instanceof PreparedStatement) { StatementEvent event = new StatementEvent(this, (PreparedStatement) st, ex); for (StatementEventListener listener : statementEventListeners) { listener.statementErrorOccurred(event); } } }
java
public void fireStatementErrorOccured(Statement st, SQLException ex) { if (st instanceof PreparedStatement) { StatementEvent event = new StatementEvent(this, (PreparedStatement) st, ex); for (StatementEventListener listener : statementEventListeners) { listener.statementErrorOccurred(event); } } }
[ "public", "void", "fireStatementErrorOccured", "(", "Statement", "st", ",", "SQLException", "ex", ")", "{", "if", "(", "st", "instanceof", "PreparedStatement", ")", "{", "StatementEvent", "event", "=", "new", "StatementEvent", "(", "this", ",", "(", "PreparedSta...
Fire statement error to listeners. @param st statement @param ex exception
[ "Fire", "statement", "error", "to", "listeners", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java#L204-L211
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java
MariaDbPooledConnection.fireConnectionClosed
public void fireConnectionClosed() { ConnectionEvent event = new ConnectionEvent(this); for (ConnectionEventListener listener : connectionEventListeners) { listener.connectionClosed(event); } }
java
public void fireConnectionClosed() { ConnectionEvent event = new ConnectionEvent(this); for (ConnectionEventListener listener : connectionEventListeners) { listener.connectionClosed(event); } }
[ "public", "void", "fireConnectionClosed", "(", ")", "{", "ConnectionEvent", "event", "=", "new", "ConnectionEvent", "(", "this", ")", ";", "for", "(", "ConnectionEventListener", "listener", ":", "connectionEventListeners", ")", "{", "listener", ".", "connectionClose...
Fire Connection close to listening listeners.
[ "Fire", "Connection", "close", "to", "listening", "listeners", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java#L216-L221
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java
MariaDbPooledConnection.fireConnectionErrorOccured
public void fireConnectionErrorOccured(SQLException ex) { ConnectionEvent event = new ConnectionEvent(this, ex); for (ConnectionEventListener listener : connectionEventListeners) { listener.connectionErrorOccurred(event); } }
java
public void fireConnectionErrorOccured(SQLException ex) { ConnectionEvent event = new ConnectionEvent(this, ex); for (ConnectionEventListener listener : connectionEventListeners) { listener.connectionErrorOccurred(event); } }
[ "public", "void", "fireConnectionErrorOccured", "(", "SQLException", "ex", ")", "{", "ConnectionEvent", "event", "=", "new", "ConnectionEvent", "(", "this", ",", "ex", ")", ";", "for", "(", "ConnectionEventListener", "listener", ":", "connectionEventListeners", ")",...
Fire connection error to listening listeners. @param ex exception
[ "Fire", "connection", "error", "to", "listening", "listeners", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbPooledConnection.java#L228-L233
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbStatement.java
MariaDbStatement.setTimerTask
protected void setTimerTask(boolean isBatch) { assert (timerTaskFuture == null); timerTaskFuture = timeoutScheduler.schedule(() -> { try { isTimedout = true; if (!isBatch) { protocol.cancelCurrentQuery(); } protocol.interrupt(); } catch (Throwable e) { //eat } }, queryTimeout, TimeUnit.SECONDS); }
java
protected void setTimerTask(boolean isBatch) { assert (timerTaskFuture == null); timerTaskFuture = timeoutScheduler.schedule(() -> { try { isTimedout = true; if (!isBatch) { protocol.cancelCurrentQuery(); } protocol.interrupt(); } catch (Throwable e) { //eat } }, queryTimeout, TimeUnit.SECONDS); }
[ "protected", "void", "setTimerTask", "(", "boolean", "isBatch", ")", "{", "assert", "(", "timerTaskFuture", "==", "null", ")", ";", "timerTaskFuture", "=", "timeoutScheduler", ".", "schedule", "(", "(", ")", "->", "{", "try", "{", "isTimedout", "=", "true", ...
Part of query prolog - setup timeout timer
[ "Part", "of", "query", "prolog", "-", "setup", "timeout", "timer" ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L160-L174
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbStatement.java
MariaDbStatement.executeExceptionEpilogue
protected SQLException executeExceptionEpilogue(SQLException sqle) { //if has a failover, closing the statement if (sqle.getSQLState() != null && sqle.getSQLState().startsWith("08")) { try { close(); } catch (SQLException sqlee) { //eat exception } } if (isTimedout) { return new SQLTimeoutException("(conn:" + getServerThreadId() + ") Query timed out", "JZ0002", 1317, sqle); } SQLException sqlException = ExceptionMapper .getException(sqle, connection, this, queryTimeout != 0); logger.error("error executing query", sqlException); return sqlException; }
java
protected SQLException executeExceptionEpilogue(SQLException sqle) { //if has a failover, closing the statement if (sqle.getSQLState() != null && sqle.getSQLState().startsWith("08")) { try { close(); } catch (SQLException sqlee) { //eat exception } } if (isTimedout) { return new SQLTimeoutException("(conn:" + getServerThreadId() + ") Query timed out", "JZ0002", 1317, sqle); } SQLException sqlException = ExceptionMapper .getException(sqle, connection, this, queryTimeout != 0); logger.error("error executing query", sqlException); return sqlException; }
[ "protected", "SQLException", "executeExceptionEpilogue", "(", "SQLException", "sqle", ")", "{", "//if has a failover, closing the statement", "if", "(", "sqle", ".", "getSQLState", "(", ")", "!=", "null", "&&", "sqle", ".", "getSQLState", "(", ")", ".", "startsWith"...
Reset timeout after query, re-throw SQL exception. @param sqle current exception @return SQLException exception with new message in case of timer timeout.
[ "Reset", "timeout", "after", "query", "re", "-", "throw", "SQL", "exception", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L223-L241
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbStatement.java
MariaDbStatement.executeLargeUpdate
@Override public long executeLargeUpdate(String sql) throws SQLException { if (executeInternal(sql, fetchSize, Statement.NO_GENERATED_KEYS)) { return 0; } return getLargeUpdateCount(); }
java
@Override public long executeLargeUpdate(String sql) throws SQLException { if (executeInternal(sql, fetchSize, Statement.NO_GENERATED_KEYS)) { return 0; } return getLargeUpdateCount(); }
[ "@", "Override", "public", "long", "executeLargeUpdate", "(", "String", "sql", ")", "throws", "SQLException", "{", "if", "(", "executeInternal", "(", "sql", ",", "fetchSize", ",", "Statement", ".", "NO_GENERATED_KEYS", ")", ")", "{", "return", "0", ";", "}",...
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement. This method should be used when the returned row count may exceed Integer.MAX_VALUE. @param sql sql command @return update counts @throws SQLException if any error occur during execution
[ "Executes", "the", "given", "SQL", "statement", "which", "may", "be", "an", "INSERT", "UPDATE", "or", "DELETE", "statement", "or", "an", "SQL", "statement", "that", "returns", "nothing", "such", "as", "an", "SQL", "DDL", "statement", ".", "This", "method", ...
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L618-L624
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbStatement.java
MariaDbStatement.getUpdateCount
public int getUpdateCount() { if (results != null && results.getCmdInformation() != null && !results.isBatch()) { return results.getCmdInformation().getUpdateCount(); } return -1; }
java
public int getUpdateCount() { if (results != null && results.getCmdInformation() != null && !results.isBatch()) { return results.getCmdInformation().getUpdateCount(); } return -1; }
[ "public", "int", "getUpdateCount", "(", ")", "{", "if", "(", "results", "!=", "null", "&&", "results", ".", "getCmdInformation", "(", ")", "!=", "null", "&&", "!", "results", ".", "isBatch", "(", ")", ")", "{", "return", "results", ".", "getCmdInformatio...
Retrieves the current result as an update count; if the result is a ResultSet object or there are no more results, -1 is returned. This method should be called only once per result. @return the current result as an update count; -1 if the current result is a ResultSet object or there are no more results
[ "Retrieves", "the", "current", "result", "as", "an", "update", "count", ";", "if", "the", "result", "is", "a", "ResultSet", "object", "or", "there", "are", "no", "more", "results", "-", "1", "is", "returned", ".", "This", "method", "should", "be", "calle...
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L1057-L1062
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbStatement.java
MariaDbStatement.getLargeUpdateCount
@Override public long getLargeUpdateCount() { if (results != null && results.getCmdInformation() != null && !results.isBatch()) { return results.getCmdInformation().getLargeUpdateCount(); } return -1; }
java
@Override public long getLargeUpdateCount() { if (results != null && results.getCmdInformation() != null && !results.isBatch()) { return results.getCmdInformation().getLargeUpdateCount(); } return -1; }
[ "@", "Override", "public", "long", "getLargeUpdateCount", "(", ")", "{", "if", "(", "results", "!=", "null", "&&", "results", ".", "getCmdInformation", "(", ")", "!=", "null", "&&", "!", "results", ".", "isBatch", "(", ")", ")", "{", "return", "results",...
Retrieves the current result as an update count; if the result is a ResultSet object or there are no more results, -1 is returned. @return last update count
[ "Retrieves", "the", "current", "result", "as", "an", "update", "count", ";", "if", "the", "result", "is", "a", "ResultSet", "object", "or", "there", "are", "no", "more", "results", "-", "1", "is", "returned", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L1070-L1076
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbStatement.java
MariaDbStatement.internalBatchExecution
private void internalBatchExecution(int size) throws SQLException { executeQueryPrologue(true); results = new Results(this, 0, true, size, false, resultSetScrollType, resultSetConcurrency, Statement.RETURN_GENERATED_KEYS, protocol.getAutoIncrementIncrement()); protocol.executeBatchStmt(protocol.isMasterConnection(), results, batchQueries); results.commandEnd(); }
java
private void internalBatchExecution(int size) throws SQLException { executeQueryPrologue(true); results = new Results(this, 0, true, size, false, resultSetScrollType, resultSetConcurrency, Statement.RETURN_GENERATED_KEYS, protocol.getAutoIncrementIncrement()); protocol.executeBatchStmt(protocol.isMasterConnection(), results, batchQueries); results.commandEnd(); }
[ "private", "void", "internalBatchExecution", "(", "int", "size", ")", "throws", "SQLException", "{", "executeQueryPrologue", "(", "true", ")", ";", "results", "=", "new", "Results", "(", "this", ",", "0", ",", "true", ",", "size", ",", "false", ",", "resul...
Internal batch execution. @param size expected result-set size @throws SQLException throw exception if batch error occur
[ "Internal", "batch", "execution", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L1337-L1351
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/MariaDbStatement.java
MariaDbStatement.checkCloseOnCompletion
public void checkCloseOnCompletion(ResultSet resultSet) throws SQLException { if (mustCloseOnCompletion && !closed && results != null && resultSet.equals(results.getResultSet())) { close(); } }
java
public void checkCloseOnCompletion(ResultSet resultSet) throws SQLException { if (mustCloseOnCompletion && !closed && results != null && resultSet.equals(results.getResultSet())) { close(); } }
[ "public", "void", "checkCloseOnCompletion", "(", "ResultSet", "resultSet", ")", "throws", "SQLException", "{", "if", "(", "mustCloseOnCompletion", "&&", "!", "closed", "&&", "results", "!=", "null", "&&", "resultSet", ".", "equals", "(", "results", ".", "getResu...
Check that close on completion is asked, and close if so. @param resultSet resultSet @throws SQLException if close has error
[ "Check", "that", "close", "on", "completion", "is", "asked", "and", "close", "if", "so", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L1418-L1425
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/CallableFunctionStatement.java
CallableFunctionStatement.initFunctionData
public void initFunctionData(int parametersCount) { params = new CallParameter[parametersCount]; for (int i = 0; i < parametersCount; i++) { params[i] = new CallParameter(); if (i > 0) { params[i].setInput(true); } } // the query was in the form {?=call function()}, so the first parameter is always output params[0].setOutput(true); }
java
public void initFunctionData(int parametersCount) { params = new CallParameter[parametersCount]; for (int i = 0; i < parametersCount; i++) { params[i] = new CallParameter(); if (i > 0) { params[i].setInput(true); } } // the query was in the form {?=call function()}, so the first parameter is always output params[0].setOutput(true); }
[ "public", "void", "initFunctionData", "(", "int", "parametersCount", ")", "{", "params", "=", "new", "CallParameter", "[", "parametersCount", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parametersCount", ";", "i", "++", ")", "{", "params"...
Data initialisation when parameterCount is defined. @param parametersCount number of parameters
[ "Data", "initialisation", "when", "parameterCount", "is", "defined", "." ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/CallableFunctionStatement.java#L131-L141
train
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/ServerSidePreparedStatement.java
ServerSidePreparedStatement.executeQueryPrologue
private void executeQueryPrologue(ServerPrepareResult serverPrepareResult) throws SQLException { executing = true; if (closed) { throw new SQLException("execute() is called on closed statement"); } protocol .prologProxy(serverPrepareResult, maxRows, protocol.getProxy() != null, connection, this); }
java
private void executeQueryPrologue(ServerPrepareResult serverPrepareResult) throws SQLException { executing = true; if (closed) { throw new SQLException("execute() is called on closed statement"); } protocol .prologProxy(serverPrepareResult, maxRows, protocol.getProxy() != null, connection, this); }
[ "private", "void", "executeQueryPrologue", "(", "ServerPrepareResult", "serverPrepareResult", ")", "throws", "SQLException", "{", "executing", "=", "true", ";", "if", "(", "closed", ")", "{", "throw", "new", "SQLException", "(", "\"execute() is called on closed statemen...
must have "lock" locked before invoking
[ "must", "have", "lock", "locked", "before", "invoking" ]
d148c7cd347c4680617be65d9e511b289d38a30b
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/ServerSidePreparedStatement.java#L351-L359
train
intel-iot-devkit/upm
examples/java/GroveQTouch_Example.java
GroveQTouch_Example.printButtons
public static void printButtons(int buttonNumber){ boolean buttonPressed = false; System.out.print("Button Pressed: "); for(int i=0;i<7;i++){ if((buttonNumber & (1<<i)) != 0){ System.out.println(i+" "); buttonPressed = true; } } if(!buttonPressed){ System.out.println("None "); } }
java
public static void printButtons(int buttonNumber){ boolean buttonPressed = false; System.out.print("Button Pressed: "); for(int i=0;i<7;i++){ if((buttonNumber & (1<<i)) != 0){ System.out.println(i+" "); buttonPressed = true; } } if(!buttonPressed){ System.out.println("None "); } }
[ "public", "static", "void", "printButtons", "(", "int", "buttonNumber", ")", "{", "boolean", "buttonPressed", "=", "false", ";", "System", ".", "out", ".", "print", "(", "\"Button Pressed: \"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", ...
This function prints out the button numbers from 0 through 6 @param buttonNumber
[ "This", "function", "prints", "out", "the", "button", "numbers", "from", "0", "through", "6" ]
2c7fff24c7c5647ef50a65d5aff587de0c5b8b2f
https://github.com/intel-iot-devkit/upm/blob/2c7fff24c7c5647ef50a65d5aff587de0c5b8b2f/examples/java/GroveQTouch_Example.java#L53-L68
train
rapidoid/rapidoid
rapidoid-jpa/src/main/java/org/rapidoid/jpa/JPA.java
JPA.transaction
public static void transaction(Runnable action, boolean readOnly) { Ctx ctx = Ctxs.get(); boolean newContext = ctx == null; if (newContext) { ctx = Ctxs.open("transaction"); } try { EntityManager em = ctx.persister(); JPA.with(em).transactional(action, readOnly); } finally { if (newContext) { Ctxs.close(); } } }
java
public static void transaction(Runnable action, boolean readOnly) { Ctx ctx = Ctxs.get(); boolean newContext = ctx == null; if (newContext) { ctx = Ctxs.open("transaction"); } try { EntityManager em = ctx.persister(); JPA.with(em).transactional(action, readOnly); } finally { if (newContext) { Ctxs.close(); } } }
[ "public", "static", "void", "transaction", "(", "Runnable", "action", ",", "boolean", "readOnly", ")", "{", "Ctx", "ctx", "=", "Ctxs", ".", "get", "(", ")", ";", "boolean", "newContext", "=", "ctx", "==", "null", ";", "if", "(", "newContext", ")", "{",...
FIXME replace Runnable with Executable
[ "FIXME", "replace", "Runnable", "with", "Executable" ]
1775344bcf4abbee289d474b34d553ff6bc821b0
https://github.com/rapidoid/rapidoid/blob/1775344bcf4abbee289d474b34d553ff6bc821b0/rapidoid-jpa/src/main/java/org/rapidoid/jpa/JPA.java#L210-L227
train
rapidoid/rapidoid
rapidoid-rest/src/main/java/org/rapidoid/setup/App.java
App.run
public static synchronized void run(String[] args, String... extraArgs) { AppStarter.startUp(args, extraArgs); // no implicit classpath scanning here boot(); // finish initialization and start the application onAppReady(); boot(); }
java
public static synchronized void run(String[] args, String... extraArgs) { AppStarter.startUp(args, extraArgs); // no implicit classpath scanning here boot(); // finish initialization and start the application onAppReady(); boot(); }
[ "public", "static", "synchronized", "void", "run", "(", "String", "[", "]", "args", ",", "String", "...", "extraArgs", ")", "{", "AppStarter", ".", "startUp", "(", "args", ",", "extraArgs", ")", ";", "// no implicit classpath scanning here", "boot", "(", ")", ...
Initializes the app in non-atomic way. Then starts serving requests immediately when routes are configured.
[ "Initializes", "the", "app", "in", "non", "-", "atomic", "way", ".", "Then", "starts", "serving", "requests", "immediately", "when", "routes", "are", "configured", "." ]
1775344bcf4abbee289d474b34d553ff6bc821b0
https://github.com/rapidoid/rapidoid/blob/1775344bcf4abbee289d474b34d553ff6bc821b0/rapidoid-rest/src/main/java/org/rapidoid/setup/App.java#L90-L100
train
rapidoid/rapidoid
rapidoid-rest/src/main/java/org/rapidoid/setup/App.java
App.bootstrap
public static synchronized void bootstrap(String[] args, String... extraArgs) { AppStarter.startUp(args, extraArgs); boot(); App.scan(); // scan classpath for beans // finish initialization and start the application onAppReady(); boot(); }
java
public static synchronized void bootstrap(String[] args, String... extraArgs) { AppStarter.startUp(args, extraArgs); boot(); App.scan(); // scan classpath for beans // finish initialization and start the application onAppReady(); boot(); }
[ "public", "static", "synchronized", "void", "bootstrap", "(", "String", "[", "]", "args", ",", "String", "...", "extraArgs", ")", "{", "AppStarter", ".", "startUp", "(", "args", ",", "extraArgs", ")", ";", "boot", "(", ")", ";", "App", ".", "scan", "("...
Initializes the app in non-atomic way. Then scans the classpath for beans. Then starts serving requests immediately when routes are configured.
[ "Initializes", "the", "app", "in", "non", "-", "atomic", "way", ".", "Then", "scans", "the", "classpath", "for", "beans", ".", "Then", "starts", "serving", "requests", "immediately", "when", "routes", "are", "configured", "." ]
1775344bcf4abbee289d474b34d553ff6bc821b0
https://github.com/rapidoid/rapidoid/blob/1775344bcf4abbee289d474b34d553ff6bc821b0/rapidoid-rest/src/main/java/org/rapidoid/setup/App.java#L107-L118
train
rapidoid/rapidoid
rapidoid-commons/src/main/java/org/rapidoid/cache/impl/ConcurrentCacheAtom.java
ConcurrentCacheAtom.setValueInsideWriteLock
private V setValueInsideWriteLock(V newValue) { CachedValue<V> cached = cachedValue; // read the cached value V oldValue = cached != null ? cached.value : null; if (newValue != null) { long expiresAt = ttlInMs > 0 ? U.time() + ttlInMs : Long.MAX_VALUE; cachedValue = new CachedValue<>(newValue, expiresAt); } else { cachedValue = null; } return oldValue; }
java
private V setValueInsideWriteLock(V newValue) { CachedValue<V> cached = cachedValue; // read the cached value V oldValue = cached != null ? cached.value : null; if (newValue != null) { long expiresAt = ttlInMs > 0 ? U.time() + ttlInMs : Long.MAX_VALUE; cachedValue = new CachedValue<>(newValue, expiresAt); } else { cachedValue = null; } return oldValue; }
[ "private", "V", "setValueInsideWriteLock", "(", "V", "newValue", ")", "{", "CachedValue", "<", "V", ">", "cached", "=", "cachedValue", ";", "// read the cached value", "V", "oldValue", "=", "cached", "!=", "null", "?", "cached", ".", "value", ":", "null", ";...
Sets new cached value, executes inside already acquired write lock.
[ "Sets", "new", "cached", "value", "executes", "inside", "already", "acquired", "write", "lock", "." ]
1775344bcf4abbee289d474b34d553ff6bc821b0
https://github.com/rapidoid/rapidoid/blob/1775344bcf4abbee289d474b34d553ff6bc821b0/rapidoid-commons/src/main/java/org/rapidoid/cache/impl/ConcurrentCacheAtom.java#L215-L228
train
lviggiano/owner
owner/src/main/java/org/aeonbits/owner/ConfigFactory.java
ConfigFactory.newInstance
public static Factory newInstance() { ScheduledExecutorService scheduler = newSingleThreadScheduledExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { Thread result = new Thread(r); result.setDaemon(true); return result; } }); Properties props = new Properties(); return new DefaultFactory(scheduler, props); }
java
public static Factory newInstance() { ScheduledExecutorService scheduler = newSingleThreadScheduledExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { Thread result = new Thread(r); result.setDaemon(true); return result; } }); Properties props = new Properties(); return new DefaultFactory(scheduler, props); }
[ "public", "static", "Factory", "newInstance", "(", ")", "{", "ScheduledExecutorService", "scheduler", "=", "newSingleThreadScheduledExecutor", "(", "new", "ThreadFactory", "(", ")", "{", "public", "Thread", "newThread", "(", "Runnable", "r", ")", "{", "Thread", "r...
Returns a new instance of a config Factory object. @return a new instance of a config Factory object.
[ "Returns", "a", "new", "instance", "of", "a", "config", "Factory", "object", "." ]
1223ecfbe3c275b3b7c5ec13e9238c9bb888754f
https://github.com/lviggiano/owner/blob/1223ecfbe3c275b3b7c5ec13e9238c9bb888754f/owner/src/main/java/org/aeonbits/owner/ConfigFactory.java#L45-L55
train
lviggiano/owner
owner/src/main/java/org/aeonbits/owner/ConfigCache.java
ConfigCache.remove
@SuppressWarnings("unchecked") public static <T extends Config> T remove(Object key) { return (T) CACHE.remove(key); }
java
@SuppressWarnings("unchecked") public static <T extends Config> T remove(Object key) { return (T) CACHE.remove(key); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", "extends", "Config", ">", "T", "remove", "(", "Object", "key", ")", "{", "return", "(", "T", ")", "CACHE", ".", "remove", "(", "key", ")", ";", "}" ]
Removes the cached instance for the given key if it is present. <p>Returns previous instance associated to the given key in the cache, or <code>null</code> if the cache contained no instance for the given key. <p>The cache will not contain the instance for the specified key once the call returns. @param <T> type of the interface. @param key key whose instance is to be removed from the cache. @return the previous instance associated with <code>key</code>, or <code>null</code> if there was no instance for <code>key</code>.
[ "Removes", "the", "cached", "instance", "for", "the", "given", "key", "if", "it", "is", "present", "." ]
1223ecfbe3c275b3b7c5ec13e9238c9bb888754f
https://github.com/lviggiano/owner/blob/1223ecfbe3c275b3b7c5ec13e9238c9bb888754f/owner/src/main/java/org/aeonbits/owner/ConfigCache.java#L155-L158
train
lviggiano/owner
owner-creator-maven-plugin/src/main/java/org/aeonbits/owner/creator/PropertiesFileCreator.java
PropertiesFileCreator.parse
public void parse(Class clazz, PrintWriter output, String headerName, String projectName) throws Exception { long startTime = System.currentTimeMillis(); Group[] groups = parseMethods(clazz); long finishTime = System.currentTimeMillis(); lastExecutionTime = finishTime - startTime; String result = toPropertiesString(groups, headerName, projectName); writeProperties(output, result); }
java
public void parse(Class clazz, PrintWriter output, String headerName, String projectName) throws Exception { long startTime = System.currentTimeMillis(); Group[] groups = parseMethods(clazz); long finishTime = System.currentTimeMillis(); lastExecutionTime = finishTime - startTime; String result = toPropertiesString(groups, headerName, projectName); writeProperties(output, result); }
[ "public", "void", "parse", "(", "Class", "clazz", ",", "PrintWriter", "output", ",", "String", "headerName", ",", "String", "projectName", ")", "throws", "Exception", "{", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "Group", ...
Method to parse the class and write file in the choosen output. @param clazz class to parse @param output output file path @param headerName @param projectName
[ "Method", "to", "parse", "the", "class", "and", "write", "file", "in", "the", "choosen", "output", "." ]
1223ecfbe3c275b3b7c5ec13e9238c9bb888754f
https://github.com/lviggiano/owner/blob/1223ecfbe3c275b3b7c5ec13e9238c9bb888754f/owner-creator-maven-plugin/src/main/java/org/aeonbits/owner/creator/PropertiesFileCreator.java#L46-L57
train
lviggiano/owner
owner-creator-maven-plugin/src/main/java/org/aeonbits/owner/creator/PropertiesFileCreator.java
PropertiesFileCreator.parseMethods
private Group[] parseMethods(Class clazz) { List<Group> groups = new ArrayList(); Group unknownGroup = new Group(); groups.add(unknownGroup); String[] groupsOrder = new String[0]; for (Method method : clazz.getMethods()) { Property prop = new Property(); prop.deprecated = method.isAnnotationPresent(Deprecated.class); if (method.isAnnotationPresent(Key.class)) { Key val = method.getAnnotation(Key.class); prop.name = val.value(); } else { prop.name = method.getName(); } if (method.isAnnotationPresent(DefaultValue.class)) { DefaultValue val = method.getAnnotation(DefaultValue.class); prop.defaultValue = val.value(); } unknownGroup.properties.add(prop); } return orderGroup(groups, groupsOrder); }
java
private Group[] parseMethods(Class clazz) { List<Group> groups = new ArrayList(); Group unknownGroup = new Group(); groups.add(unknownGroup); String[] groupsOrder = new String[0]; for (Method method : clazz.getMethods()) { Property prop = new Property(); prop.deprecated = method.isAnnotationPresent(Deprecated.class); if (method.isAnnotationPresent(Key.class)) { Key val = method.getAnnotation(Key.class); prop.name = val.value(); } else { prop.name = method.getName(); } if (method.isAnnotationPresent(DefaultValue.class)) { DefaultValue val = method.getAnnotation(DefaultValue.class); prop.defaultValue = val.value(); } unknownGroup.properties.add(prop); } return orderGroup(groups, groupsOrder); }
[ "private", "Group", "[", "]", "parseMethods", "(", "Class", "clazz", ")", "{", "List", "<", "Group", ">", "groups", "=", "new", "ArrayList", "(", ")", ";", "Group", "unknownGroup", "=", "new", "Group", "(", ")", ";", "groups", ".", "add", "(", "unkno...
Method to get group array with subgroups and properties. @param clazz class to parse @return array of groups
[ "Method", "to", "get", "group", "array", "with", "subgroups", "and", "properties", "." ]
1223ecfbe3c275b3b7c5ec13e9238c9bb888754f
https://github.com/lviggiano/owner/blob/1223ecfbe3c275b3b7c5ec13e9238c9bb888754f/owner-creator-maven-plugin/src/main/java/org/aeonbits/owner/creator/PropertiesFileCreator.java#L65-L92
train
lviggiano/owner
owner-creator-maven-plugin/src/main/java/org/aeonbits/owner/creator/PropertiesFileCreator.java
PropertiesFileCreator.orderGroup
private Group[] orderGroup(List<Group> groups, String[] groupsOrder) { LinkedList<Group> groupsOrdered = new LinkedList(); List<Group> remained = new ArrayList(groups); for (String order : groupsOrder) { for (Group remain : remained) { if (remain.title.equals(order)) { groupsOrdered.add(remain); remained.remove(remain); break; } } } groupsOrdered.addAll(remained); return groupsOrdered.toArray(new Group[groupsOrdered.size()]); }
java
private Group[] orderGroup(List<Group> groups, String[] groupsOrder) { LinkedList<Group> groupsOrdered = new LinkedList(); List<Group> remained = new ArrayList(groups); for (String order : groupsOrder) { for (Group remain : remained) { if (remain.title.equals(order)) { groupsOrdered.add(remain); remained.remove(remain); break; } } } groupsOrdered.addAll(remained); return groupsOrdered.toArray(new Group[groupsOrdered.size()]); }
[ "private", "Group", "[", "]", "orderGroup", "(", "List", "<", "Group", ">", "groups", ",", "String", "[", "]", "groupsOrder", ")", "{", "LinkedList", "<", "Group", ">", "groupsOrdered", "=", "new", "LinkedList", "(", ")", ";", "List", "<", "Group", ">"...
Order groups based on passed order. @param groups groups to order @param groupsOrder order to follow @return ordered groups
[ "Order", "groups", "based", "on", "passed", "order", "." ]
1223ecfbe3c275b3b7c5ec13e9238c9bb888754f
https://github.com/lviggiano/owner/blob/1223ecfbe3c275b3b7c5ec13e9238c9bb888754f/owner-creator-maven-plugin/src/main/java/org/aeonbits/owner/creator/PropertiesFileCreator.java#L102-L120
train
lviggiano/owner
owner-creator-maven-plugin/src/main/java/org/aeonbits/owner/creator/PropertiesFileCreator.java
PropertiesFileCreator.toPropertiesString
private String toPropertiesString(Group[] groups, String headerName, String projectName) { StringBuilder result = new StringBuilder(); result.append(format(header, headerName, projectName)); for (Group group : groups) { result.append(group.toString()); } result.append(generateFileFooter()); return result.toString(); }
java
private String toPropertiesString(Group[] groups, String headerName, String projectName) { StringBuilder result = new StringBuilder(); result.append(format(header, headerName, projectName)); for (Group group : groups) { result.append(group.toString()); } result.append(generateFileFooter()); return result.toString(); }
[ "private", "String", "toPropertiesString", "(", "Group", "[", "]", "groups", ",", "String", "headerName", ",", "String", "projectName", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "result", ".", "append", "(", "format", "...
Convert groups list into string.
[ "Convert", "groups", "list", "into", "string", "." ]
1223ecfbe3c275b3b7c5ec13e9238c9bb888754f
https://github.com/lviggiano/owner/blob/1223ecfbe3c275b3b7c5ec13e9238c9bb888754f/owner-creator-maven-plugin/src/main/java/org/aeonbits/owner/creator/PropertiesFileCreator.java#L125-L137
train
lviggiano/owner
owner-java8-extras/src/main/java/org/aeonbits/owner/util/bytesize/ByteSize.java
ByteSize.getBytes
public BigInteger getBytes(){ return value.multiply(unit.getFactor()).setScale(0, RoundingMode.CEILING).toBigIntegerExact(); }
java
public BigInteger getBytes(){ return value.multiply(unit.getFactor()).setScale(0, RoundingMode.CEILING).toBigIntegerExact(); }
[ "public", "BigInteger", "getBytes", "(", ")", "{", "return", "value", ".", "multiply", "(", "unit", ".", "getFactor", "(", ")", ")", ".", "setScale", "(", "0", ",", "RoundingMode", ".", "CEILING", ")", ".", "toBigIntegerExact", "(", ")", ";", "}" ]
Returns the number of bytes that this byte size represents after multiplying the unit factor with the value. Since the value part can be a represented by a decimal, there is some possibility of a rounding error. Therefore, the result of multiplying the value and the unit factor are always rounded towards positive infinity to the nearest integer value (see {@link RoundingMode#CEILING}) to make sure that this method never gives values that are too small. @return number of bytes this byte size represents after factoring in the unit.
[ "Returns", "the", "number", "of", "bytes", "that", "this", "byte", "size", "represents", "after", "multiplying", "the", "unit", "factor", "with", "the", "value", "." ]
1223ecfbe3c275b3b7c5ec13e9238c9bb888754f
https://github.com/lviggiano/owner/blob/1223ecfbe3c275b3b7c5ec13e9238c9bb888754f/owner-java8-extras/src/main/java/org/aeonbits/owner/util/bytesize/ByteSize.java#L91-L93
train
lviggiano/owner
owner/src/main/java/org/aeonbits/owner/StrSubstitutor.java
StrSubstitutor.replace
String replace(String source) { if (source == null) return null; Matcher m = PATTERN.matcher(source); StringBuffer sb = new StringBuffer(); while (m.find()) { String var = m.group(1); String value = values.getProperty(var); String replacement = (value != null) ? replace(value) : ""; m.appendReplacement(sb, Matcher.quoteReplacement(replacement)); } m.appendTail(sb); return sb.toString(); }
java
String replace(String source) { if (source == null) return null; Matcher m = PATTERN.matcher(source); StringBuffer sb = new StringBuffer(); while (m.find()) { String var = m.group(1); String value = values.getProperty(var); String replacement = (value != null) ? replace(value) : ""; m.appendReplacement(sb, Matcher.quoteReplacement(replacement)); } m.appendTail(sb); return sb.toString(); }
[ "String", "replace", "(", "String", "source", ")", "{", "if", "(", "source", "==", "null", ")", "return", "null", ";", "Matcher", "m", "=", "PATTERN", ".", "matcher", "(", "source", ")", ";", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ...
Replaces all the occurrences of variables with their matching values from the resolver using the given source string as a template. @param source the string to replace in, null returns null @return the result of the replace operation
[ "Replaces", "all", "the", "occurrences", "of", "variables", "with", "their", "matching", "values", "from", "the", "resolver", "using", "the", "given", "source", "string", "as", "a", "template", "." ]
1223ecfbe3c275b3b7c5ec13e9238c9bb888754f
https://github.com/lviggiano/owner/blob/1223ecfbe3c275b3b7c5ec13e9238c9bb888754f/owner/src/main/java/org/aeonbits/owner/StrSubstitutor.java#L70-L83
train
siom79/japicmp
japicmp/src/main/java/japicmp/cmp/JarArchiveComparator.java
JarArchiveComparator.compare
public List<JApiClass> compare(JApiCmpArchive oldArchive, JApiCmpArchive newArchive) { return compare(Collections.singletonList(oldArchive), Collections.singletonList(newArchive)); }
java
public List<JApiClass> compare(JApiCmpArchive oldArchive, JApiCmpArchive newArchive) { return compare(Collections.singletonList(oldArchive), Collections.singletonList(newArchive)); }
[ "public", "List", "<", "JApiClass", ">", "compare", "(", "JApiCmpArchive", "oldArchive", ",", "JApiCmpArchive", "newArchive", ")", "{", "return", "compare", "(", "Collections", ".", "singletonList", "(", "oldArchive", ")", ",", "Collections", ".", "singletonList",...
Compares the two given archives. @param oldArchive the old version of the archive @param newArchive the new version of the archive @return a list which contains one instance of {@link japicmp.model.JApiClass} for each class found in one of the two archives @throws JApiCmpException if the comparison fails
[ "Compares", "the", "two", "given", "archives", "." ]
f008ea588eec721c45f568bf1db5074fbcbcfced
https://github.com/siom79/japicmp/blob/f008ea588eec721c45f568bf1db5074fbcbcfced/japicmp/src/main/java/japicmp/cmp/JarArchiveComparator.java#L82-L84
train
siom79/japicmp
japicmp/src/main/java/japicmp/cmp/JarArchiveComparator.java
JarArchiveComparator.compare
public List<JApiClass> compare(List<JApiCmpArchive> oldArchives, List<JApiCmpArchive> newArchives) { return createAndCompareClassLists(toFileList(oldArchives), toFileList(newArchives)); }
java
public List<JApiClass> compare(List<JApiCmpArchive> oldArchives, List<JApiCmpArchive> newArchives) { return createAndCompareClassLists(toFileList(oldArchives), toFileList(newArchives)); }
[ "public", "List", "<", "JApiClass", ">", "compare", "(", "List", "<", "JApiCmpArchive", ">", "oldArchives", ",", "List", "<", "JApiCmpArchive", ">", "newArchives", ")", "{", "return", "createAndCompareClassLists", "(", "toFileList", "(", "oldArchives", ")", ",",...
Compares the two given lists of archives. @param oldArchives the old versions of the archives @param newArchives the new versions of the archives @return a list which contains one instance of {@link japicmp.model.JApiClass} for each class found in one of the archives @throws JApiCmpException if the comparison fails
[ "Compares", "the", "two", "given", "lists", "of", "archives", "." ]
f008ea588eec721c45f568bf1db5074fbcbcfced
https://github.com/siom79/japicmp/blob/f008ea588eec721c45f568bf1db5074fbcbcfced/japicmp/src/main/java/japicmp/cmp/JarArchiveComparator.java#L94-L96
train
siom79/japicmp
japicmp/src/main/java/japicmp/cmp/JarArchiveComparator.java
JarArchiveComparator.compareClassLists
List<JApiClass> compareClassLists(JarArchiveComparatorOptions options, List<CtClass> oldClasses, List<CtClass> newClasses) { List<CtClass> oldClassesFiltered = applyFilter(options, oldClasses); List<CtClass> newClassesFiltered = applyFilter(options, newClasses); ClassesComparator classesComparator = new ClassesComparator(this, options); classesComparator.compare(oldClassesFiltered, newClassesFiltered); List<JApiClass> classList = classesComparator.getClasses(); if (LOGGER.isLoggable(Level.FINE)) { for (JApiClass jApiClass : classList) { LOGGER.fine(jApiClass.toString()); } } checkBinaryCompatibility(classList); checkJavaObjectSerializationCompatibility(classList); OutputFilter.sortClassesAndMethods(classList); return classList; }
java
List<JApiClass> compareClassLists(JarArchiveComparatorOptions options, List<CtClass> oldClasses, List<CtClass> newClasses) { List<CtClass> oldClassesFiltered = applyFilter(options, oldClasses); List<CtClass> newClassesFiltered = applyFilter(options, newClasses); ClassesComparator classesComparator = new ClassesComparator(this, options); classesComparator.compare(oldClassesFiltered, newClassesFiltered); List<JApiClass> classList = classesComparator.getClasses(); if (LOGGER.isLoggable(Level.FINE)) { for (JApiClass jApiClass : classList) { LOGGER.fine(jApiClass.toString()); } } checkBinaryCompatibility(classList); checkJavaObjectSerializationCompatibility(classList); OutputFilter.sortClassesAndMethods(classList); return classList; }
[ "List", "<", "JApiClass", ">", "compareClassLists", "(", "JarArchiveComparatorOptions", "options", ",", "List", "<", "CtClass", ">", "oldClasses", ",", "List", "<", "CtClass", ">", "newClasses", ")", "{", "List", "<", "CtClass", ">", "oldClassesFiltered", "=", ...
Compares the two lists with CtClass objects using the provided options instance. @param options the options to use @param oldClasses a list of CtClasses that represent the old version @param newClasses a list of CtClasses that represent the new version @return a list of {@link japicmp.model.JApiClass} that represent the changes
[ "Compares", "the", "two", "lists", "with", "CtClass", "objects", "using", "the", "provided", "options", "instance", "." ]
f008ea588eec721c45f568bf1db5074fbcbcfced
https://github.com/siom79/japicmp/blob/f008ea588eec721c45f568bf1db5074fbcbcfced/japicmp/src/main/java/japicmp/cmp/JarArchiveComparator.java#L203-L218
train
siom79/japicmp
japicmp/src/main/java/japicmp/cmp/JarArchiveComparator.java
JarArchiveComparator.loadClass
public Optional<CtClass> loadClass(ArchiveType archiveType, String name) { Optional<CtClass> loadedClass = Optional.absent(); if (this.options.getClassPathMode() == JarArchiveComparatorOptions.ClassPathMode.ONE_COMMON_CLASSPATH) { try { loadedClass = Optional.of(commonClassPool.get(name)); } catch (NotFoundException e) { if (!options.getIgnoreMissingClasses().ignoreClass(e.getMessage())) { throw JApiCmpException.forClassLoading(e, name, this); } } } else if (this.options.getClassPathMode() == JarArchiveComparatorOptions.ClassPathMode.TWO_SEPARATE_CLASSPATHS) { if (archiveType == ArchiveType.OLD) { try { loadedClass = Optional.of(oldClassPool.get(name)); } catch (NotFoundException e) { if (!options.getIgnoreMissingClasses().ignoreClass(e.getMessage())) { throw JApiCmpException.forClassLoading(e, name, this); } } } else if (archiveType == ArchiveType.NEW) { try { loadedClass = Optional.of(newClassPool.get(name)); } catch (NotFoundException e) { if (!options.getIgnoreMissingClasses().ignoreClass(e.getMessage())) { throw JApiCmpException.forClassLoading(e, name, this); } } } else { throw new JApiCmpException(Reason.IllegalState, "Unknown archive type: " + archiveType); } } else { throw new JApiCmpException(Reason.IllegalState, "Unknown classpath mode: " + this.options.getClassPathMode()); } return loadedClass; }
java
public Optional<CtClass> loadClass(ArchiveType archiveType, String name) { Optional<CtClass> loadedClass = Optional.absent(); if (this.options.getClassPathMode() == JarArchiveComparatorOptions.ClassPathMode.ONE_COMMON_CLASSPATH) { try { loadedClass = Optional.of(commonClassPool.get(name)); } catch (NotFoundException e) { if (!options.getIgnoreMissingClasses().ignoreClass(e.getMessage())) { throw JApiCmpException.forClassLoading(e, name, this); } } } else if (this.options.getClassPathMode() == JarArchiveComparatorOptions.ClassPathMode.TWO_SEPARATE_CLASSPATHS) { if (archiveType == ArchiveType.OLD) { try { loadedClass = Optional.of(oldClassPool.get(name)); } catch (NotFoundException e) { if (!options.getIgnoreMissingClasses().ignoreClass(e.getMessage())) { throw JApiCmpException.forClassLoading(e, name, this); } } } else if (archiveType == ArchiveType.NEW) { try { loadedClass = Optional.of(newClassPool.get(name)); } catch (NotFoundException e) { if (!options.getIgnoreMissingClasses().ignoreClass(e.getMessage())) { throw JApiCmpException.forClassLoading(e, name, this); } } } else { throw new JApiCmpException(Reason.IllegalState, "Unknown archive type: " + archiveType); } } else { throw new JApiCmpException(Reason.IllegalState, "Unknown classpath mode: " + this.options.getClassPathMode()); } return loadedClass; }
[ "public", "Optional", "<", "CtClass", ">", "loadClass", "(", "ArchiveType", "archiveType", ",", "String", "name", ")", "{", "Optional", "<", "CtClass", ">", "loadedClass", "=", "Optional", ".", "absent", "(", ")", ";", "if", "(", "this", ".", "options", ...
Loads a class either from the old, new or common classpath. @param archiveType specify if this class should be loaded from the old or new class path @param name the name of the class (FQN) @return the loaded class (if options are not set to ignore missing classes) @throws japicmp.exception.JApiCmpException if loading the class fails
[ "Loads", "a", "class", "either", "from", "the", "old", "new", "or", "common", "classpath", "." ]
f008ea588eec721c45f568bf1db5074fbcbcfced
https://github.com/siom79/japicmp/blob/f008ea588eec721c45f568bf1db5074fbcbcfced/japicmp/src/main/java/japicmp/cmp/JarArchiveComparator.java#L345-L379
train
siom79/japicmp
japicmp/src/main/java/japicmp/compat/CompatibilityChanges.java
CompatibilityChanges.isImplemented
private boolean isImplemented(JApiMethod jApiMethod) { JApiClass aClass = jApiMethod.getjApiClass(); while(aClass != null) { for (JApiMethod method : aClass.getMethods()) { if (jApiMethod.getName().equals(method.getName()) && jApiMethod.hasSameParameter(method) && !isAbstract(method) && method.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(method)) { return true; } } if(aClass.getSuperclass() != null && aClass.getSuperclass().getJApiClass().isPresent()) { aClass = aClass.getSuperclass().getJApiClass().get(); } else { aClass = null; } } return false; }
java
private boolean isImplemented(JApiMethod jApiMethod) { JApiClass aClass = jApiMethod.getjApiClass(); while(aClass != null) { for (JApiMethod method : aClass.getMethods()) { if (jApiMethod.getName().equals(method.getName()) && jApiMethod.hasSameParameter(method) && !isAbstract(method) && method.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(method)) { return true; } } if(aClass.getSuperclass() != null && aClass.getSuperclass().getJApiClass().isPresent()) { aClass = aClass.getSuperclass().getJApiClass().get(); } else { aClass = null; } } return false; }
[ "private", "boolean", "isImplemented", "(", "JApiMethod", "jApiMethod", ")", "{", "JApiClass", "aClass", "=", "jApiMethod", ".", "getjApiClass", "(", ")", ";", "while", "(", "aClass", "!=", "null", ")", "{", "for", "(", "JApiMethod", "method", ":", "aClass",...
Is a method implemented in a super class @param jApiMethod the method @return <code>true</code> if it is implemented in a super class
[ "Is", "a", "method", "implemented", "in", "a", "super", "class" ]
f008ea588eec721c45f568bf1db5074fbcbcfced
https://github.com/siom79/japicmp/blob/f008ea588eec721c45f568bf1db5074fbcbcfced/japicmp/src/main/java/japicmp/compat/CompatibilityChanges.java#L538-L555
train
JakeWharton/RxRelay
src/main/java/com/jakewharton/rxrelay2/SerializedRelay.java
SerializedRelay.emitLoop
private void emitLoop() { for (;;) { AppendOnlyLinkedArrayList<T> q; synchronized (this) { q = queue; if (q == null) { emitting = false; return; } queue = null; } q.accept(actual); } }
java
private void emitLoop() { for (;;) { AppendOnlyLinkedArrayList<T> q; synchronized (this) { q = queue; if (q == null) { emitting = false; return; } queue = null; } q.accept(actual); } }
[ "private", "void", "emitLoop", "(", ")", "{", "for", "(", ";", ";", ")", "{", "AppendOnlyLinkedArrayList", "<", "T", ">", "q", ";", "synchronized", "(", "this", ")", "{", "q", "=", "queue", ";", "if", "(", "q", "==", "null", ")", "{", "emitting", ...
Loops until all notifications in the queue has been processed.
[ "Loops", "until", "all", "notifications", "in", "the", "queue", "has", "been", "processed", "." ]
67231debeb87eabbacb3bbacebd5353637b32327
https://github.com/JakeWharton/RxRelay/blob/67231debeb87eabbacb3bbacebd5353637b32327/src/main/java/com/jakewharton/rxrelay2/SerializedRelay.java#L62-L75
train
jenetics/jenetics
jenetics/src/main/java/io/jenetics/Genotype.java
Genotype.geneCount
public int geneCount() { int count = 0; for (int i = 0, n = _chromosomes.length(); i < n; ++i) { count += _chromosomes.get(i).length(); } return count; }
java
public int geneCount() { int count = 0; for (int i = 0, n = _chromosomes.length(); i < n; ++i) { count += _chromosomes.get(i).length(); } return count; }
[ "public", "int", "geneCount", "(", ")", "{", "int", "count", "=", "0", ";", "for", "(", "int", "i", "=", "0", ",", "n", "=", "_chromosomes", ".", "length", "(", ")", ";", "i", "<", "n", ";", "++", "i", ")", "{", "count", "+=", "_chromosomes", ...
Return the number of genes this genotype consists of. This is the sum of the number of genes of the genotype chromosomes. @return Return the number of genes this genotype consists of.
[ "Return", "the", "number", "of", "genes", "this", "genotype", "consists", "of", ".", "This", "is", "the", "sum", "of", "the", "number", "of", "genes", "of", "the", "genotype", "chromosomes", "." ]
ee516770c65ef529b27deb283f071c85f344eff4
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/Genotype.java#L226-L232
train
jenetics/jenetics
jenetics/src/main/java/io/jenetics/stat/MinMax.java
MinMax.accept
@Override public void accept(final C object) { _min = min(_comparator, _min, object); _max = max(_comparator, _max, object); ++_count; }
java
@Override public void accept(final C object) { _min = min(_comparator, _min, object); _max = max(_comparator, _max, object); ++_count; }
[ "@", "Override", "public", "void", "accept", "(", "final", "C", "object", ")", "{", "_min", "=", "min", "(", "_comparator", ",", "_min", ",", "object", ")", ";", "_max", "=", "max", "(", "_comparator", ",", "_max", ",", "object", ")", ";", "++", "_...
Accept the element for min-max calculation. @param object the element to use for min-max calculation
[ "Accept", "the", "element", "for", "min", "-", "max", "calculation", "." ]
ee516770c65ef529b27deb283f071c85f344eff4
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/stat/MinMax.java#L73-L78
train
jenetics/jenetics
jenetics/src/main/java/io/jenetics/IntegerChromosome.java
IntegerChromosome.toArray
public int[] toArray(final int[] array) { final int[] a = array.length >= length() ? array : new int[length()]; for (int i = length(); --i >= 0;) { a[i] = intValue(i); } return a; }
java
public int[] toArray(final int[] array) { final int[] a = array.length >= length() ? array : new int[length()]; for (int i = length(); --i >= 0;) { a[i] = intValue(i); } return a; }
[ "public", "int", "[", "]", "toArray", "(", "final", "int", "[", "]", "array", ")", "{", "final", "int", "[", "]", "a", "=", "array", ".", "length", ">=", "length", "(", ")", "?", "array", ":", "new", "int", "[", "length", "(", ")", "]", ";", ...
Returns an int array containing all of the elements in this chromosome in proper sequence. If the chromosome fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the length of this chromosome. @since 3.0 @param array the array into which the elements of this chromosomes are to be stored, if it is big enough; otherwise, a new array is allocated for this purpose. @return an array containing the elements of this chromosome @throws NullPointerException if the given {@code array} is {@code null}
[ "Returns", "an", "int", "array", "containing", "all", "of", "the", "elements", "in", "this", "chromosome", "in", "proper", "sequence", ".", "If", "the", "chromosome", "fits", "in", "the", "specified", "array", "it", "is", "returned", "therein", ".", "Otherwi...
ee516770c65ef529b27deb283f071c85f344eff4
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/IntegerChromosome.java#L169-L176
train
jenetics/jenetics
jenetics/src/main/java/io/jenetics/internal/math/DoubleAdder.java
DoubleAdder.add
public DoubleAdder add(final double[] values) { for (int i = values.length; --i >= 0;) { add(values[i]); } return this; }
java
public DoubleAdder add(final double[] values) { for (int i = values.length; --i >= 0;) { add(values[i]); } return this; }
[ "public", "DoubleAdder", "add", "(", "final", "double", "[", "]", "values", ")", "{", "for", "(", "int", "i", "=", "values", ".", "length", ";", "--", "i", ">=", "0", ";", ")", "{", "add", "(", "values", "[", "i", "]", ")", ";", "}", "return", ...
Add the given values to this adder. @param values the values to add. @return {@code this} adder, for command chaining
[ "Add", "the", "given", "values", "to", "this", "adder", "." ]
ee516770c65ef529b27deb283f071c85f344eff4
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/internal/math/DoubleAdder.java#L116-L122
train
jenetics/jenetics
jenetics.example/src/main/java/io/jenetics/example/image/Polygon.java
Polygon.draw
public void draw(final Graphics2D g, final int width, final int height) { g.setColor(new Color(_data[0], _data[1], _data[2], _data[3])); final GeneralPath path = new GeneralPath(); path.moveTo(_data[4]*width, _data[5]*height); for (int j = 1; j < _length; ++j) { path.lineTo(_data[4 + j*2]*width, _data[5 + j*2]*height); } path.closePath(); g.fill(path); }
java
public void draw(final Graphics2D g, final int width, final int height) { g.setColor(new Color(_data[0], _data[1], _data[2], _data[3])); final GeneralPath path = new GeneralPath(); path.moveTo(_data[4]*width, _data[5]*height); for (int j = 1; j < _length; ++j) { path.lineTo(_data[4 + j*2]*width, _data[5 + j*2]*height); } path.closePath(); g.fill(path); }
[ "public", "void", "draw", "(", "final", "Graphics2D", "g", ",", "final", "int", "width", ",", "final", "int", "height", ")", "{", "g", ".", "setColor", "(", "new", "Color", "(", "_data", "[", "0", "]", ",", "_data", "[", "1", "]", ",", "_data", "...
Draw the Polygon to the buffer of the given size.
[ "Draw", "the", "Polygon", "to", "the", "buffer", "of", "the", "given", "size", "." ]
ee516770c65ef529b27deb283f071c85f344eff4
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics.example/src/main/java/io/jenetics/example/image/Polygon.java#L107-L117
train
jenetics/jenetics
jenetics.example/src/main/java/io/jenetics/example/image/Polygon.java
Polygon.newRandom
public static Polygon newRandom(final int length, final Random random) { require.positive(length); final Polygon p = new Polygon(length); p._data[0] = random.nextFloat(); // r p._data[1] = random.nextFloat(); // g p._data[2] = random.nextFloat(); // b p._data[3] = max(0.2F, random.nextFloat()*random.nextFloat()); // a float px = 0.5F; float py = 0.5F; for (int k = 0; k < length; k++) { p._data[4 + 2*k] = px = clamp(px + random.nextFloat() - 0.5F); p._data[5 + 2*k] = py = clamp(py + random.nextFloat() - 0.5F); } return p; }
java
public static Polygon newRandom(final int length, final Random random) { require.positive(length); final Polygon p = new Polygon(length); p._data[0] = random.nextFloat(); // r p._data[1] = random.nextFloat(); // g p._data[2] = random.nextFloat(); // b p._data[3] = max(0.2F, random.nextFloat()*random.nextFloat()); // a float px = 0.5F; float py = 0.5F; for (int k = 0; k < length; k++) { p._data[4 + 2*k] = px = clamp(px + random.nextFloat() - 0.5F); p._data[5 + 2*k] = py = clamp(py + random.nextFloat() - 0.5F); } return p; }
[ "public", "static", "Polygon", "newRandom", "(", "final", "int", "length", ",", "final", "Random", "random", ")", "{", "require", ".", "positive", "(", "length", ")", ";", "final", "Polygon", "p", "=", "new", "Polygon", "(", "length", ")", ";", "p", "....
Creates a new random Polygon of the given length.
[ "Creates", "a", "new", "random", "Polygon", "of", "the", "given", "length", "." ]
ee516770c65ef529b27deb283f071c85f344eff4
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics.example/src/main/java/io/jenetics/example/image/Polygon.java#L122-L138
train