Skip to content

Commit

Permalink
Use try-with-resources for closable streams
Browse files Browse the repository at this point in the history
This also fixes a few streams that weren't closed (for saving properties).
  • Loading branch information
Pokechu22 committed Aug 28, 2017
1 parent 656407d commit 53d8210
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 169 deletions.
160 changes: 52 additions & 108 deletions share/src/main/java/wdl/WDL.java
Original file line number Diff line number Diff line change
Expand Up @@ -273,21 +273,12 @@ public class WDL {
defaultProps.setProperty("TutorialShown", "false");

globalProps = new Properties(defaultProps);
FileReader reader = null;
try {
reader = new FileReader(new File(minecraft.mcDataDir,
"WorldDownloader.txt"));

File dataFile = new File(minecraft.mcDataDir, "WorldDownloader.txt");
try (FileReader reader = new FileReader(dataFile)) {
globalProps.load(reader);
} catch (Exception e) {
LOGGER.debug("Failed to load global properties", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
LOGGER.warn("Failed to close global properties reader", e);
}
}
}
baseProps = new Properties(globalProps);
worldProps = new Properties(baseProps);
Expand Down Expand Up @@ -379,35 +370,27 @@ public void onCancel() {
saveHandler = (SaveHandler) minecraft.getSaveLoader().getSaveLoader(
getWorldFolderName(worldName), true);

FileInputStream worldDat = null;
try {
long lastSaved = Long.parseLong(worldProps.getProperty("LastSaved",
"-1"));
//Can't directly use worldClient.getWorldInfo, as that doesn't use
//the saved version.
worldDat = new FileInputStream(new File(
saveHandler.getWorldDirectory(), "level.dat"));
long lastPlayed = CompressedStreamTools.readCompressed(worldDat)
.getCompoundTag("Data").getLong("LastPlayed");
if (!overrideLastModifiedCheck && lastPlayed > lastSaved) {
// The world was played later than it was saved; confirm that the
// user is willing for possible changes they made to be overwritten.
minecraft.displayGuiScreen(new GuiWDLOverwriteChanges(
lastSaved, lastPlayed));
return;
}
long lastSaved = Long.parseLong(worldProps.getProperty("LastSaved",
"-1"));
long lastPlayed;
// Can't directly use worldClient.getWorldInfo, as that doesn't use
// the saved version.
File levelDatFile = new File(saveHandler.getWorldDirectory(), "level.dat");
try (FileInputStream stream = new FileInputStream(levelDatFile)) {
NBTTagCompound compound = CompressedStreamTools.readCompressed(stream);
lastPlayed = compound.getCompoundTag("Data").getLong("LastPlayed");
} catch (Exception e) {
LOGGER.warn("Error while checking if the map has been played and " +
"needs to be backed up (this is normal if this world " +
"has not been saved before): ", e);
} finally {
if (worldDat != null) {
try {
worldDat.close();
} catch (Exception e) {
e.printStackTrace();
}
}
lastPlayed = -1;
}
if (!overrideLastModifiedCheck && lastPlayed > lastSaved) {
// The world was played later than it was saved; confirm that the
// user is willing for possible changes they made to be overwritten.
minecraft.displayGuiScreen(new GuiWDLOverwriteChanges(
lastSaved, lastPlayed));
return;
}

runSanityCheck();
Expand Down Expand Up @@ -702,16 +685,14 @@ public static NBTTagCompound savePlayer(GuiWDLSaveProgress progressScreen) {
progressScreen.setMinorTaskProgress(
I18n.format("wdl.saveProgress.playerData.writingNBT"), taskNum);

FileOutputStream stream = null;
try {
File playersDirectory = new File(saveHandler.getWorldDirectory(),
"playerdata");
File playerFileTmp = new File(playersDirectory, thePlayer
.getUniqueID().toString() + ".dat.tmp");
File playerFile = new File(playersDirectory, thePlayer
.getUniqueID().toString() + ".dat");
File playersDirectory = new File(saveHandler.getWorldDirectory(),
"playerdata");
File playerFileTmp = new File(playersDirectory, thePlayer
.getUniqueID().toString() + ".dat.tmp");
File playerFile = new File(playersDirectory, thePlayer
.getUniqueID().toString() + ".dat");

stream = new FileOutputStream(playerFileTmp);
try (FileOutputStream stream = new FileOutputStream(playerFileTmp)) {

CompressedStreamTools.writeCompressed(playerNBT, stream);

Expand All @@ -723,14 +704,6 @@ public static NBTTagCompound savePlayer(GuiWDLSaveProgress progressScreen) {
playerFileTmp.renameTo(playerFile);
} catch (Exception e) {
throw new RuntimeException("Couldn't save the player!", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

WDLMessages.chatMessageTranslated(WDLMessageTypes.SAVING,
Expand Down Expand Up @@ -802,13 +775,11 @@ public static void saveWorldInfo(GuiWDLSaveProgress progressScreen,
worldProps.setProperty("LastSaved",
Long.toString(worldInfoNBT.getLong("LastPlayed")));

FileOutputStream stream = null;
try {
File dataFile = new File(saveDirectory, "level.dat_new");
File dataFileBackup = new File(saveDirectory, "level.dat_old");
File dataFileOld = new File(saveDirectory, "level.dat");
stream = new FileOutputStream(dataFile);
File dataFile = new File(saveDirectory, "level.dat_new");
File dataFileBackup = new File(saveDirectory, "level.dat_old");
File dataFileOld = new File(saveDirectory, "level.dat");

try (FileOutputStream stream = new FileOutputStream(dataFile)) {
CompressedStreamTools.writeCompressed(rootWorldInfoNBT, stream);

if (dataFileBackup.exists()) {
Expand All @@ -828,14 +799,6 @@ public static void saveWorldInfo(GuiWDLSaveProgress progressScreen,
}
} catch (Exception e) {
throw new RuntimeException("Couldn't save the world metadata!", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

WDLMessages.chatMessageTranslated(WDLMessageTypes.SAVING,
Expand Down Expand Up @@ -951,25 +914,15 @@ public static void loadBaseProps() {
baseFolderName = getBaseFolderName();
baseProps = new Properties(globalProps);

FileReader reader = null;
try {
File savesFolder = new File(minecraft.mcDataDir, "saves");
File baseFolder = new File(savesFolder, baseFolderName);
reader = new FileReader(new File(baseFolder,
"WorldDownloader.txt"));
File savesFolder = new File(minecraft.mcDataDir, "saves");
File baseFolder = new File(savesFolder, baseFolderName);
File dataFile = new File(baseFolder, "WorldDownloader.txt");
try (FileReader reader = new FileReader(dataFile)) {
baseProps.load(reader);
propsFound = true;
} catch (Exception e) {
propsFound = false;
LOGGER.debug("Failed to load base properties", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
LOGGER.warn("Failed to close base properties reader", e);
}
}
}

if (baseProps.getProperty("LinkedWorlds").isEmpty()) {
Expand Down Expand Up @@ -997,25 +950,15 @@ public static Properties loadWorldProps(String theWorldName) {

String folder = getWorldFolderName(theWorldName);
File worldFolder = new File(savesDir, folder);
File dataFile = new File(worldFolder, "WorldDownloader.txt");

FileReader reader = null;
try {
ret.load(new FileReader(new File(worldFolder,
"WorldDownloader.txt")));
try (FileReader reader = new FileReader(dataFile)) {
ret.load(reader);

return ret;
} catch (Exception e) {
LOGGER.debug("Failed to load world props for " + worldName, e);
return ret;
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
LOGGER.warn("Failed to close world props reader for "
+ worldName, e);
}
}
}
}

Expand All @@ -1039,10 +982,11 @@ public static void saveProps(String theWorldName, Properties theWorldProps) {

File worldFolder = new File(savesDir, folder);
worldFolder.mkdirs();
try {
theWorldProps.store(new FileWriter(new File(worldFolder,
"WorldDownloader.txt")), I18n.format("wdl.props.world.title"));
File worldPropsFile = new File(worldFolder, "WorldDownloader.txt");
try (FileWriter writer = new FileWriter(worldPropsFile)) {
theWorldProps.store(writer, I18n.format("wdl.props.world.title"));
} catch (Exception e) {
LOGGER.warn("Failed to write world props!", e);
}
} else if (!isMultiworld) {
baseProps.putAll(theWorldProps);
Expand All @@ -1051,10 +995,11 @@ public static void saveProps(String theWorldName, Properties theWorldProps) {
File baseFolder = new File(savesDir, baseFolderName);
baseFolder.mkdirs();

try {
baseProps.store(new FileWriter(new File(baseFolder,
"WorldDownloader.txt")), I18n.format("wdl.props.base.title"));
File basePropsFile = new File(baseFolder, "WorldDownloader.txt");
try (FileWriter writer = new FileWriter(basePropsFile)) {
baseProps.store(writer, I18n.format("wdl.props.base.title"));
} catch (Exception e) {
LOGGER.warn("Failed to write base props!", e);
}

saveGlobalProps();
Expand All @@ -1064,11 +1009,11 @@ public static void saveProps(String theWorldName, Properties theWorldProps) {
* Saves the global properties, which are used for all servers.
*/
public static void saveGlobalProps() {
try {
globalProps.store(new FileWriter(new File(minecraft.mcDataDir,
"WorldDownloader.txt")), I18n.format("wdl.props.global.title"));
File globalPropsFile = new File(minecraft.mcDataDir, "WorldDownloader.txt");
try (FileWriter writer = new FileWriter(globalPropsFile)) {
globalProps.store(writer, I18n.format("wdl.props.global.title"));
} catch (Exception e) {

LOGGER.warn("Failed to write globalprops!", e);
}
}

Expand Down Expand Up @@ -1332,9 +1277,8 @@ public static void saveMapData(GuiWDLSaveProgress progressScreen) {

mapNBT.setTag("data", data);

try {
CompressedStreamTools.writeCompressed(mapNBT,
new FileOutputStream(mapFile));
try (FileOutputStream stream = new FileOutputStream(mapFile)) {
CompressedStreamTools.writeCompressed(mapNBT, stream);
} catch (IOException ex) {
throw new RuntimeException("WDL: Exception while writing " +
"map data for map " + e.getKey() + "!", ex);
Expand Down
14 changes: 2 additions & 12 deletions share/src/main/java/wdl/WDLChunkLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -466,12 +466,10 @@ public NBTTagList getTileEntityList(Chunk chunk) {
* @return A map of positions to tile entities.
*/
public Map<BlockPos, NBTTagCompound> getOldTileEntities(Chunk chunk) {
DataInputStream dis = null;
Map<BlockPos, NBTTagCompound> returned = new HashMap<>();

try {
dis = RegionFileCache.getChunkInputStream(chunkSaveLocation,
chunk.x, chunk.z);
try (DataInputStream dis = RegionFileCache.getChunkInputStream(chunkSaveLocation,
chunk.x, chunk.z)) {

if (dis == null) {
// This happens whenever the chunk hasn't been saved before.
Expand Down Expand Up @@ -509,14 +507,6 @@ public Map<BlockPos, NBTTagCompound> getOldTileEntities(Chunk chunk) {
WDLMessages.chatMessageTranslated(WDLMessageTypes.ERROR,
"wdl.messages.generalError.failedToImportTE",
chunk.x, chunk.z, e);
} finally {
if (dis != null) {
try {
dis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return returned;
}
Expand Down
21 changes: 3 additions & 18 deletions share/src/main/java/wdl/WorldBackup.java
Original file line number Diff line number Diff line change
Expand Up @@ -169,21 +169,9 @@ public static void zipDirectory(File src, File destination,
IBackupProgressMonitor monitor) throws IOException {
monitor.setNumberOfFiles(countFilesInFolder(src));

FileOutputStream outStream = null;
ZipOutputStream stream = null;
try {
outStream = new FileOutputStream(destination);
try {
stream = new ZipOutputStream(outStream);
try (FileOutputStream outStream = new FileOutputStream(destination)) {
try (ZipOutputStream stream = new ZipOutputStream(outStream)) {
zipFolder(src, stream, src.getPath().length() + 1, monitor);
} finally {
if (stream != null) {
stream.close();
}
}
} finally {
if (outStream != null) {
outStream.close();
}
}
}
Expand All @@ -206,11 +194,8 @@ private static void zipFolder(File folder, ZipOutputStream stream,
monitor.onNextFile(name);
ZipEntry zipEntry = new ZipEntry(name);
stream.putNextEntry(zipEntry);
FileInputStream inputStream = new FileInputStream(file);
try {
try (FileInputStream inputStream = new FileInputStream(file)) {
IOUtils.copy(inputStream, stream);
} finally {
inputStream.close();
}
stream.closeEntry();
} else if (file.isDirectory()) {
Expand Down
17 changes: 2 additions & 15 deletions share/src/main/java/wdl/update/ClassHasher.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,26 +44,13 @@ public static String hash(String relativeTo, String file)
Class<?> clazz = Class.forName(relativeTo);
MessageDigest digest = MessageDigest.getInstance("MD5");

InputStream stream = null;
try {
stream = clazz.getResourceAsStream(file);
try (InputStream stream = clazz.getResourceAsStream(file)) {
if (stream == null) {
throw new FileNotFoundException(file + " relative to "
+ relativeTo);
}
DigestInputStream digestStream = null;
try {
digestStream = new DigestInputStream(stream, digest);

try (DigestInputStream digestStream = new DigestInputStream(stream, digest)) {
while (digestStream.read() != -1); //Read entire stream
} finally {
if (digestStream != null) {
digestStream.close();
}
}
} finally {
if (stream != null) {
stream.close();
}
}

Expand Down
Loading

0 comments on commit 53d8210

Please sign in to comment.