This commit is based off a patch submitted by admin@int3solutions.com.
It fixes several locations in the code where there are potential resource leaks.
This commit is contained in:
Christopher L. Shannon (cshannon) 2015-06-22 18:34:37 +00:00 committed by Timothy Bish
parent 1b493749a1
commit 12b26b641b
21 changed files with 273 additions and 243 deletions

View File

@ -273,15 +273,17 @@ public class BrokerService implements Service {
}
LOCAL_HOST_NAME = localHostName;
InputStream in = null;
String version = null;
if ((in = BrokerService.class.getResourceAsStream("/org/apache/activemq/version.txt")) != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
try(InputStream in = BrokerService.class.getResourceAsStream("/org/apache/activemq/version.txt")) {
if (in != null) {
try(InputStreamReader isr = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(isr)) {
version = reader.readLine();
} catch(Exception e) {
}
}
} catch (IOException ie) {
LOG.warn("Error reading broker version ", ie);
}
BROKER_VERSION = version;
}

View File

@ -38,7 +38,7 @@ public class PropertiesBrokerFactory implements BrokerFactoryHandler {
public BrokerService createBroker(URI brokerURI) throws Exception {
Map properties = loadProperties(brokerURI);
Map<Object, Object> properties = loadProperties(brokerURI);
BrokerService brokerService = createBrokerService(brokerURI, properties);
IntrospectionSupport.setProperties(brokerService, properties);
@ -48,14 +48,31 @@ public class PropertiesBrokerFactory implements BrokerFactoryHandler {
/**
* Lets load the properties from some external URL or a relative file
*/
protected Map loadProperties(URI brokerURI) throws IOException {
protected Map<Object, Object> loadProperties(URI brokerURI) throws IOException {
// lets load a URI
String remaining = brokerURI.getSchemeSpecificPart();
Properties properties = new Properties();
File file = new File(remaining);
try (InputStream inputStream = loadStream(file, remaining)) {
if (inputStream != null) {
properties.load(inputStream);
}
}
// should we append any system properties?
try {
Properties systemProperties = System.getProperties();
properties.putAll(systemProperties);
} catch (Exception e) {
// ignore security exception
}
return properties;
}
protected InputStream loadStream(File file, String remaining) throws IOException {
InputStream inputStream = null;
if (file.exists()) {
if (file != null && file.exists()) {
inputStream = new FileInputStream(file);
} else {
URL url = null;
@ -72,19 +89,7 @@ public class PropertiesBrokerFactory implements BrokerFactoryHandler {
inputStream = url.openStream();
}
}
if (inputStream != null) {
properties.load(inputStream);
inputStream.close();
}
// should we append any system properties?
try {
Properties systemProperties = System.getProperties();
properties.putAll(systemProperties);
} catch (Exception e) {
// ignore security exception
}
return properties;
return inputStream;
}
protected InputStream findResourceOnClassPath(String remaining) {
@ -95,7 +100,7 @@ public class PropertiesBrokerFactory implements BrokerFactoryHandler {
return answer;
}
protected BrokerService createBrokerService(URI brokerURI, Map properties) {
protected BrokerService createBrokerService(URI brokerURI, Map<Object, Object> properties) {
return new BrokerService();
}
}

View File

@ -281,15 +281,18 @@ public final class IOHelper {
}
public static void copyInputStream(InputStream in, OutputStream out) throws IOException {
try {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int len = in.read(buffer);
while (len >= 0) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
} finally {
in.close();
out.close();
}
}
static {
MAX_DIR_NAME_LENGTH = Integer.getInteger("MaximumDirNameLength", 200);

View File

@ -505,7 +505,13 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
* <CODE>BlobMessage</CODE> object is used to send a message containing
* the <CODE>File</CODE> content. Before the message is sent the file
* conent will be uploaded to the broker or some other remote repository
* depending on the {@link #getBlobTransferPolicy()}.
* depending on the {@link #getBlobTransferPolicy()}. <br/>
* <p>
* The caller of this method is responsible for closing the
* input stream that is used, however the stream can not be closed
* until <b>after</b> the message has been sent. To have this class
* manage the stream and close it automatically, use the method
* {@link ActiveMQSession#createBlobMessage(File)}
*
* @param in the stream to be uploaded to some remote repo (or the broker)
* depending on the strategy

View File

@ -130,7 +130,7 @@ public class ActiveMQSslConnectionFactory extends ActiveMQConnectionFactory {
KeyStore trustedCertStore = KeyStore.getInstance(getTrustStoreType());
if (trustStore != null) {
InputStream tsStream = getInputStream(trustStore);
try(InputStream tsStream = getInputStream(trustStore)) {
trustedCertStore.load(tsStream, trustStorePassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
@ -138,6 +138,7 @@ public class ActiveMQSslConnectionFactory extends ActiveMQConnectionFactory {
tmf.init(trustedCertStore);
trustStoreManagers = tmf.getTrustManagers();
}
}
return trustStoreManagers;
}
@ -149,12 +150,13 @@ public class ActiveMQSslConnectionFactory extends ActiveMQConnectionFactory {
byte[] sslCert = loadClientCredential(keyStore);
if (sslCert != null && sslCert.length > 0) {
ByteArrayInputStream bin = new ByteArrayInputStream(sslCert);
try(ByteArrayInputStream bin = new ByteArrayInputStream(sslCert)) {
ks.load(bin, keyStorePassword.toCharArray());
kmf.init(ks, keyStoreKeyPassword !=null ? keyStoreKeyPassword.toCharArray() : keyStorePassword.toCharArray());
keystoreManagers = kmf.getKeyManagers();
}
}
}
return keystoreManagers;
}
@ -162,17 +164,17 @@ public class ActiveMQSslConnectionFactory extends ActiveMQConnectionFactory {
if (fileName == null) {
return null;
}
InputStream in = getInputStream(fileName);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try(InputStream in = getInputStream(fileName);
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] buf = new byte[512];
int i = in.read(buf);
while (i > 0) {
out.write(buf, 0, i);
i = in.read(buf);
}
in.close();
return out.toByteArray();
}
}
protected InputStream getInputStream(String urlOrResource) throws IOException {
try {

View File

@ -40,7 +40,9 @@ public class DefaultBlobUploadStrategy extends DefaultStrategy implements BlobUp
}
public URL uploadFile(ActiveMQBlobMessage message, File file) throws JMSException, IOException {
return uploadStream(message, new FileInputStream(file));
try(FileInputStream fis = new FileInputStream(file)) {
return uploadStream(message, fis);
}
}
public URL uploadStream(ActiveMQBlobMessage message, InputStream fis) throws JMSException, IOException {
@ -55,15 +57,13 @@ public class DefaultBlobUploadStrategy extends DefaultStrategy implements BlobUp
// (chunked mode not supported before JRE 1.5)
connection.setChunkedStreamingMode(transferPolicy.getBufferSize());
OutputStream os = connection.getOutputStream();
try(OutputStream os = connection.getOutputStream()) {
byte[] buf = new byte[transferPolicy.getBufferSize()];
for (int c = fis.read(buf); c != -1; c = fis.read(buf)) {
os.write(buf, 0, c);
os.flush();
}
os.close();
fis.close();
}
if (!isSuccessfulCode(connection.getResponseCode())) {
throw new IOException("PUT was not successful: " + connection.getResponseCode() + " "

View File

@ -39,7 +39,9 @@ public class FTPBlobUploadStrategy extends FTPStrategy implements BlobUploadStra
@Override
public URL uploadFile(ActiveMQBlobMessage message, File file) throws JMSException, IOException {
return uploadStream(message, new FileInputStream(file));
try(FileInputStream fis = new FileInputStream(file)) {
return uploadStream(message, fis);
}
}
@Override

View File

@ -65,7 +65,9 @@ public class FileSystemBlobStrategy implements BlobUploadStrategy, BlobDownloadS
* @see org.apache.activemq.blob.BlobUploadStrategy#uploadFile(org.apache.activemq.command.ActiveMQBlobMessage, java.io.File)
*/
public URL uploadFile(ActiveMQBlobMessage message, File file) throws JMSException, IOException {
return uploadStream(message, new FileInputStream(file));
try(FileInputStream fis = new FileInputStream(file)) {
return uploadStream(message, fis);
}
}
/*
@ -74,14 +76,13 @@ public class FileSystemBlobStrategy implements BlobUploadStrategy, BlobDownloadS
*/
public URL uploadStream(ActiveMQBlobMessage message, InputStream in) throws JMSException, IOException {
File f = getFile(message);
FileOutputStream out = new FileOutputStream(f);
try(FileOutputStream out = new FileOutputStream(f)) {
byte[] buffer = new byte[policy.getBufferSize()];
for (int c = in.read(buffer); c != -1; c = in.read(buffer)) {
out.write(buffer, 0, c);
out.flush();
}
out.flush();
out.close();
}
// File.toURL() is deprecated
return f.toURI().toURL();
}

View File

@ -191,9 +191,10 @@ public class CreateCommand extends AbstractCommand {
buf.put(data.getBytes());
buf.flip();
FileChannel destinationChannel = new FileOutputStream(dest).getChannel();
try(FileOutputStream fos = new FileOutputStream(dest);
FileChannel destinationChannel = fos.getChannel()) {
destinationChannel.write(buf);
destinationChannel.close();
}
// Set file permissions available for Java 6.0 only
dest.setExecutable(true);
@ -215,11 +216,13 @@ public class CreateCommand extends AbstractCommand {
if (!from.exists()) {
return;
}
FileChannel sourceChannel = new FileInputStream(from).getChannel();
FileChannel destinationChannel = new FileOutputStream(dest).getChannel();
try(FileInputStream fis = new FileInputStream(from);
FileChannel sourceChannel = fis.getChannel();
FileOutputStream fos = new FileOutputStream(dest);
FileChannel destinationChannel = fos.getChannel()) {
sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
sourceChannel.close();
destinationChannel.close();
}
}
private void copyConfDirectory(File from, File dest) throws IOException {

View File

@ -105,15 +105,18 @@ public final class IOHelper {
}
public static void copyInputStream(InputStream in, OutputStream out) throws IOException {
try {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int len = in.read(buffer);
while (len >= 0) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
} finally {
in.close();
out.close();
}
}
static {
MAX_DIR_NAME_LENGTH = Integer.valueOf(System.getProperty("MaximumDirNameLength","200")).intValue();

View File

@ -88,10 +88,8 @@ public class TextFileCertificateLoginModule extends CertificateLoginModule {
Properties users = new Properties();
try {
java.io.FileInputStream in = new java.io.FileInputStream(usersFile);
try(java.io.FileInputStream in = new java.io.FileInputStream(usersFile)) {
users.load(in);
in.close();
} catch (IOException ioe) {
throw new LoginException("Unable to load user properties file " + usersFile);
}

View File

@ -139,18 +139,15 @@ public class BlobJDBCAdapter extends DefaultJDBCAdapter {
return null;
}
Blob blob = rs.getBlob(1);
InputStream is = blob.getBinaryStream();
ByteArrayOutputStream os = new ByteArrayOutputStream((int)blob.length());
try(InputStream is = blob.getBinaryStream();
ByteArrayOutputStream os = new ByteArrayOutputStream((int)blob.length())) {
int ch;
while ((ch = is.read()) >= 0) {
os.write(ch);
}
is.close();
os.close();
return os.toByteArray();
}
} finally {
cleanupExclusiveLock.readLock().unlock();
close(rs);

View File

@ -47,16 +47,13 @@ public class StreamJDBCAdapter extends DefaultJDBCAdapter {
@Override
protected byte[] getBinaryData(ResultSet rs, int index) throws SQLException {
try {
InputStream is = rs.getBinaryStream(index);
ByteArrayOutputStream os = new ByteArrayOutputStream(1024 * 4);
try (InputStream is = rs.getBinaryStream(index);
ByteArrayOutputStream os = new ByteArrayOutputStream(1024 * 4)) {
int ch;
while ((ch = is.read()) >= 0) {
os.write(ch);
}
is.close();
os.close();
return os.toByteArray();
} catch (IOException e) {

View File

@ -196,10 +196,10 @@ public class PageFile {
public byte[] getDiskBound() throws IOException {
if (diskBound == null && diskBoundLocation != -1) {
diskBound = new byte[length];
RandomAccessFile file = new RandomAccessFile(tmpFile, "r");
try(RandomAccessFile file = new RandomAccessFile(tmpFile, "r")) {
file.seek(diskBoundLocation);
file.read(diskBound);
file.close();
}
diskBoundLocation = -1;
}
return diskBound;

View File

@ -16,14 +16,13 @@
*/
package org.apache.activemq.store.kahadb.disk.util;
import org.apache.activemq.util.RecoverableRandomAccessFile;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.activemq.util.RecoverableRandomAccessFile;
/**
* This class is used to get a benchmark the raw disk performance.
*/
@ -203,15 +202,19 @@ public class DiskBenchmark {
for (int i = 0; i < data.length; i++) {
data[i] = (byte) ('a' + (i % 26));
}
rc.size = data.length;
RecoverableRandomAccessFile raf = new RecoverableRandomAccessFile(file, "rw");
long start;
long now;
int ioCount;
try(RecoverableRandomAccessFile raf = new RecoverableRandomAccessFile(file, "rw")) {
preallocateDataFile(raf, file.getParentFile());
start = System.currentTimeMillis();
now = System.currentTimeMillis();
ioCount = 0;
// Figure out how many writes we can do in the sample interval.
long start = System.currentTimeMillis();
long now = System.currentTimeMillis();
int ioCount = 0;
while (true) {
if ((now - start) > sampleInterval) {
break;
@ -230,14 +233,14 @@ public class DiskBenchmark {
raf.getChannel().force(!SKIP_METADATA_UPDATE);
}
raf.getChannel().force(!SKIP_METADATA_UPDATE);
raf.close();
}
now = System.currentTimeMillis();
rc.size = data.length;
rc.writes = ioCount;
rc.writeDuration = (now - start);
raf = new RecoverableRandomAccessFile(file, "rw");
try(RecoverableRandomAccessFile raf = new RecoverableRandomAccessFile(file, "rw")) {
start = System.currentTimeMillis();
now = System.currentTimeMillis();
ioCount = 0;
@ -256,12 +259,12 @@ public class DiskBenchmark {
}
}
}
raf.close();
}
now = System.currentTimeMillis();
rc.syncWrites = ioCount;
rc.syncWriteDuration = (now - start);
raf = new RecoverableRandomAccessFile(file, "rw");
try(RecoverableRandomAccessFile raf = new RecoverableRandomAccessFile(file, "rw")) {
start = System.currentTimeMillis();
now = System.currentTimeMillis();
ioCount = 0;
@ -280,7 +283,7 @@ public class DiskBenchmark {
}
}
}
raf.close();
}
rc.reads = ioCount;
rc.readDuration = (now - start);

View File

@ -84,15 +84,17 @@ public class ProtocolConverter {
private static final StompFrame ping = new StompFrame(Stomp.Commands.KEEPALIVE);
static {
InputStream in = null;
String version = "5.6.0";
if ((in = ProtocolConverter.class.getResourceAsStream("/org/apache/activemq/version.txt")) != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
try(InputStream in = ProtocolConverter.class.getResourceAsStream("/org/apache/activemq/version.txt")) {
if (in != null) {
try(InputStreamReader isr = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(isr)) {
version = reader.readLine();
} catch(Exception e) {
}
}
}catch(Exception e) {
}
BROKER_VERSION = version;
}

View File

@ -294,8 +294,10 @@ public abstract class AbstractJmsClientSystem extends AbstractObjectProperties {
Properties fileProps = new Properties();
try {
if (configFile != null) {
try(FileInputStream inputStream = new FileInputStream(configFile)) {
LOG.info("Loading properties file: " + configFile.getAbsolutePath());
fileProps.load(new FileInputStream(configFile));
fileProps.load(inputStream);
}
}
} catch (IOException e) {
e.printStackTrace();

View File

@ -376,13 +376,14 @@ public class JmsProducerClient extends AbstractJmsMeasurableClient {
}
// try to load file
BufferedReader br = new BufferedReader(new FileReader(f));
StringBuffer payload = new StringBuffer();
try(FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
String tmp = null;
while ((tmp = br.readLine()) != null) {
payload.append(tmp);
}
br.close();
}
jmsTextMessage = getSession().createTextMessage(payload.toString());
return jmsTextMessage;
} catch (FileNotFoundException ex) {

View File

@ -195,7 +195,10 @@ public class XmlFilePerfReportWriter extends AbstractPerfReportWriter {
xmlFileWriter.println("<property name='performanceData'>");
xmlFileWriter.println("<list>");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(tempLogFile)));
try (FileInputStream fileInputStream = new FileInputStream(tempLogFile);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader reader = new BufferedReader(inputStreamReader)) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("[TP-DATA]")) {
@ -210,7 +213,7 @@ public class XmlFilePerfReportWriter extends AbstractPerfReportWriter {
xmlFileWriter.println("<error>" + line + "</error>");
}
}
}
xmlFileWriter.println("</list>");
xmlFileWriter.println("</property>");
}

View File

@ -64,21 +64,21 @@ public class AjaxServlet extends MessageListenerServlet {
byte[] data = jsCache.get(resource);
if (data == null) {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
try(InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource)) {
if (in != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try(ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] buf = new byte[4096];
int len = in.read(buf);
while (len >= 0) {
out.write(buf, 0, len);
len = in.read(buf);
}
in.close();
out.close();
data = out.toByteArray();
jsCache.put(resource, data);
}
}
}
}
if (data != null) {