private synchronized void init() throws SQLException { if (isClosed) return; // do tables exists? Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(TABLE_NAMES_SELECT_STMT); ArrayList<String> missingTables = new ArrayList(TABLES.keySet()); while (rs.next()) { String tableName = rs.getString("name"); missingTables.remove(tableName); } for (String missingTable : missingTables) { try { Statement createStmt = conn.createStatement(); // System.out.println("Adding table "+ missingTable); createStmt.executeUpdate(TABLES.get(missingTable)); createStmt.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } }
public synchronized void close() { if (isClosed) return; try { if (conn != null) conn.close(); isClosed = true; } catch (Exception e) { e.printStackTrace(); } }
@Override public String getUsername(byte[] encodedKey) { String b64key = Base64.getEncoder().encodeToString(encodedKey); try { try (PreparedStatement preparedStatement = conn.prepareStatement("select name from users where publickey = ? limit 1")) { preparedStatement.setString(1, b64key); ResultSet resultSet = preparedStatement.executeQuery(); boolean next = resultSet.next(); if (!next) return ""; return resultSet.getString(1); } } catch (SQLException sqle) { throw new IllegalStateException(sqle); } }
public boolean delete(String table, String deleteString) { Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate("delete from " + table + " where " + deleteString + ";"); return true; } catch (SQLException sqe) { sqe.printStackTrace(); return false; } finally { if (stmt != null) try { stmt.close(); } catch (SQLException sqe2) { sqe2.printStackTrace(); } } }
@Override public byte[] getAllUsernamesGzip() throws IOException { try (PreparedStatement stmt = conn.prepareStatement("select name from users")) { ResultSet rs = stmt.executeQuery(); List<String> list = new ArrayList<>(); while (rs.next()) { String username = rs.getString("name"); list.add(username); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); try (DataOutputStream dout = new DataOutputStream(new GZIPOutputStream(bout))) { for (String uname : list) Serialize.serialize(uname, dout); } return bout.toByteArray(); } catch (SQLException sqe) { throw new IOException(sqe); } }