Commit 32b85e8e authored by Dave Cridland's avatar Dave Cridland

Merge pull request #343 from sco0ter/trywithresources

Use try-with-resources statement to properly close resources.
parents 5fc7a6ac e0bc007f
...@@ -666,10 +666,8 @@ public class DbConnectionManager { ...@@ -666,10 +666,8 @@ public class DbConnectionManager {
*/ */
public static String getLargeTextField(ResultSet rs, int columnIndex) throws SQLException { public static String getLargeTextField(ResultSet rs, int columnIndex) throws SQLException {
if (isStreamTextRequired()) { if (isStreamTextRequired()) {
Reader bodyReader = null; String value;
String value = null; try (Reader bodyReader = rs.getCharacterStream(columnIndex)) {
try {
bodyReader = rs.getCharacterStream(columnIndex);
if (bodyReader == null) { if (bodyReader == null) {
return null; return null;
} }
...@@ -686,16 +684,6 @@ public class DbConnectionManager { ...@@ -686,16 +684,6 @@ public class DbConnectionManager {
Log.error(e.getMessage(), e); Log.error(e.getMessage(), e);
throw new SQLException("Failed to load text field"); throw new SQLException("Failed to load text field");
} }
finally {
try {
if (bodyReader != null) {
bodyReader.close();
}
}
catch (Exception e) {
// Ignore.
}
}
return value; return value;
} }
else { else {
......
...@@ -235,11 +235,11 @@ public class SchemaManager { ...@@ -235,11 +235,11 @@ public class SchemaManager {
// Resource will be like "/database/openfire_hsqldb.sql" // Resource will be like "/database/openfire_hsqldb.sql"
String resourceName = schemaKey + "_" + String resourceName = schemaKey + "_" +
DbConnectionManager.getDatabaseType() + ".sql"; DbConnectionManager.getDatabaseType() + ".sql";
InputStream resource = resourceLoader.loadResource(resourceName);
if (resource == null) { try (InputStream resource = resourceLoader.loadResource(resourceName)) {
return false; if (resource == null) {
} return false;
try { }
// For plugins, we will automatically convert jiveVersion to ofVersion // For plugins, we will automatically convert jiveVersion to ofVersion
executeSQLScript(con, resource, !schemaKey.equals("openfire") && !schemaKey.equals("wildfire")); executeSQLScript(con, resource, !schemaKey.equals("openfire") && !schemaKey.equals("wildfire"));
} }
...@@ -247,14 +247,6 @@ public class SchemaManager { ...@@ -247,14 +247,6 @@ public class SchemaManager {
Log.error(e.getMessage(), e); Log.error(e.getMessage(), e);
return false; return false;
} }
finally {
try {
resource.close();
}
catch (Exception e) {
// Ignore.
}
}
Log.info(LocaleUtils.getLocalizedString("upgrade.database.success")); Log.info(LocaleUtils.getLocalizedString("upgrade.database.success"));
System.out.println(LocaleUtils.getLocalizedString("upgrade.database.success")); System.out.println(LocaleUtils.getLocalizedString("upgrade.database.success"));
return true; return true;
...@@ -281,34 +273,23 @@ public class SchemaManager { ...@@ -281,34 +273,23 @@ public class SchemaManager {
// Run all upgrade scripts until we're up to the latest schema. // Run all upgrade scripts until we're up to the latest schema.
for (int i = currentVersion + 1; i <= requiredVersion; i++) { for (int i = currentVersion + 1; i <= requiredVersion; i++) {
InputStream resource = getUpgradeResource(resourceLoader, i, schemaKey); try (InputStream resource = getUpgradeResource(resourceLoader, i, schemaKey)) {
// apply the 'database-patches-done-in-java'
// apply the 'database-patches-done-in-java'
try {
if (i == 21 && schemaKey.equals("openfire")) {
OF33.executeFix(con);
}
} catch (Exception e) {
Log.error(e.getMessage(), e);
return false;
}
if (resource == null) {
continue;
}
try {
executeSQLScript(con, resource, !schemaKey.equals("openfire") && !schemaKey.equals("wildfire"));
}
catch (Exception e) {
Log.error(e.getMessage(), e);
return false;
}
finally {
try { try {
resource.close(); if (i == 21 && schemaKey.equals("openfire")) {
OF33.executeFix(con);
}
} catch (Exception e) {
Log.error(e.getMessage(), e);
return false;
} }
catch (Exception e) { if (resource == null) {
// Ignore. continue;
} }
executeSQLScript(con, resource, !schemaKey.equals("openfire") && !schemaKey.equals("wildfire"));
} catch (Exception e) {
Log.error(e.getMessage(), e);
return false;
} }
} }
Log.info(LocaleUtils.getLocalizedString("upgrade.database.success")); Log.info(LocaleUtils.getLocalizedString("upgrade.database.success"));
...@@ -371,9 +352,7 @@ public class SchemaManager { ...@@ -371,9 +352,7 @@ public class SchemaManager {
private static void executeSQLScript(Connection con, InputStream resource, Boolean autoreplace) throws IOException, private static void executeSQLScript(Connection con, InputStream resource, Boolean autoreplace) throws IOException,
SQLException SQLException
{ {
BufferedReader in = null; try (BufferedReader in = new BufferedReader(new InputStreamReader(resource))) {
try {
in = new BufferedReader(new InputStreamReader(resource));
boolean done = false; boolean done = false;
while (!done) { while (!done) {
StringBuilder command = new StringBuilder(); StringBuilder command = new StringBuilder();
...@@ -418,16 +397,6 @@ public class SchemaManager { ...@@ -418,16 +397,6 @@ public class SchemaManager {
} }
} }
} }
finally {
if (in != null) {
try {
in.close();
}
catch (Exception e) {
Log.error(e.getMessage(), e);
}
}
}
} }
private static abstract class ResourceLoader { private static abstract class ResourceLoader {
......
...@@ -474,13 +474,12 @@ public class XMPPServer { ...@@ -474,13 +474,12 @@ public class XMPPServer {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void loadModules() { private void loadModules() {
FileReader in = null;
try { File modulesXml = new File(JiveGlobals.getHomeDirectory(), "conf/modules.xml");
File modulesXml = new File(JiveGlobals.getHomeDirectory(), "conf/modules.xml"); logger.info("Loading modules from " + modulesXml.getAbsolutePath());
logger.info("Loading modules from " + modulesXml.getAbsolutePath()); SAXReader xmlReader = new SAXReader();
SAXReader xmlReader = new SAXReader(); xmlReader.setEncoding("UTF-8");
xmlReader.setEncoding("UTF-8"); try (FileReader in = new FileReader(modulesXml)) {
in = new FileReader(modulesXml);
Document document = xmlReader.read(in); Document document = xmlReader.read(in);
Element root = document.getRootElement(); Element root = document.getRootElement();
Iterator<Node> itr = root.nodeIterator(); Iterator<Node> itr = root.nodeIterator();
...@@ -495,14 +494,6 @@ public class XMPPServer { ...@@ -495,14 +494,6 @@ public class XMPPServer {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
logger.error(LocaleUtils.getLocalizedString("admin.error"), e); logger.error(LocaleUtils.getLocalizedString("admin.error"), e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Squash
}
}
} }
// Keep a reference to the internal component manager // Keep a reference to the internal component manager
...@@ -773,9 +764,7 @@ public class XMPPServer { ...@@ -773,9 +764,7 @@ public class XMPPServer {
// we have to attempt to load the value from openfire_init.xml, // we have to attempt to load the value from openfire_init.xml,
// which must be in the classpath. // which must be in the classpath.
if (openfireHome == null) { if (openfireHome == null) {
InputStream in = null; try (InputStream in = getClass().getResourceAsStream("/openfire_init.xml")) {
try {
in = getClass().getResourceAsStream("/openfire_init.xml");
if (in != null) { if (in != null) {
SAXReader reader = new SAXReader(); SAXReader reader = new SAXReader();
Document doc = reader.read(in); Document doc = reader.read(in);
...@@ -794,17 +783,6 @@ public class XMPPServer { ...@@ -794,17 +783,6 @@ public class XMPPServer {
System.err.println("Error loading openfire_init.xml to find home."); System.err.println("Error loading openfire_init.xml to find home.");
e.printStackTrace(); e.printStackTrace();
} }
finally {
try {
if (in != null) {
in.close();
}
}
catch (Exception e) {
System.err.println("Could not close open connection");
e.printStackTrace();
}
}
} }
if (openfireHome == null) { if (openfireHome == null) {
......
...@@ -69,37 +69,17 @@ public class PluginIconServlet extends HttpServlet { ...@@ -69,37 +69,17 @@ public class PluginIconServlet extends HttpServlet {
else { else {
response.setContentType("image/gif"); response.setContentType("image/gif");
} }
InputStream in = null; try (InputStream in = new FileInputStream(icon)) {
OutputStream ost = null; try (OutputStream ost = response.getOutputStream()) {
try { byte[] buf = new byte[1024];
in = new FileInputStream(icon); int len;
ost = response.getOutputStream(); while ((len = in.read(buf)) >= 0) {
ost.write(buf, 0, len);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) >= 0) {
ost.write(buf, 0, len);
}
ost.flush();
}
catch (IOException ioe) {
}
finally {
if (in != null) {
try {
in.close();
}
catch (Exception e) {
}
}
if (ost != null) {
try {
ost.close();
}
catch (Exception e) {
} }
ost.flush();
} }
} catch (IOException ioe) {
throw new ServletException(ioe);
} }
} }
} }
......
...@@ -177,12 +177,12 @@ public class PluginManager { ...@@ -177,12 +177,12 @@ public class PluginManager {
// Absolute path to the plugin file // Absolute path to the plugin file
String absolutePath = pluginDirectory + File.separator + pluginFilename; String absolutePath = pluginDirectory + File.separator + pluginFilename;
// Save input stream contents to a temp file // Save input stream contents to a temp file
OutputStream out = new FileOutputStream(absolutePath + ".part"); try (OutputStream out = new FileOutputStream(absolutePath + ".part")) {
while ((len = in.read(b)) != -1) { while ((len = in.read(b)) != -1) {
//write byte to file //write byte to file
out.write(b, 0, len); out.write(b, 0, len);
}
} }
out.close();
// Delete old .jar (if it exists) // Delete old .jar (if it exists)
new File(absolutePath).delete(); new File(absolutePath).delete();
// Rename temp file to .jar // Rename temp file to .jar
...@@ -1097,8 +1097,7 @@ public class PluginManager { ...@@ -1097,8 +1097,7 @@ public class PluginManager {
* @param dir the directory to extract the plugin to. * @param dir the directory to extract the plugin to.
*/ */
private void unzipPlugin(String pluginName, File file, File dir) { private void unzipPlugin(String pluginName, File file, File dir) {
try { try (ZipFile zipFile = new JarFile(file)) {
ZipFile zipFile = new JarFile(file);
// Ensure that this JAR is a plugin. // Ensure that this JAR is a plugin.
if (zipFile.getEntry("plugin.xml") == null) { if (zipFile.getEntry("plugin.xml") == null) {
return; return;
...@@ -1116,20 +1115,18 @@ public class PluginManager { ...@@ -1116,20 +1115,18 @@ public class PluginManager {
} }
if (!entry.isDirectory()) { if (!entry.isDirectory()) {
entryFile.getParentFile().mkdirs(); entryFile.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(entryFile); try (FileOutputStream out = new FileOutputStream(entryFile)) {
InputStream zin = zipFile.getInputStream(entry); try (InputStream zin = zipFile.getInputStream(entry)) {
byte[] b = new byte[512]; byte[] b = new byte[512];
int len; int len;
while ((len = zin.read(b)) != -1) { while ((len = zin.read(b)) != -1) {
out.write(b, 0, len); out.write(b, 0, len);
}
out.flush();
}
} }
out.flush();
out.close();
zin.close();
} }
} }
zipFile.close();
} }
catch (Exception e) { catch (Exception e) {
Log.error(e.getMessage(), e); Log.error(e.getMessage(), e);
......
...@@ -405,34 +405,18 @@ public class PluginServlet extends HttpServlet { ...@@ -405,34 +405,18 @@ public class PluginServlet extends HttpServlet {
// response.setHeader("Content-disposition", "filename=\"" + file + "\";"); // response.setHeader("Content-disposition", "filename=\"" + file + "\";");
response.setContentType(contentType); response.setContentType(contentType);
// Write out the resource to the user. // Write out the resource to the user.
InputStream in = null; try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
ServletOutputStream out = null; try (ServletOutputStream out = response.getOutputStream()) {
try {
in = new BufferedInputStream(new FileInputStream(file));
out = response.getOutputStream();
// Set the size of the file. // Set the size of the file.
response.setContentLength((int)file.length()); response.setContentLength((int) file.length());
// Use a 1K buffer. // Use a 1K buffer.
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int len; int len;
while ((len = in.read(buf)) != -1) { while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len); out.write(buf, 0, len);
} }
}
finally {
try {
in.close();
}
catch (Exception ignored) {
// Ignore.
}
try {
out.close();
}
catch (Exception ignored) {
// Ignore.
} }
} }
} }
......
...@@ -125,43 +125,23 @@ public class DefaultProxyTransfer implements ProxyTransfer { ...@@ -125,43 +125,23 @@ public class DefaultProxyTransfer implements ProxyTransfer {
if (!isActivatable()) { if (!isActivatable()) {
throw new IOException("Transfer missing party"); throw new IOException("Transfer missing party");
} }
InputStream in = null;
OutputStream out = null;
try { try (InputStream in = getInputStream()) {
in = getInputStream(); try (OutputStream out = new ProxyOutputStream(getOutputStream())) {
out = new ProxyOutputStream(getOutputStream());
final byte[] b = new byte[BUFFER_SIZE]; final byte[] b = new byte[BUFFER_SIZE];
int count = 0; int count = 0;
amountWritten = 0; amountWritten = 0;
do { do {
// write to the output stream // write to the output stream
out.write(b, 0, count); out.write(b, 0, count);
amountWritten += count; amountWritten += count;
// read more bytes from the input stream // read more bytes from the input stream
count = in.read(b); count = in.read(b);
} while (count >= 0); } while (count >= 0);
}
finally {
if (in != null) {
try {
in.close();
}
catch (Exception e) {
Log.error(e.getMessage(), e);
}
}
if (out != null) {
try {
out.close();
}
catch (Exception e) {
Log.error(e.getMessage(), e);
}
} }
} }
} }
......
...@@ -115,20 +115,17 @@ public class FlashCrossDomainServlet extends HttpServlet { ...@@ -115,20 +115,17 @@ public class FlashCrossDomainServlet extends HttpServlet {
private static String getContent(File file) { private static String getContent(File file) {
final StringBuilder content = new StringBuilder(); final StringBuilder content = new StringBuilder();
if (file.canRead()) { if (file.canRead()) {
try { try (BufferedReader in = new BufferedReader(new FileReader(file))) {
final BufferedReader in = new BufferedReader(new FileReader( String str;
file)); while ((str = in.readLine()) != null) {
String str; content.append(str);
while ((str = in.readLine()) != null) { content.append('\n');
content.append(str); }
content.append('\n'); } catch (IOException ex) {
} Log.warn("Unexpected exception while trying to read file: " + file.getName(), ex);
in.close(); return null;
} catch (IOException ex) { }
Log.warn("Unexpected exception while trying to read file: " + file.getName(), ex); }
return null;
}
}
return content.toString(); return content.toString();
} }
......
...@@ -93,8 +93,6 @@ public class ResourceServlet extends HttpServlet { ...@@ -93,8 +93,6 @@ public class ResourceServlet extends HttpServlet {
response.setHeader("Expires", "1"); response.setHeader("Expires", "1");
compress = false; compress = false;
} }
OutputStream out = null;
InputStream in = null;
try { try {
byte[] content; byte[] content;
...@@ -114,24 +112,22 @@ public class ResourceServlet extends HttpServlet { ...@@ -114,24 +112,22 @@ public class ResourceServlet extends HttpServlet {
} }
// Write the content out // Write the content out
in = new ByteArrayInputStream(content); try (ByteArrayInputStream in = new ByteArrayInputStream(content)) {
out = response.getOutputStream(); try (OutputStream out = response.getOutputStream()) {
// Use a 128K buffer. // Use a 128K buffer.
byte[] buf = new byte[128*1024]; byte[] buf = new byte[128 * 1024];
int len; int len;
while ((len=in.read(buf)) != -1) { while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len); out.write(buf, 0, len);
}
out.flush();
}
} }
out.flush();
} }
catch (IOException e) { catch (IOException e) {
Log.error(e.getMessage(), e); Log.error(e.getMessage(), e);
} }
finally {
try { if (in != null) { in.close(); } } catch (Exception ignored) { /* ignored */ }
try { if (out != null) { out.close(); } } catch (Exception ignored) { /* ignored */ }
}
} }
private static byte[] getJavaScriptContent(boolean compress) throws IOException private static byte[] getJavaScriptContent(boolean compress) throws IOException
...@@ -142,24 +138,13 @@ public class ResourceServlet extends HttpServlet { ...@@ -142,24 +138,13 @@ public class ResourceServlet extends HttpServlet {
} }
if (compress) { if (compress) {
ByteArrayOutputStream baos = null; try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
GZIPOutputStream gzos = null; try (GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
try { gzos.write(writer.toString().getBytes());
baos = new ByteArrayOutputStream(); gzos.finish();
gzos = new GZIPOutputStream(baos); gzos.flush();
return baos.toByteArray();
gzos.write(writer.toString().getBytes()); }
gzos.finish();
gzos.flush();
gzos.close();
return baos.toByteArray();
}
finally {
try { if (gzos != null) { gzos.close(); } }
catch (Exception ignored) { /* ignored */ }
try { if (baos != null) { baos.close(); } }
catch (Exception ignored) { /* ignored */ }
} }
} }
else { else {
...@@ -175,31 +160,21 @@ public class ResourceServlet extends HttpServlet { ...@@ -175,31 +160,21 @@ public class ResourceServlet extends HttpServlet {
private static String getJavaScriptFile(String path) { private static String getJavaScriptFile(String path) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
InputStream in = null; try (InputStream in = getResourceAsStream(path)) {
InputStreamReader isr = null;
BufferedReader br = null;
try {
in = getResourceAsStream(path);
if (in == null) { if (in == null) {
Log.error("Unable to find javascript file: '" + path + "' in classpath"); Log.error("Unable to find javascript file: '" + path + "' in classpath");
return ""; return "";
} }
isr = new InputStreamReader(in, "ISO-8859-1"); try (BufferedReader br = new BufferedReader(new InputStreamReader(in, "ISO-8859-1"))) {
br = new BufferedReader(isr); String line;
String line; while ((line = br.readLine()) != null) {
while ((line = br.readLine()) != null) { sb.append(line.trim()).append('\n');
sb.append(line.trim()).append('\n'); }
} }
} } catch (Exception e) {
catch (Exception e) {
Log.error("Error loading JavaScript file: '" + path + "'.", e); Log.error("Error loading JavaScript file: '" + path + "'.", e);
} }
finally {
try { if (br != null) { br.close(); } } catch (Exception ignored) { /* ignored */ }
try { if (isr != null) { isr.close(); } } catch (Exception ignored) { /* ignored */ }
try { if (in != null) { in.close(); } } catch (Exception ignored) { /* ignored */ }
}
return sb.toString(); return sb.toString();
} }
......
...@@ -427,9 +427,8 @@ public class Launcher { ...@@ -427,9 +427,8 @@ public class Launcher {
@Override @Override
public Object construct() { public Object construct() {
if (openfired != null) { if (openfired != null) {
try { // Get the input stream and read from it
// Get the input stream and read from it try (InputStream in = openfired.getInputStream()) {
InputStream in = openfired.getInputStream();
int c; int c;
while ((c = in.read()) != -1) { while ((c = in.read()) != -1) {
try { try {
...@@ -441,7 +440,6 @@ public class Launcher { ...@@ -441,7 +440,6 @@ public class Launcher {
// Ignore. // Ignore.
} }
} }
in.close();
} }
catch (IOException e) { catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
...@@ -457,9 +455,8 @@ public class Launcher { ...@@ -457,9 +455,8 @@ public class Launcher {
@Override @Override
public Object construct() { public Object construct() {
if (openfired != null) { if (openfired != null) {
try { // Get the input stream and read from it
// Get the input stream and read from it try (InputStream in = openfired.getErrorStream()) {
InputStream in = openfired.getErrorStream();
int c; int c;
while ((c = in.read()) != -1) { while ((c = in.read()) != -1) {
try { try {
...@@ -470,7 +467,6 @@ public class Launcher { ...@@ -470,7 +467,6 @@ public class Launcher {
// Ignore. // Ignore.
} }
} }
in.close();
} }
catch (IOException e) { catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
...@@ -505,11 +501,11 @@ public class Launcher { ...@@ -505,11 +501,11 @@ public class Launcher {
try { try {
// attempt to perform a graceful shutdown by sending // attempt to perform a graceful shutdown by sending
// an "exit" command to the process (via stdin) // an "exit" command to the process (via stdin)
Writer out = new OutputStreamWriter( try (Writer out = new OutputStreamWriter(
new BufferedOutputStream(openfired.getOutputStream())); new BufferedOutputStream(openfired.getOutputStream()))) {
out.write("exit\n"); out.write("exit\n");
out.close(); }
final Thread waiting = Thread.currentThread(); final Thread waiting = Thread.currentThread();
Thread waiter = new Thread() { Thread waiter = new Thread() {
public void run() { public void run() {
try { try {
...@@ -620,30 +616,10 @@ public class Launcher { ...@@ -620,30 +616,10 @@ public class Launcher {
} }
private static void copy(URL src, File dst) throws IOException { private static void copy(URL src, File dst) throws IOException {
InputStream in = null; try (InputStream in = src.openStream()) {
OutputStream out = null; try (OutputStream out = new FileOutputStream(dst)) {
try { dst.mkdirs();
in = src.openStream(); copy(in, out);
out = new FileOutputStream(dst);
dst.mkdirs();
copy(in, out);
}
finally {
try {
if (in != null) {
in.close();
}
}
catch (IOException e) {
// Ignore.
}
try {
if (out != null) {
out.close();
}
}
catch (IOException e) {
// Ignore.
} }
} }
} }
......
...@@ -280,11 +280,11 @@ public class UpdateManager extends BasicModule { ...@@ -280,11 +280,11 @@ public class UpdateManager extends BasicModule {
int statusCode = httpClient.executeMethod(getMethod); int statusCode = httpClient.executeMethod(getMethod);
if (statusCode == 200) { if (statusCode == 200) {
//get the resonse as an InputStream //get the resonse as an InputStream
InputStream in = getMethod.getResponseBodyAsStream(); try (InputStream in = getMethod.getResponseBodyAsStream()) {
String pluginFilename = url.substring(url.lastIndexOf("/") + 1); String pluginFilename = url.substring(url.lastIndexOf("/") + 1);
installed = XMPPServer.getInstance().getPluginManager() installed = XMPPServer.getInstance().getPluginManager()
.installPlugin(in, pluginFilename); .installPlugin(in, pluginFilename);
in.close(); }
if (installed) { if (installed) {
// Remove the plugin from the list of plugins to update // Remove the plugin from the list of plugins to update
for (Update update : pluginUpdates) { for (Update update : pluginUpdates) {
...@@ -657,7 +657,6 @@ public class UpdateManager extends BasicModule { ...@@ -657,7 +657,6 @@ public class UpdateManager extends BasicModule {
component.addAttribute("url", serverUpdate.getURL()); component.addAttribute("url", serverUpdate.getURL());
} }
// Write data out to conf/server-update.xml file. // Write data out to conf/server-update.xml file.
Writer writer = null;
try { try {
// Create the conf folder if required // Create the conf folder if required
File file = new File(JiveGlobals.getHomeDirectory(), "conf"); File file = new File(JiveGlobals.getHomeDirectory(), "conf");
...@@ -671,24 +670,15 @@ public class UpdateManager extends BasicModule { ...@@ -671,24 +670,15 @@ public class UpdateManager extends BasicModule {
file.delete(); file.delete();
} }
// Create new version.xml with returned data // Create new version.xml with returned data
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
OutputFormat prettyPrinter = OutputFormat.createPrettyPrint(); OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter); XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
xmlWriter.write(xmlResponse); xmlWriter.write(xmlResponse);
}
} }
catch (Exception e) { catch (Exception e) {
Log.error(e.getMessage(), e); Log.error(e.getMessage(), e);
} }
finally {
if (writer != null) {
try {
writer.close();
}
catch (IOException e1) {
Log.error(e1.getMessage(), e1);
}
}
}
} }
/** /**
...@@ -772,27 +762,15 @@ public class UpdateManager extends BasicModule { ...@@ -772,27 +762,15 @@ public class UpdateManager extends BasicModule {
Log.warn("Cannot retrieve server updates. File must be readable: " + file.getName()); Log.warn("Cannot retrieve server updates. File must be readable: " + file.getName());
return; return;
} }
FileReader reader = null; try (FileReader reader = new FileReader(file)){
try {
reader = new FileReader(file);
SAXReader xmlReader = new SAXReader(); SAXReader xmlReader = new SAXReader();
xmlReader.setEncoding("UTF-8"); xmlReader.setEncoding("UTF-8");
xmlResponse = xmlReader.read(reader); xmlResponse = xmlReader.read(reader);
} } catch (Exception e) {
catch (Exception e) {
Log.error("Error reading server-update.xml", e); Log.error("Error reading server-update.xml", e);
return; return;
} }
finally {
if (reader != null) {
try {
reader.close();
}
catch (Exception e) {
// Do nothing
}
}
}
// Parse info and recreate update information (if still required) // Parse info and recreate update information (if still required)
Element openfire = xmlResponse.getRootElement().element("openfire"); Element openfire = xmlResponse.getRootElement().element("openfire");
if (openfire != null) { if (openfire != null) {
...@@ -819,27 +797,15 @@ public class UpdateManager extends BasicModule { ...@@ -819,27 +797,15 @@ public class UpdateManager extends BasicModule {
Log.warn("Cannot retrieve available plugins. File must be readable: " + file.getName()); Log.warn("Cannot retrieve available plugins. File must be readable: " + file.getName());
return; return;
} }
FileReader reader = null; try (FileReader reader = new FileReader(file)) {
try {
reader = new FileReader(file);
SAXReader xmlReader = new SAXReader(); SAXReader xmlReader = new SAXReader();
xmlReader.setEncoding("UTF-8"); xmlReader.setEncoding("UTF-8");
xmlResponse = xmlReader.read(reader); xmlResponse = xmlReader.read(reader);
} } catch (Exception e) {
catch (Exception e) {
Log.error("Error reading available-plugins.xml", e); Log.error("Error reading available-plugins.xml", e);
return; return;
} }
finally {
if (reader != null) {
try {
reader.close();
}
catch (Exception e) {
// Do nothing
}
}
}
// Parse info and recreate available plugins // Parse info and recreate available plugins
Iterator it = xmlResponse.getRootElement().elementIterator("plugin"); Iterator it = xmlResponse.getRootElement().elementIterator("plugin");
while (it.hasNext()) { while (it.hasNext()) {
......
...@@ -124,11 +124,9 @@ public class FaviconServlet extends HttpServlet { ...@@ -124,11 +124,9 @@ public class FaviconServlet extends HttpServlet {
response.setContentType(CONTENT_TYPE); response.setContentType(CONTENT_TYPE);
// Send image // Send image
try { try (ServletOutputStream sos = response.getOutputStream()) {
ServletOutputStream sos = response.getOutputStream();
sos.write(bytes); sos.write(bytes);
sos.flush(); sos.flush();
sos.close();
} }
catch (IOException e) { catch (IOException e) {
// Do nothing // Do nothing
...@@ -195,20 +193,20 @@ public class FaviconServlet extends HttpServlet { ...@@ -195,20 +193,20 @@ public class FaviconServlet extends HttpServlet {
urlConnection.setReadTimeout(1000); urlConnection.setReadTimeout(1000);
urlConnection.connect(); urlConnection.connect();
DataInputStream di = new DataInputStream(urlConnection.getInputStream()); try (DataInputStream di = new DataInputStream(urlConnection.getInputStream())) {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteStream); DataOutputStream out = new DataOutputStream(byteStream);
int len; int len;
byte[] b = new byte[1024]; byte[] b = new byte[1024];
while ((len = di.read(b)) != -1) { while ((len = di.read(b)) != -1) {
out.write(b, 0, len); out.write(b, 0, len);
} }
di.close(); out.flush();
out.flush();
return byteStream.toByteArray(); return byteStream.toByteArray();
}
} }
catch (IOException ioe) { catch (IOException ioe) {
// We failed again so return null // We failed again so return null
......
...@@ -249,30 +249,11 @@ public class WebManager extends WebBean { ...@@ -249,30 +249,11 @@ public class WebManager extends WebBean {
* Copies the contents at <CODE>src</CODE> to <CODE>dst</CODE>. * Copies the contents at <CODE>src</CODE> to <CODE>dst</CODE>.
*/ */
public static void copy(URL src, File dst) throws IOException { public static void copy(URL src, File dst) throws IOException {
InputStream in = null;
OutputStream out = null; try (InputStream in = src.openStream()) {
try { try (OutputStream out = new FileOutputStream(dst)) {
in = src.openStream(); dst.mkdirs();
out = new FileOutputStream(dst); copy(in, out);
dst.mkdirs();
copy(in, out);
}
finally {
try {
if (in != null) {
in.close();
}
}
catch (IOException e) {
// Ignore.
}
try {
if (out != null) {
out.close();
}
}
catch (IOException e) {
// Ignore.
} }
} }
} }
......
...@@ -742,54 +742,24 @@ public class XMLProperties { ...@@ -742,54 +742,24 @@ public class XMLProperties {
Log.error("Unable to save XML properties; no file specified"); Log.error("Unable to save XML properties; no file specified");
return; return;
} }
boolean error = false;
// Write data out to a temporary file first. // Write data out to a temporary file first.
File tempFile = null; File tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
Writer writer = null; try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"))) {
try {
tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"));
OutputFormat prettyPrinter = OutputFormat.createPrettyPrint(); OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter); XMLWriter xmlWriter = new XMLWriter(writer, prettyPrinter);
xmlWriter.write(document); xmlWriter.write(document);
}
catch (Exception e) {
Log.error(e.getMessage(), e);
// There were errors so abort replacing the old property file.
error = true;
}
finally {
if (writer != null) {
try {
writer.close();
}
catch (IOException e1) {
Log.error(e1.getMessage(), e1);
error = true;
}
}
}
// No errors occurred, so delete the main file.
if (!error) {
// Delete the old file so we can replace it. // Delete the old file so we can replace it.
if (!file.delete()) { if (!file.delete()) {
Log.error("Error deleting property file: " + file.getAbsolutePath()); Log.error("Error deleting property file: " + file.getAbsolutePath());
return; return;
} }
// Copy new contents to the file. // Copy new contents to the file.
try { copy(tempFile, file);
copy(tempFile, file);
}
catch (Exception e) {
Log.error(e.getMessage(), e);
// There were errors so abort replacing the old property file.
error = true;
}
// If no errors, delete the temp file. // If no errors, delete the temp file.
if (!error) { tempFile.delete();
tempFile.delete(); } catch (Exception e) {
} Log.error(e.getMessage(), e);
} }
} }
...@@ -826,25 +796,9 @@ public class XMLProperties { ...@@ -826,25 +796,9 @@ public class XMLProperties {
* @throws IOException If there was a problem making the copy * @throws IOException If there was a problem making the copy
*/ */
private static void copy(File inFile, File outFile) throws IOException { private static void copy(File inFile, File outFile) throws IOException {
FileInputStream fin = null; try (FileInputStream fin = new FileInputStream(inFile)) {
FileOutputStream fout = null; try (FileOutputStream fout = new FileOutputStream(outFile)) {
try { copy(fin, fout);
fin = new FileInputStream(inFile);
fout = new FileOutputStream(outFile);
copy(fin, fout);
}
finally {
try {
if (fin != null) fin.close();
}
catch (IOException e) {
// do nothing
}
try {
if (fout != null) fout.close();
}
catch (IOException e) {
// do nothing
} }
} }
} }
......
...@@ -53,9 +53,8 @@ public class SANCertificateIdentityMapping implements CertificateIdentityMapping ...@@ -53,9 +53,8 @@ public class SANCertificateIdentityMapping implements CertificateIdentityMapping
Integer type = (Integer) item.get(0); Integer type = (Integer) item.get(0);
if (type == 0) { if (type == 0) {
// Type OtherName found so return the associated value // Type OtherName found so return the associated value
try { try (ASN1InputStream decoder = new ASN1InputStream((byte[]) item.get(1))) {
// Value is encoded using ASN.1 so decode it to get the server's identity // Value is encoded using ASN.1 so decode it to get the server's identity
ASN1InputStream decoder = new ASN1InputStream((byte[]) item.get(1));
Object object = decoder.readObject(); Object object = decoder.readObject();
ASN1Sequence otherNameSeq = null; ASN1Sequence otherNameSeq = null;
if (object != null && object instanceof ASN1Sequence) { if (object != null && object instanceof ASN1Sequence) {
...@@ -90,7 +89,6 @@ public class SANCertificateIdentityMapping implements CertificateIdentityMapping ...@@ -90,7 +89,6 @@ public class SANCertificateIdentityMapping implements CertificateIdentityMapping
// Add the decoded server name to the list of identities // Add the decoded server name to the list of identities
identities.add(identity); identities.add(identity);
} }
decoder.close();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// OF-517: othername formats are extensible. If we don't recognize the format, skip it. // OF-517: othername formats are extensible. If we don't recognize the format, skip it.
Log.debug("Cannot parse altName, likely because of unknown record format.", ex); Log.debug("Cannot parse altName, likely because of unknown record format.", ex);
......
...@@ -43,18 +43,18 @@ public class TestUtils { ...@@ -43,18 +43,18 @@ public class TestUtils {
* Returns the contents of the given file as a String. * Returns the contents of the given file as a String.
*/ */
public static String getAsString(File file) throws Exception { public static String getAsString(File file) throws Exception {
BufferedReader in = new BufferedReader(new FileReader(file)); try (BufferedReader in = new BufferedReader(new FileReader(file))) {
StringBuffer xml = new StringBuffer(); StringBuffer xml = new StringBuffer();
String lineSeparator = System.getProperty("line.separator"); String lineSeparator = System.getProperty("line.separator");
if (lineSeparator == null) { if (lineSeparator == null) {
lineSeparator = "\n"; lineSeparator = "\n";
}
String line = null;
while ((line = in.readLine()) != null) {
xml.append(line).append(lineSeparator);
}
return xml.toString();
} }
String line = null;
while ((line=in.readLine()) != null) {
xml.append(line).append(lineSeparator);
}
in.close();
return xml.toString();
} }
public static String prepareFilename(String filename) { public static String prepareFilename(String filename) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment