Skip to content

Commit 4e2e1be

Browse files
author
Vincent Potucek
committed
use try-with-resources statement
1 parent 2e086bd commit 4e2e1be

File tree

11 files changed

+50
-121
lines changed

11 files changed

+50
-121
lines changed

spring-context-support/src/main/java/org/springframework/mail/javamail/JavaMailSenderImpl.java

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -342,14 +342,7 @@ public void send(MimeMessage... mimeMessages) throws MailException {
342342
* for. Throws a {@link MessagingException} if the connection attempt failed.
343343
*/
344344
public void testConnection() throws MessagingException {
345-
Transport transport = null;
346-
try {
347-
transport = connectTransport();
348-
}
349-
finally {
350-
if (transport != null) {
351-
transport.close();
352-
}
345+
try (Transport ignored = connectTransport()) {
353346
}
354347
}
355348

spring-core/src/main/java/org/springframework/cglib/core/DuplicatesPredicate.java

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -89,14 +89,12 @@ public DuplicatesPredicate(List allMethods) {
8989
continue;
9090
}
9191
InputStream is = cl.getResourceAsStream(c.getName().replace('.', '/') + ".class");
92-
if (is == null) {
93-
continue;
94-
}
95-
try {
96-
new ClassReader(is).accept(finder, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
97-
} finally {
98-
is.close();
99-
}
92+
try (is) {
93+
if (is == null) {
94+
continue;
95+
}
96+
new ClassReader(is).accept(finder, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
97+
}
10098
} catch (IOException ignored) {
10199
}
102100
}

spring-core/src/main/java/org/springframework/cglib/proxy/BridgeMethodResolver.java

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,14 @@ public BridgeMethodResolver(Map declToBridge, ClassLoader classLoader) {
6363
Set bridges = (Set) entry.getValue();
6464
try {
6565
InputStream is = classLoader.getResourceAsStream(owner.getName().replace('.', '/') + ".class");
66-
if (is == null) {
67-
return resolved;
68-
}
69-
try {
70-
new ClassReader(is)
71-
.accept(new BridgedFinder(bridges, resolved),
72-
ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
73-
} finally {
74-
is.close();
75-
}
66+
try (is) {
67+
if (is == null) {
68+
return resolved;
69+
}
70+
new ClassReader(is)
71+
.accept(new BridgedFinder(bridges, resolved),
72+
ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
73+
}
7674
} catch (IOException ignored) {}
7775
}
7876
return resolved;

spring-core/src/main/java/org/springframework/cglib/transform/AbstractClassLoader.java

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -61,20 +61,16 @@ public Class loadClass(String name) throws ClassNotFoundException {
6161
name.replace('.','/') + ".class"
6262
);
6363

64-
if (is == null) {
64+
try (is) {
65+
if (is == null) {
6566

66-
throw new ClassNotFoundException(name);
67+
throw new ClassNotFoundException(name);
6768

68-
}
69-
try {
69+
}
7070

71-
r = new ClassReader(is);
71+
r = new ClassReader(is);
7272

73-
} finally {
74-
75-
is.close();
76-
77-
}
73+
}
7874
} catch (IOException e) {
7975
throw new ClassNotFoundException(name + ":" + e.getMessage());
8076
}

spring-core/src/main/java/org/springframework/core/io/AbstractResource.java

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -153,8 +153,7 @@ public ReadableByteChannel readableChannel() throws IOException {
153153
*/
154154
@Override
155155
public long contentLength() throws IOException {
156-
InputStream is = getInputStream();
157-
try {
156+
try (InputStream is = getInputStream()) {
158157
long size = 0;
159158
byte[] buf = new byte[256];
160159
int read;
@@ -163,14 +162,6 @@ public long contentLength() throws IOException {
163162
}
164163
return size;
165164
}
166-
finally {
167-
try {
168-
is.close();
169-
}
170-
catch (IOException ex) {
171-
debug(() -> "Could not close content-length InputStream for " + getDescription(), ex);
172-
}
173-
}
174165
}
175166

176167
/**

spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/AbstractEmbeddedDatabaseConfigurer.java

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -40,31 +40,15 @@ abstract class AbstractEmbeddedDatabaseConfigurer implements EmbeddedDatabaseCon
4040

4141
@Override
4242
public void shutdown(DataSource dataSource, String databaseName) {
43-
Connection con = null;
44-
try {
45-
con = dataSource.getConnection();
43+
try (Connection con = dataSource.getConnection()) {
4644
if (con != null) {
4745
try (Statement stmt = con.createStatement()) {
4846
stmt.execute("SHUTDOWN");
4947
}
5048
}
51-
}
52-
catch (SQLException ex) {
49+
} catch (SQLException ex) {
5350
logger.info("Could not shut down embedded database", ex);
5451
}
55-
finally {
56-
if (con != null) {
57-
try {
58-
con.close();
59-
}
60-
catch (SQLException ex) {
61-
logger.debug("Could not close JDBC Connection on shutdown", ex);
62-
}
63-
catch (Throwable ex) {
64-
logger.debug("Unexpected exception on closing JDBC Connection", ex);
65-
}
66-
}
67-
}
6852
}
6953

7054
}

spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ScriptUtils.java

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -253,8 +253,7 @@ public static void executeSqlScript(Connection connection, EncodedResource resou
253253
blockCommentEndDelimiter, statements);
254254

255255
int stmtNumber = 0;
256-
Statement stmt = connection.createStatement();
257-
try {
256+
try (Statement stmt = connection.createStatement()) {
258257
for (String statement : statements) {
259258
stmtNumber++;
260259
try {
@@ -270,27 +269,19 @@ public static void executeSqlScript(Connection connection, EncodedResource resou
270269
warningToLog = warningToLog.getNextWarning();
271270
}
272271
}
273-
}
274-
catch (SQLException ex) {
272+
} catch (SQLException ex) {
275273
boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
276274
if (continueOnError || (dropStatement && ignoreFailedDrops)) {
277275
if (logger.isDebugEnabled()) {
278276
logger.debug(ScriptStatementFailedException.buildErrorMessage(statement, stmtNumber, resource), ex);
279277
}
280-
}
281-
else {
278+
} else {
282279
throw new ScriptStatementFailedException(statement, stmtNumber, resource, ex);
283280
}
284281
}
285282
}
286-
}
287-
finally {
288-
try {
289-
stmt.close();
290-
}
291-
catch (Throwable ex) {
292-
logger.trace("Could not close JDBC Statement", ex);
293-
}
283+
} catch (Throwable ex) {
284+
logger.trace("Could not close JDBC Statement", ex);
294285
}
295286

296287
long elapsedTime = System.currentTimeMillis() - startTime;

spring-jms/src/main/java/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.java

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -316,21 +316,19 @@ protected boolean doReceiveAndExecute(Object invoker, @Nullable Session session,
316316
boolean exposeResource = (!transactional && isExposeListenerSession() &&
317317
!TransactionSynchronizationManager.hasResource(obtainConnectionFactory()));
318318
Observation observation = createObservation(message).start();
319-
Observation.Scope scope = observation.openScope();
320-
if (logger.isDebugEnabled()) {
321-
logger.debug("Received message of type [" + message.getClass() + "] from consumer [" +
322-
consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" +
323-
sessionToUse + "]");
324-
}
325-
try {
319+
try (Observation.Scope ignored = observation.openScope()) {
320+
if (logger.isDebugEnabled()) {
321+
logger.debug("Received message of type [" + message.getClass() + "] from consumer [" +
322+
consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" +
323+
sessionToUse + "]");
324+
}
326325
messageReceived(invoker, sessionToUse);
327326
if (exposeResource) {
328327
TransactionSynchronizationManager.bindResource(
329328
obtainConnectionFactory(), new LocallyExposedJmsResourceHolder(sessionToUse));
330329
}
331330
doExecuteListener(sessionToUse, message);
332-
}
333-
catch (Throwable ex) {
331+
} catch (Throwable ex) {
334332
if (status != null) {
335333
if (logger.isDebugEnabled()) {
336334
logger.debug("Rolling back transaction because of listener exception thrown: " + ex);
@@ -339,8 +337,7 @@ protected boolean doReceiveAndExecute(Object invoker, @Nullable Session session,
339337
}
340338
try {
341339
handleListenerException(ex);
342-
}
343-
catch (Throwable throwable) {
340+
} catch (Throwable throwable) {
344341
observation.error(throwable);
345342
throw throwable;
346343
}
@@ -349,13 +346,11 @@ protected boolean doReceiveAndExecute(Object invoker, @Nullable Session session,
349346
if (ex instanceof JMSException jmsException) {
350347
throw jmsException;
351348
}
352-
}
353-
finally {
349+
} finally {
354350
if (exposeResource) {
355351
TransactionSynchronizationManager.unbindResource(obtainConnectionFactory());
356352
}
357353
observation.stop();
358-
scope.close();
359354
}
360355
// Indicate that a message has been received.
361356
return true;

spring-orm/src/test/java/org/springframework/orm/jpa/hibernate/HibernateMultiEntityManagerFactoryIntegrationTests.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,10 @@ protected void testEntityManagerFactoryImplementsEntityManagerFactoryInfo() {
5858

5959
@Test
6060
void testEntityManagerFactory2() {
61-
EntityManager em = this.entityManagerFactory2.createEntityManager();
62-
try {
61+
try (EntityManager em = this.entityManagerFactory2.createEntityManager()) {
6362
assertThatIllegalArgumentException().isThrownBy(() ->
6463
em.createQuery("select tb from TestBean"));
6564
}
66-
finally {
67-
em.close();
68-
}
6965
}
7066

7167
}

spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -152,22 +152,16 @@ protected void writeContent(Resource resource, HttpOutputMessage outputMessage)
152152
// We cannot use try-with-resources here for the InputStream, since we have
153153
// custom handling of the close() method in a finally-block.
154154
try {
155-
InputStream in = resource.getInputStream();
156-
try {
157-
OutputStream out = outputMessage.getBody();
158-
in.transferTo(out);
159-
out.flush();
160-
}
161-
catch (NullPointerException ex) {
162-
// ignore, see SPR-13620
163-
}
164-
finally {
155+
try (InputStream in = resource.getInputStream()) {
165156
try {
166-
in.close();
167-
}
168-
catch (Throwable ex) {
169-
// ignore, see SPR-12999
157+
OutputStream out = outputMessage.getBody();
158+
in.transferTo(out);
159+
out.flush();
160+
} catch (NullPointerException ex) {
161+
// ignore, see SPR-13620
170162
}
163+
} catch (Throwable ex) {
164+
// ignore, see SPR-12999
171165
}
172166
}
173167
catch (FileNotFoundException ex) {

0 commit comments

Comments
 (0)