diff options
| author | Simon Rettberg | 2015-06-11 18:40:49 +0200 |
|---|---|---|
| committer | Simon Rettberg | 2015-06-11 18:40:49 +0200 |
| commit | e0005ceecfd9281230c4add7575b18ee88307774 (patch) | |
| tree | a73bbcfc213df478c701aac120ae2b7c6e52bb1b /dozentenmodulserver/src/main/java/sql | |
| parent | [server] db stuff, new interface, ... (diff) | |
| download | tutor-module-e0005ceecfd9281230c4add7575b18ee88307774.tar.gz tutor-module-e0005ceecfd9281230c4add7575b18ee88307774.tar.xz tutor-module-e0005ceecfd9281230c4add7575b18ee88307774.zip | |
[server] On mah way (lots of restructuring, some early db classes, sql dump of current schema)
Diffstat (limited to 'dozentenmodulserver/src/main/java/sql')
4 files changed, 0 insertions, 487 deletions
diff --git a/dozentenmodulserver/src/main/java/sql/MysqlConnection.java b/dozentenmodulserver/src/main/java/sql/MysqlConnection.java deleted file mode 100644 index dbbddfe1..00000000 --- a/dozentenmodulserver/src/main/java/sql/MysqlConnection.java +++ /dev/null @@ -1,74 +0,0 @@ -package sql; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -public class MysqlConnection implements AutoCloseable { - - private static final Logger LOGGER = Logger.getLogger(MysqlConnection.class); - - private static final int CONNECTION_TIMEOUT_MS = 5 * 60 * 1000; - - private final long deadline = System.currentTimeMillis() + CONNECTION_TIMEOUT_MS; - - private final Connection rawConnection; - - private boolean hasPendingQueries = false; - - private List<MysqlStatement> openStatements = new ArrayList<>(); - - MysqlConnection(Connection rawConnection) { - this.rawConnection = rawConnection; - } - - public MysqlStatement prepareStatement(String sql) throws SQLException { - hasPendingQueries = true; - MysqlStatement statement = new MysqlStatement(rawConnection, sql); - openStatements.add(statement); - return statement; - } - - public void commit() throws SQLException { - rawConnection.commit(); - hasPendingQueries = false; - } - - public void rollback() throws SQLException { - rawConnection.rollback(); - hasPendingQueries = false; - } - - boolean isValid() { - return System.currentTimeMillis() < deadline; - } - - @Override - public void close() { - if (hasPendingQueries) { - LOGGER.warn("Mysql connection had uncommited queries on .close()"); - try { - rawConnection.rollback(); - } catch (SQLException e) { - LOGGER.warn("Rolling back uncommited queries failed!", e); - } - for (MysqlStatement statement : openStatements) { - statement.close(); - } - openStatements.clear(); - } - SQL.returnConnection(this); - } - - void release() { - try { - rawConnection.close(); - } catch (SQLException e) { - // Nothing meaningful to do - } - } - -} diff --git a/dozentenmodulserver/src/main/java/sql/MysqlStatement.java b/dozentenmodulserver/src/main/java/sql/MysqlStatement.java deleted file mode 100644 index efef88b0..00000000 --- a/dozentenmodulserver/src/main/java/sql/MysqlStatement.java +++ /dev/null @@ -1,291 +0,0 @@ -package sql; - -import java.io.Closeable; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Class for creating {@link java.sql.PreparedStatement}s with - * named parameters. - * Based on - * <a href= - * "http://www.javaworld.com/article/2077706/core-java/named-parameters-for-preparedstatement.html?page=2" - * >Named Parameters for PreparedStatement</a> - */ -public class MysqlStatement implements Closeable { - - private static final QueryCache cache = new QueryCache(); - - private final PreparsedQuery query; - - private final PreparedStatement statement; - - private final List<ResultSet> openResultSets = new ArrayList<>(); - - MysqlStatement(Connection con, String sql) throws SQLException { - PreparsedQuery query; - synchronized (cache) { - query = cache.get(sql); - } - if (query == null) { - query = parse(sql); - synchronized (cache) { - cache.put(sql, query); - } - } - this.query = query; - this.statement = con.prepareStatement(query.sql); - } - - /** - * Returns the indexes for a parameter. - * - * @param name parameter name - * @return parameter indexes - * @throws IllegalArgumentException if the parameter does not exist - */ - private List<Integer> getIndexes(String name) { - List<Integer> indexes = query.indexMap.get(name); - if (indexes == null) { - throw new IllegalArgumentException("Parameter not found: " + name); - } - return indexes; - } - - /** - * Sets a parameter. - * - * @param name parameter name - * @param value parameter value - * @throws SQLException if an error occurred - * @throws IllegalArgumentException if the parameter does not exist - * @see PreparedStatement#setObject(int, java.lang.Object) - */ - public void setObject(String name, Object value) throws SQLException { - List<Integer> indexes = getIndexes(name); - for (Integer index : indexes) { - statement.setObject(index, value); - } - } - - /** - * Sets a parameter. - * - * @param name parameter name - * @param value parameter value - * @throws SQLException if an error occurred - * @throws IllegalArgumentException if the parameter does not exist - * @see PreparedStatement#setString(int, java.lang.String) - */ - public void setString(String name, String value) throws SQLException { - List<Integer> indexes = getIndexes(name); - for (Integer index : indexes) { - statement.setString(index, value); - } - } - - /** - * Sets a parameter. - * - * @param name parameter name - * @param value parameter value - * @throws SQLException if an error occurred - * @throws IllegalArgumentException if the parameter does not exist - * @see PreparedStatement#setInt(int, int) - */ - public void setInt(String name, int value) throws SQLException { - List<Integer> indexes = getIndexes(name); - for (Integer index : indexes) { - statement.setInt(index, value); - } - } - - /** - * Sets a parameter. - * - * @param name parameter name - * @param value parameter value - * @throws SQLException if an error occurred - * @throws IllegalArgumentException if the parameter does not exist - * @see PreparedStatement#setInt(int, int) - */ - public void setLong(String name, long value) throws SQLException { - List<Integer> indexes = getIndexes(name); - for (Integer index : indexes) { - statement.setLong(index, value); - } - } - - /** - * Executes the statement. - * - * @return true if the first result is a {@link ResultSet} - * @throws SQLException if an error occurred - * @see PreparedStatement#execute() - */ - public boolean execute() throws SQLException { - return statement.execute(); - } - - /** - * Executes the statement, which must be a query. - * - * @return the query results - * @throws SQLException if an error occurred - * @see PreparedStatement#executeQuery() - */ - public ResultSet executeQuery() throws SQLException { - ResultSet rs = statement.executeQuery(); - openResultSets.add(rs); - return rs; - } - - /** - * Executes the statement, which must be an SQL INSERT, UPDATE or DELETE - * statement; or an SQL statement that returns nothing, such as a DDL - * statement. - * - * @return number of rows affected - * @throws SQLException if an error occurred - * @see PreparedStatement#executeUpdate() - */ - public int executeUpdate() throws SQLException { - return statement.executeUpdate(); - } - - /** - * Closes the statement. - * - * @see Statement#close() - */ - @Override - public void close() { - for (ResultSet rs : openResultSets) { - try { - rs.close(); - } catch (SQLException e) { - // - } - } - try { - statement.close(); - } catch (SQLException e) { - // Nothing to do - } - } - - /** - * Adds the current set of parameters as a batch entry. - * - * @throws SQLException if something went wrong - */ - public void addBatch() throws SQLException { - statement.addBatch(); - } - - /** - * Executes all of the batched statements. - * - * See {@link Statement#executeBatch()} for details. - * - * @return update counts for each statement - * @throws SQLException if something went wrong - */ - public int[] executeBatch() throws SQLException { - return statement.executeBatch(); - } - - // static methods - - private static PreparsedQuery parse(String query) { - int length = query.length(); - StringBuffer parsedQuery = new StringBuffer(length); - Map<String, List<Integer>> paramMap = new HashMap<>(); - boolean inSingleQuote = false; - boolean inDoubleQuote = false; - boolean hasBackslash = false; - int index = 1; - - for (int i = 0; i < length; i++) { - char c = query.charAt(i); - if (hasBackslash) { - // Last char was a backslash, so we ignore the current char - hasBackslash = false; - } else if (c == '\\') { - // This is a backslash, next char will be escaped - hasBackslash = true; - } else if (inSingleQuote) { - // End of quoted string - if (c == '\'') { - inSingleQuote = false; - } - } else if (inDoubleQuote) { - // End of quoted string - if (c == '"') { - inDoubleQuote = false; - } - } else { - // Not in string, look for named params - if (c == '\'') { - inSingleQuote = true; - } else if (c == '"') { - inDoubleQuote = true; - } else if (c == ':' && i + 1 < length && Character.isJavaIdentifierStart(query.charAt(i + 1))) { - int j = i + 2; - while (j < length && Character.isJavaIdentifierPart(query.charAt(j))) { - j++; - } - String name = query.substring(i + 1, j); - c = '?'; // replace the parameter with a question mark - i += name.length(); // skip past the end of the parameter - - List<Integer> indexList = paramMap.get(name); - if (indexList == null) { - indexList = new ArrayList<>(); - paramMap.put(name, indexList); - } - indexList.add(new Integer(index)); - - index++; - } - } - parsedQuery.append(c); - } - - return new PreparsedQuery(parsedQuery.toString(), paramMap); - } - - // private helper classes - - private static class PreparsedQuery { - private final Map<String, List<Integer>> indexMap; - private final String sql; - - public PreparsedQuery(String sql, Map<String, List<Integer>> indexMap) { - this.sql = sql; - this.indexMap = indexMap; - } - } - - private static class QueryCache extends LinkedHashMap<String, PreparsedQuery> { - private static final long serialVersionUID = 1L; - - public QueryCache() { - super(30, (float) 0.75, true); - } - - @Override - protected boolean removeEldestEntry(Map.Entry<String, PreparsedQuery> eldest) { - return size() > 40; - } - } - -} diff --git a/dozentenmodulserver/src/main/java/sql/SQL.java b/dozentenmodulserver/src/main/java/sql/SQL.java deleted file mode 100644 index af79b521..00000000 --- a/dozentenmodulserver/src/main/java/sql/SQL.java +++ /dev/null @@ -1,81 +0,0 @@ -package sql;
-
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
-import java.util.Collections;
-import java.util.Queue;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-import models.Configuration;
-
-import org.apache.log4j.Logger;
-
-public class SQL {
-
- private static final Logger LOGGER = Logger.getLogger(SQL.class);
- /**
- * Pool of available connections.
- */
- private static final Queue<MysqlConnection> pool = new ConcurrentLinkedQueue<>();
-
- /**
- * Set of connections currently handed out.
- */
- private static final Set<MysqlConnection> busyConnections = Collections.newSetFromMap(new ConcurrentHashMap<MysqlConnection, Boolean>());
-
- static {
- try {
- Class.forName("com.mysql.jdbc.Driver").newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
- LOGGER.fatal("Cannot get mysql JDBC driver!", e);
- System.exit(1);
- }
- }
-
- public static MysqlConnection getConnection() {
- MysqlConnection con;
- for (;;) {
- con = pool.poll();
- if (con == null)
- break;
- if (!con.isValid()) {
- con.release();
- continue;
- }
- if (!busyConnections.add(con))
- throw new RuntimeException("Tried to hand out a busy connection!");
- return con;
- }
- // No pooled connection
- if (busyConnections.size() > 20) {
- LOGGER.warn("Too many open MySQL connections. Possible connection leak!");
- return null;
- }
- try {
- // Create fresh connection
- Connection rawConnection = DriverManager.getConnection(Configuration.getDbUri(),
- Configuration.getDbUsername(), Configuration.getDbPassword());
- // By convention in our program we don't want auto commit
- rawConnection.setAutoCommit(false);
- // Wrap into our proxy
- con = new MysqlConnection(rawConnection);
- // Keep track of busy mysql connection
- if (!busyConnections.add(con))
- throw new RuntimeException("Tried to hand out a busy connection!");
- return con;
- } catch (SQLException e) {
- LOGGER.info("Failed to connect to local mysql server", e);
- }
- return null;
- }
-
- static void returnConnection(MysqlConnection connection) {
- if (!busyConnections.remove(connection))
- throw new RuntimeException("Tried to return a mysql connection to the pool that was not taken!");
- pool.add(connection);
- }
-
-}// end class
diff --git a/dozentenmodulserver/src/main/java/sql/models/DbImage.java b/dozentenmodulserver/src/main/java/sql/models/DbImage.java deleted file mode 100644 index fe59dac8..00000000 --- a/dozentenmodulserver/src/main/java/sql/models/DbImage.java +++ /dev/null @@ -1,41 +0,0 @@ -package sql.models; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import org.apache.log4j.Logger; -import org.openslx.bwlp.thrift.iface.ImageSummaryRead; -import org.openslx.bwlp.thrift.iface.UserInfo; - -import sql.MysqlConnection; -import sql.MysqlStatement; -import sql.SQL; - -public class DbImage { - - private static final Logger LOGGER = Logger.getLogger(DbImage.class); - - public static List<ImageSummaryRead> getAllVisible(UserInfo user, List<String> tagSearch) { - try (MysqlConnection connection = SQL.getConnection()) { - MysqlStatement stmt = connection.prepareStatement("SELECT" - + " i.imagebaseid, i.currentversionid, i.latestversionid, i.displayname," - + " i.osid, i.virtid, i.createtime, i.updatetime, i.ownerid, i.uploaderid," - + " i.sharemode, i.istemplate, i.canlinkdefault, i.candownloaddefault," - + " i.caneditdefault, i.canadmindefault," - + " cur.filesize, cur.isenabled, cur.isrestricted, cur.isvalid," + " lat.isprocessed" - + " FROM imagebase i" - + " LEFT JOIN imageversion cur ON (cur.imageversionid = i.currentversionid)" - + " LEFT JOIN imageversion lat ON (lat.imageversionid = i.latestversionid)"); - ResultSet rs = stmt.executeQuery(); - while (rs.next()) { - ImageSummaryRead entry = new ImageSummaryRead(); - } - return null; - } catch (SQLException e) { - LOGGER.error("Query failed in DbImage.getAllVisible()", e); - return null; - } - } - -} |
