Skip to content

Commit eb16a4e

Browse files
sedukullDaanHoogland
authored andcommitted
Fixed Resource Leaks
Signed-off-by: Daan Hoogland <daan@onecht.net> (cherry picked from commit c690320)
1 parent 20a457d commit eb16a4e

4 files changed

Lines changed: 83 additions & 102 deletions

File tree

engine/schema/src/com/cloud/upgrade/dao/DatabaseAccessObject.java

Lines changed: 20 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -26,63 +26,49 @@ public class DatabaseAccessObject {
2626

2727
private static Logger s_logger = Logger.getLogger(DatabaseAccessObject.class);
2828

29-
public void dropKey(Connection conn, String tableName, String key, boolean isForeignKey) {
30-
PreparedStatement pstmt = null;
31-
try {
32-
if (isForeignKey) {
33-
pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP FOREIGN KEY " + key);
34-
} else {
35-
pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP KEY " + key);
36-
}
29+
public void dropKey(Connection conn, String tableName, String key, boolean isForeignKey)
30+
{
31+
String alter_sql_str;
32+
if (isForeignKey) {
33+
alter_sql_str = "ALTER TABLE " + tableName + " DROP FOREIGN KEY " + key;
34+
} else {
35+
alter_sql_str = "ALTER TABLE " + tableName + " DROP KEY " + key;
36+
}
37+
try(PreparedStatement pstmt = conn.prepareStatement(alter_sql_str);)
38+
{
3739
pstmt.executeUpdate();
3840
s_logger.debug("Key " + key + " is dropped successfully from the table " + tableName);
3941
} catch (SQLException e) {
40-
s_logger.warn("Ignored SQL Exception when trying to drop " + (isForeignKey ? "foreign " : "") + "key " + key + " on table " + tableName, e);
41-
} finally {
42-
closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement atfer dropping " + (isForeignKey ? "foreign " : "") + "key " + key
43-
+ " on table " + tableName);
42+
s_logger.warn("dropKey:Exception:"+e.getMessage());
4443
}
4544
}
4645

4746
public void dropPrimaryKey(Connection conn, String tableName) {
48-
PreparedStatement pstmt = null;
49-
try {
50-
pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP PRIMARY KEY ");
47+
try(PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP PRIMARY KEY ");) {
5148
pstmt.executeUpdate();
5249
s_logger.debug("Primary key is dropped successfully from the table " + tableName);
53-
} catch (SQLException e) {
54-
s_logger.warn("Ignored SQL Exception when trying to drop primary key on table " + tableName, e);
55-
} finally {
56-
closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement atfer dropping primary key on table " + tableName);
50+
} catch (Exception e) {
51+
s_logger.warn("dropPrimaryKey:Exception:"+e.getMessage());
5752
}
5853
}
5954

6055
public void dropColumn(Connection conn, String tableName, String columnName) {
61-
PreparedStatement pstmt = null;
62-
try {
63-
pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP COLUMN " + columnName);
56+
try (PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE " + tableName + " DROP COLUMN " + columnName);){
6457
pstmt.executeUpdate();
6558
s_logger.debug("Column " + columnName + " is dropped successfully from the table " + tableName);
66-
} catch (SQLException e) {
67-
s_logger.warn("Unable to drop columns using query " + pstmt + " due to exception", e);
68-
} finally {
69-
closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement after dropping column " + columnName + " on table " + tableName);
59+
} catch (Exception e) {
60+
s_logger.warn("dropColumn:Exception:"+e.getMessage());
7061
}
7162
}
7263

7364
public boolean columnExists(Connection conn, String tableName, String columnName) {
7465
boolean columnExists = false;
75-
PreparedStatement pstmt = null;
76-
try {
77-
pstmt = conn.prepareStatement("SELECT " + columnName + " FROM " + tableName);
66+
try (PreparedStatement pstmt = conn.prepareStatement("SELECT " + columnName + " FROM " + tableName);){
7867
pstmt.executeQuery();
7968
columnExists = true;
80-
} catch (SQLException e) {
81-
s_logger.warn("Field " + columnName + " doesn't exist in " + tableName, e);
82-
} finally {
83-
closePreparedStatement(pstmt, "Ignored SQL Exception when trying to close PreparedStatement atfer checking if column " + columnName + " existed on table " + tableName);
69+
} catch (Exception e) {
70+
s_logger.warn("columnExists:Exception:"+e.getMessage());
8471
}
85-
8672
return columnExists;
8773
}
8874

framework/db/src/com/cloud/utils/crypt/EncryptionSecretKeyChanger.java

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,8 @@ public static void main(String[] args) {
105105
PropertiesConfiguration backupDBProps = null;
106106

107107
System.out.println("Parsing db.properties file");
108-
try {
109-
dbProps.load(new FileInputStream(dbPropsFile));
108+
try(FileInputStream db_prop_fstream = new FileInputStream(dbPropsFile);) {
109+
dbProps.load(db_prop_fstream);
110110
backupDBProps = new PropertiesConfiguration(dbPropsFile);
111111
} catch (FileNotFoundException e) {
112112
System.out.println("db.properties file not found while reading DB secret key" + e.getMessage());
@@ -142,11 +142,10 @@ public static void main(String[] args) {
142142
//db.properties updated successfully
143143
if (encryptionType.equals("file")) {
144144
//update key file with new MS key
145-
try {
146-
FileWriter fwriter = new FileWriter(keyFile);
147-
BufferedWriter bwriter = new BufferedWriter(fwriter);
145+
try (FileWriter fwriter = new FileWriter(keyFile);
146+
BufferedWriter bwriter = new BufferedWriter(fwriter);)
147+
{
148148
bwriter.write(newMSKey);
149-
bwriter.close();
150149
} catch (IOException e) {
151150
System.out.println("Failed to write new secret to file. Please update the file manually");
152151
}
@@ -180,11 +179,10 @@ public static void main(String[] args) {
180179
}
181180
if (encryptionType.equals("file")) {
182181
//revert secret key in file
183-
try {
184-
FileWriter fwriter = new FileWriter(keyFile);
185-
BufferedWriter bwriter = new BufferedWriter(fwriter);
182+
try (FileWriter fwriter = new FileWriter(keyFile);
183+
BufferedWriter bwriter = new BufferedWriter(fwriter);)
184+
{
186185
bwriter.write(oldMSKey);
187-
bwriter.close();
188186
} catch (IOException e) {
189187
System.out.println("Failed to revert to old secret to file. Please update the file manually");
190188
}

framework/db/src/com/cloud/utils/db/ScriptRunner.java

Lines changed: 33 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -131,52 +131,44 @@ private void runScript(Connection conn, Reader reader) throws IOException, SQLEx
131131
} else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
132132
command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
133133
command.append(" ");
134-
Statement statement = conn.createStatement();
135-
136-
println(command);
137-
138-
boolean hasResults = false;
139-
if (stopOnError) {
140-
hasResults = statement.execute(command.toString());
141-
} else {
142-
try {
143-
statement.execute(command.toString());
144-
} catch (SQLException e) {
145-
e.fillInStackTrace();
146-
printlnError("Error executing: " + command);
147-
printlnError(e);
134+
try (Statement statement = conn.createStatement();) {
135+
println(command);
136+
boolean hasResults = false;
137+
if (stopOnError) {
138+
hasResults = statement.execute(command.toString());
139+
} else {
140+
try {
141+
statement.execute(command.toString());
142+
} catch (SQLException e) {
143+
e.fillInStackTrace();
144+
printlnError("Error executing: " + command);
145+
printlnError(e);
146+
}
148147
}
149-
}
150-
151-
if (autoCommit && !conn.getAutoCommit()) {
152-
conn.commit();
153-
}
154-
155-
ResultSet rs = statement.getResultSet();
156-
if (hasResults && rs != null) {
157-
ResultSetMetaData md = rs.getMetaData();
158-
int cols = md.getColumnCount();
159-
for (int i = 0; i < cols; i++) {
160-
String name = md.getColumnLabel(i);
161-
print(name + "\t");
148+
if (autoCommit && !conn.getAutoCommit()) {
149+
conn.commit();
162150
}
163-
println("");
164-
while (rs.next()) {
165-
for (int i = 1; i <= cols; i++) {
166-
String value = rs.getString(i);
167-
print(value + "\t");
151+
try(ResultSet rs = statement.getResultSet();) {
152+
if (hasResults && rs != null) {
153+
ResultSetMetaData md = rs.getMetaData();
154+
int cols = md.getColumnCount();
155+
for (int i = 0; i < cols; i++) {
156+
String name = md.getColumnLabel(i);
157+
print(name + "\t");
158+
}
159+
println("");
160+
while (rs.next()) {
161+
for (int i = 1; i <= cols; i++) {
162+
String value = rs.getString(i);
163+
print(value + "\t");
164+
}
165+
println("");
166+
}
168167
}
169-
println("");
168+
command = null;
169+
Thread.yield();
170170
}
171171
}
172-
173-
command = null;
174-
try {
175-
statement.close();
176-
} catch (Exception e) {
177-
// Ignore to workaround a bug in Jakarta DBCP
178-
}
179-
Thread.yield();
180172
} else {
181173
int idx = line.indexOf("--");
182174
if (idx != -1)

framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/AsyncJobJoinMapDaoImpl.java

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -214,12 +214,14 @@ public List<Long> findJobsToWake(long joinedJobId) {
214214
List<Long> standaloneList = new ArrayList<Long>();
215215
TransactionLegacy txn = TransactionLegacy.currentTxn();
216216
String sql = "SELECT job_id FROM async_job_join_map WHERE join_job_id = ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
217-
try {
218-
PreparedStatement pstmt = txn.prepareStatement(sql);
217+
try (PreparedStatement pstmt = txn.prepareStatement(sql);){
219218
pstmt.setLong(1, joinedJobId);
220-
ResultSet rs = pstmt.executeQuery();
221-
while (rs.next()) {
222-
standaloneList.add(rs.getLong(1));
219+
try(ResultSet rs = pstmt.executeQuery();) {
220+
while (rs.next()) {
221+
standaloneList.add(rs.getLong(1));
222+
}
223+
}catch (SQLException e) {
224+
throw new CloudRuntimeException("Unable to execute " + sql, e);
223225
}
224226
} catch (SQLException e) {
225227
throw new CloudRuntimeException("Unable to execute " + sql, e);
@@ -231,23 +233,26 @@ public List<Long> findJobsToWake(long joinedJobId) {
231233
public List<Long> findJobsToWakeBetween(Date cutDate) {
232234
List<Long> standaloneList = new ArrayList<Long>();
233235
TransactionLegacy txn = TransactionLegacy.currentTxn();
234-
try {
235-
String sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
236-
PreparedStatement pstmt = txn.prepareStatement(sql);
236+
String sql = "SELECT job_id FROM async_job_join_map WHERE next_wakeup < ? AND expiration > ? AND job_id NOT IN (SELECT content_id FROM sync_queue_item)";
237+
try (PreparedStatement pstmt = txn.prepareStatement(sql);){
237238
pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
238239
pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
239-
ResultSet rs = pstmt.executeQuery();
240-
while (rs.next()) {
241-
standaloneList.add(rs.getLong(1));
240+
try(ResultSet rs = pstmt.executeQuery();) {
241+
while (rs.next()) {
242+
standaloneList.add(rs.getLong(1));
243+
}
244+
}catch (SQLException e) {
245+
throw new CloudRuntimeException("Unable to handle SQL exception", e);
242246
}
243-
244247
// update for next wake-up
245248
sql = "UPDATE async_job_join_map SET next_wakeup=DATE_ADD(next_wakeup, INTERVAL wakeup_interval SECOND) WHERE next_wakeup < ? AND expiration > ?";
246-
pstmt = txn.prepareStatement(sql);
247-
pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
248-
pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
249-
pstmt.executeUpdate();
250-
249+
try(PreparedStatement update_pstmt = txn.prepareStatement(sql);) {
250+
update_pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
251+
update_pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutDate));
252+
update_pstmt.executeUpdate();
253+
}catch (SQLException e) {
254+
throw new CloudRuntimeException("Unable to handle SQL exception", e);
255+
}
251256
return standaloneList;
252257
} catch (SQLException e) {
253258
throw new CloudRuntimeException("Unable to handle SQL exception", e);

0 commit comments

Comments
 (0)