Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6674: Use try-with-resource in more places and close un-closed resources #33

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter...
Filter file types
Jump to…
Jump to file
Failed to load files.

Always

Just for now

@@ -92,8 +92,9 @@
private static void initPluginService(File file) throws IOException {
String[] files = file.list();
if (files != null && files.length > 0) {
pluginService = ServiceLoader.load(JConsolePlugin.class,
new URLClassLoader(getURLs(file), Activator.class.getClassLoader()));
try (URLClassLoader loader = new URLClassLoader(getURLs(file), Activator.class.getClassLoader())) {
pluginService = ServiceLoader.load(JConsolePlugin.class, loader);
}
}
}

@@ -181,11 +181,8 @@ protected IStatus run(IProgressMonitor monitor) {
private File dumpFile(
IProgressMonitor monitor, IFlightRecorderService service, IRecordingDescriptor descriptor, MCFile path)
throws IOException, FlightRecorderException {
InputStream stream = service.openStream(descriptor, false);
try {
try (InputStream stream = service.openStream(descriptor, false)) {
return IDESupportToolkit.writeToUniqueFile(path, stream, monitor);
} finally {
IOToolkit.closeSilently(stream);
}
}

@@ -121,11 +121,8 @@ private IRecordingDescriptor findRecording() throws FlightRecorderException {

private File writeFile(IProgressMonitor monitor, IRecordingDescriptor descriptor, IQuantity duration)
throws FlightRecorderException, IOException {
InputStream stream = service.openStream(descriptor, duration, false);
try {
try (InputStream stream = service.openStream(descriptor, duration, false)) {
return IDESupportToolkit.writeToUniqueFile(path, stream, monitor);
} finally {
IOToolkit.closeSilently(stream);
}
}
}
@@ -103,11 +103,10 @@ public static NotificationRegistry getDefaultModel() {
* successfully
*/
public static IStatus resetTriggers(NotificationRegistry model) {
InputStream stream = null;
try {
// Load DOM for default triggers
stream = NotificationPlugin.class.getResourceAsStream(NotificationPlugin.DEFAULT_TRIGGER_FILE);
Document doc = XmlToolkit.loadDocumentFromStream(new BufferedInputStream(stream));
// Load DOM for default triggers
try (InputStream stream = NotificationPlugin.class.getResourceAsStream(NotificationPlugin.DEFAULT_TRIGGER_FILE);
BufferedInputStream bis = new BufferedInputStream(stream)) {
Document doc = XmlToolkit.loadDocumentFromStream(bis);
Collection<TriggerRule> c = model.getAvailableRules();

// Remove all rules
@@ -124,8 +123,6 @@ public static IStatus resetTriggers(NotificationRegistry model) {
} catch (Exception exc) {
return StatusFactory.createErr(NLS.bind(Messages.TriggerToolkit_ERROR_COULD_NOT_READ_DEFAULT_TEMPLATE_FILE,
NotificationPlugin.DEFAULT_TRIGGER_FILE), exc, false);
} finally {
IOToolkit.closeSilently(stream);
}
return StatusFactory.createOk(Messages.TriggerToolkit_MESSAGE_DEFAULT_TRIGGERS_LOADED);
}
@@ -259,9 +259,10 @@ public void saveToFile(File file) throws IOException {
// NOTE: The pretty printer writes that the encoding is UTF-8, so we must make sure it is.
// Ensure charset exists before opening file for writing.
Charset charset = Charset.forName("UTF-8"); //$NON-NLS-1$
Writer osw = new OutputStreamWriter(new FileOutputStream(file), charset);
if (writeTo(osw)) {
setDirty(false);
try (Writer osw = new OutputStreamWriter(new FileOutputStream(file), charset)) {
if (writeTo(osw)) {
setDirty(false);
}
}
}

@@ -275,15 +276,12 @@ public void saveToFile(File file) throws IOException {
* @return true iff the model was successfully written to the {@link Writer}.
*/
public boolean writeTo(Writer writer) {
PrintWriter pw = new PrintWriter(writer);
try {
try (PrintWriter pw = new PrintWriter(writer)) {
PrettyPrinter pp = new PrettyPrinter(pw, m_validator.getElementsTooKeepOnOneLine());
pp.print(this);
pw.flush();
// PrintWriter never throws any exceptions, so this is how we find out if something went wrong.
return !pw.checkError();
} finally {
IOToolkit.closeSilently(pw);
}
}

@@ -62,9 +62,8 @@ public DumpAnyRecordingAction(FlightRecorderProvider flightRecorderProvider) {

@Override
public IWizard doCreateWizard() throws Exception {
IConnectionHandle handle = null;
try {
handle = flightRecorder.getServerHandle().connect(Messages.ACTION_DUMP_ANY_RECORDING_LABEL);
try (IConnectionHandle handle = flightRecorder.getServerHandle()
.connect(Messages.ACTION_DUMP_ANY_RECORDING_LABEL)) {
RecordingProvider recording = flightRecorder.getSnapshotRecording(handle);
if (recording != null) {
flightRecorder.resetWarning();
@@ -77,8 +76,6 @@ public IWizard doCreateWizard() throws Exception {
} catch (Exception e) {
flightRecorder.setWarning(e.getLocalizedMessage());
throw e;
} finally {
IOToolkit.closeSilently(handle);
}
}

@@ -34,7 +34,6 @@

import org.eclipse.jface.wizard.IWizard;

import org.openjdk.jmc.common.io.IOToolkit;
import org.openjdk.jmc.flightrecorder.controlpanel.ui.ControlPanel;
import org.openjdk.jmc.flightrecorder.controlpanel.ui.ImageConstants;
import org.openjdk.jmc.flightrecorder.controlpanel.ui.RecordingProvider;
@@ -60,14 +59,10 @@ public EditRecordingAction(RecordingProvider recording) {

@Override
public IWizard doCreateWizard() throws Exception {
IConnectionHandle connection = null;
try {
connection = recording.getServerHandle().connect(Messages.ACTION_EDIT_RECORDING_LABEL);
try (IConnectionHandle connection = recording.getServerHandle().connect(Messages.ACTION_EDIT_RECORDING_LABEL)) {
return new EditRecordingWizard(recording,
new RecordingWizardModel(connection.getServiceOrThrow(IFlightRecorderService.class),
recording.getRecordingDescriptor(), recording.getDumpToFile()));
} finally {
IOToolkit.closeSilently(connection);
}
}

@@ -60,9 +60,7 @@ public StartRecordingAction(FlightRecorderProvider recorder) {

@Override
public IWizard doCreateWizard() throws Exception {
IConnectionHandle handle = null;
try {
handle = recorder.getServerHandle().connect(Messages.ACTION_START_RECORDING_LABEL);
try (IConnectionHandle handle = recorder.getServerHandle().connect(Messages.ACTION_START_RECORDING_LABEL)) {
IFlightRecorderService flrService = handle.getServiceOrNull(IFlightRecorderService.class);
if (flrService == null) {
throw new FlightRecorderException(JVMSupportToolkit.getNoFlightRecorderErrorMessage(handle, false));
@@ -78,8 +76,6 @@ public IWizard doCreateWizard() throws Exception {
} catch (Exception e) {
recorder.setWarning(e.getLocalizedMessage());
throw e;
} finally {
IOToolkit.closeSilently(handle);
}
}

@@ -69,9 +69,7 @@ public UpdateRecordingJob(IServerHandle server, IRecordingDescriptor recordingDe

@Override
protected IStatus run(IProgressMonitor monitor) {
IConnectionHandle connection = null;
try {
connection = m_server.connect(getName());
try (IConnectionHandle connection = m_server.connect(getName())) {
IFlightRecorderService flightRecorderService = connection.getServiceOrThrow(IFlightRecorderService.class);
flightRecorderService.updateRecordingOptions(m_recordingDescriptor, m_recordingOptions);
flightRecorderService.updateEventOptions(m_recordingDescriptor, m_recordingSettings);
@@ -80,8 +78,6 @@ protected IStatus run(IProgressMonitor monitor) {
ControlPanel.getDefault().getLogger().log(Level.WARNING, "Could not update recording", e); //$NON-NLS-1$
return StatusFactory.createErr(
NLS.bind(Messages.UPDATE_RECORDING_JOB_SERVICE_ERROR_MSG, m_recordingDescriptor.getName()));
} finally {
IOToolkit.closeSilently(connection);
}
}
}
@@ -112,18 +112,15 @@

public static void validate(InputStream xmlStream, String streamName, SchemaVersion version)
throws ParseException, IOException {
InputStream schemaStream = version.createSchemaStream();
if (schemaStream != null) {
try {
try (InputStream schemaStream = version.createSchemaStream()) {
if (schemaStream != null) {
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); //$NON-NLS-1$
XMLModel.validate(xmlStream, streamName, schemaFactory.newSchema(new StreamSource(schemaStream)));
} catch (SAXException e) {
throw new IOException("Trouble parsing schema for version " + version, e); //$NON-NLS-1$
} finally {
IOToolkit.closeSilently(schemaStream);
} else {
throw new IOException("Could not locate schema for version " + version); //$NON-NLS-1$
}
} else {
throw new IOException("Could not locate schema for version " + version); //$NON-NLS-1$
} catch (SAXException e) {
throw new IOException("Trouble parsing schema for version " + version, e); //$NON-NLS-1$
}
}

@@ -141,7 +138,9 @@ public static XMLModel createModel(String xmlText) throws ParseException, IOExce
}

public static XMLModel createModel(File file) throws FileNotFoundException, IOException, ParseException {
return createModel(new FileInputStream(file));
try (FileInputStream fis = new FileInputStream(file)) {
return createModel(fis);
}
}

public static XMLModel createModel(InputStream inStream) throws IOException, ParseException {
@@ -90,12 +90,9 @@ public boolean save(String fileContent) throws IOException {
try {
// Ensure charset exists before opening file for writing.
Charset charset = Charset.forName(CHARSET_UTF8);
Writer out = new OutputStreamWriter(new FileOutputStream(file), charset);
try {
try (Writer out = new OutputStreamWriter(new FileOutputStream(file), charset)) {
out.write(fileContent);
out.flush();
} finally {
IOToolkit.closeSilently(out);
}
return true;
} catch (IllegalCharsetNameException e) {
@@ -166,17 +166,12 @@ public void run() {
Runtime runtime = Runtime.getRuntime();
long availableMemory = runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory();
if (availableMemory > (zippedFileMemoryFactor * file.length())) { // Try load from stream
InputStream stream = IOToolkit.openUncompressedStream(file);
try {
try (InputStream stream = IOToolkit.openUncompressedStream(file)) {
boolean hideExperimentals = !FlightRecorderUI.getDefault().includeExperimentalEventsAndFields();
boolean ignoreTruncatedChunk = FlightRecorderUI.getDefault().allowIncompleteRecordingFile();
return FlightRecordingLoader.loadStream(stream, hideExperimentals, ignoreTruncatedChunk);
} catch (NotEnoughMemoryException e) {
} catch (NotEnoughMemoryException | OutOfMemoryError e) {
// Try to load part of the file
} catch (OutOfMemoryError e) {
// Try to load part of the file
} finally {
IOToolkit.closeSilently(stream);
}
}
String fileName = file.getName();
@@ -257,12 +252,9 @@ private File unzipFile(File file) throws IOException {
boolean acceptUnzip = DialogToolkit.openQuestionOnUiThread(Messages.FILE_OPENER_ZIPPED_FILE_TITLE, MessageFormat
.format(Messages.FILE_OPENER_ZIPPED_FILE_TEXT, file.getName(), unzippedFile.getAbsolutePath()));
if (acceptUnzip) {
InputStream is = IOToolkit.openUncompressedStream(file);
try {
try (InputStream is = IOToolkit.openUncompressedStream(file)) {
IOToolkit.write(is, unzippedFile, false);
return unzippedFile;
} finally {
IOToolkit.closeSilently(is);
}
} else {
throw new OperationCanceledException();
@@ -240,9 +240,7 @@ public void handleDebugEvents(DebugEvent[] events) {
}

protected void scheduleOpenJfrJob() {
FileInputStream stream = null;
try {
stream = new FileInputStream(recordingFile);
try (FileInputStream stream = new FileInputStream(recordingFile)) {
boolean wrote = jfrPathToOpen.tryWriteStream(stream, null);
if (wrote) {
String info = recordingFile.getAbsolutePath() + " was written to " + jfrPathToOpen.getPath() //$NON-NLS-1$
@@ -252,8 +250,6 @@ protected void scheduleOpenJfrJob() {
WorkbenchToolkit.asyncOpenEditor(new MCPathEditorInput(recordingFile, false));
return;
} catch (IOException e) {
} finally {
IOToolkit.closeSilently(stream);
}
displayErrorMessage(NLS.bind(Messages.JfrLaunch_JFR_FILE_DID_NOT_EXIST, jfrPathToOpen));
}
@@ -60,7 +60,6 @@
import org.eclipse.jdt.launching.IVMInstall2;
import org.eclipse.jdt.launching.JavaRuntime;

import org.openjdk.jmc.common.io.IOToolkit;
import org.openjdk.jmc.common.unit.QuantityConversionException;
import org.openjdk.jmc.common.version.JavaVersion;
import org.openjdk.jmc.common.version.JavaVersionSupport;
@@ -326,28 +325,20 @@ private String getJREVersion(ILaunchConfiguration configuration, File theJreRoot
}

private static String parseJavaVersionFromJre(File theJreRoot) {
FileInputStream fis = null;
JarInputStream jis = null;
try {
File rtJar = new File(theJreRoot, "jre/lib/rt.jar"); //$NON-NLS-1$
if (!rtJar.exists()) {
rtJar = new File(theJreRoot, "lib/rt.jar"); //$NON-NLS-1$
}
if (rtJar.exists()) {
fis = new FileInputStream(rtJar);
jis = new JarInputStream(fis);
File rtJar = new File(theJreRoot, "jre/lib/rt.jar"); //$NON-NLS-1$
if (!rtJar.exists()) {
rtJar = new File(theJreRoot, "lib/rt.jar"); //$NON-NLS-1$
}
if (rtJar.exists()) {
try (FileInputStream fis = new FileInputStream(rtJar); JarInputStream jis = new JarInputStream(fis)) {
Manifest mf = jis.getManifest();
jis.close();
Attributes as = mf.getMainAttributes();
String impVer = as.getValue("Implementation-Version"); //$NON-NLS-1$
if (impVer != null) {
return new JavaVersion(impVer).toString();
}
} catch (IOException e) {
}
} catch (IOException e) {
} finally {
IOToolkit.closeSilently(jis);
IOToolkit.closeSilently(fis);
}
return null;
}
@@ -168,9 +168,7 @@ public ReadBuffer create(Object supplementalInfo) throws IOException {
} finally {
IOToolkit.closeSilently(ch);
IOToolkit.closeSilently(file);

}

return new FileReadBuffer(file);
}
}
@@ -107,11 +107,8 @@ public static void writeTextToFile(File file, List<String> lines) throws IOExcep
}

public static void writeBytesToFile(File file, byte[] bytes) throws IOException {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
out.write(bytes);
} finally {
IOToolkit.closeSilently(out);
}
}

@@ -104,8 +104,10 @@ public static void initializeLogging() {
} else {
try {
if (new File(file).exists()) {
readConfiguration(new FileInputStream(file));
getLogger().log(Level.INFO, "Loaded user specified logging settings from " + file + "."); //$NON-NLS-1$ //$NON-NLS-2$
try (FileInputStream fis = new FileInputStream(file)) {
readConfiguration(fis);
getLogger().log(Level.INFO, "Loaded user specified logging settings from " + file + "."); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
getLogger().log(Level.WARNING, "Could not find user specified logging settings at " + file + "."); //$NON-NLS-1$ //$NON-NLS-2$
}
@@ -145,13 +147,10 @@ private static void readConfiguration(InputStream resourceAsStream) throws Secur
}

private static InputStream getAsInputStream(Properties props) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
props.store(baos, ""); //$NON-NLS-1$
String newProps = baos.toString();
return new ByteArrayInputStream(newProps.getBytes("UTF-8")); //$NON-NLS-1$
} finally {
IOToolkit.closeSilently(baos);
}
}

ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.