Improved: Removes nested blocks and closed OutputStream in finally
statment
@@ -234,6 +234,7 @@ public class SecuredUpload {
File file = new File(fileName);
boolean safeState = false;
boolean fallbackOnApacheCommonsImaging;
+ OutputStream fos = null;
try {
if ((file != null) && file.exists() && file.canRead() && file.canWrite()) {
// Get the image format
@@ -285,7 +286,7 @@ public class SecuredUpload {
Graphics bg = sanitizedImage.getGraphics();
bg.drawImage(initialSizedImage, 0, 0, null);
bg.dispose();
- OutputStream fos = Files.newOutputStream(file.toPath(), StandardOpenOption.WRITE);
+ fos = Files.newOutputStream(file.toPath(), StandardOpenOption.WRITE);
if (!fallbackOnApacheCommonsImaging) {
ImageIO.write(sanitizedImage, formatName, fos);
} else {
@@ -293,35 +294,37 @@ public class SecuredUpload {
// Handle only formats for which Apache Commons Imaging can successfully write (YES in Write column of the reference link)
// the image format. See reference link in the class header
switch (formatName) {
- case "TIFF": {
+ case "TIFF":
imageParser = new TiffImageParser();
break;
- }
- case "GIF": {
+ case "GIF":
imageParser = new GifImageParser();
break;
- }
- case "PNG": {
+ case "PNG":
imageParser = new PngImageParser();
break;
- }
- case "JPEG": {
+ case "JPEG":
imageParser = new JpegImageParser();
break;
- }
- default: {
+ default:
throw new IOException("Format of the original image " + fileName + " is not supported for write operation !");
}
- }
imageParser.writeImage(sanitizedImage, fos, new HashMap<>());
}
- // Set state flag
- fos.close(); // This was not correctly handled in the document-upload-protection example, and I did not spot it :/
- safeState = true;
}
} catch (IOException | ImageReadException | ImageWriteException e) {
safeState = false;
Debug.logWarning(e, "Error during Image file " + fileName + " processing !", MODULE);
+ } finally {
+ // Set state flag
+ try {
+ fos.close();
+ } catch (IOException e) {
+ safeState = false;
+ Debug.logWarning(e, "Error during Image file " + fileName + " processing !", MODULE);
+ }
+ // This was not correctly handled in the document-upload-protection example, and I did not spot it :/
+ safeState = true;
}
return safeState;
}
