prevent resource leak by using try-with-resource syntax

This commit is contained in:
hrj 2020-07-03 22:20:30 +05:30
parent 300ff3162d
commit 3d147950a4

View File

@ -1395,9 +1395,11 @@ public class HTTPServer {
/** /**
* Returns the body in a String format * Returns the body in a String format
*/ */
public String getJson(){ public String getJson() {
java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A"); try(final java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A")) {
return s.hasNext() ? s.next() : ""; final String result = s.hasNext() ? s.next() : "";
return result;
}
} }
/** /**
@ -3034,29 +3036,27 @@ public class HTTPServer {
w = name.length(); w = name.length();
w += 2; // with room for added slash and space w += 2; // with room for added slash and space
// note: we use apache's format, for consistent user experience // note: we use apache's format, for consistent user experience
Formatter f = new Formatter(Locale.US); try(Formatter f = new Formatter(Locale.US)) {
f.format("<!DOCTYPE html>%n" + f.format("<!DOCTYPE html>%n" + "<html><head><title>Index of %s</title></head>%n"
"<html><head><title>Index of %s</title></head>%n" + + "<body><h1>Index of %s</h1>%n" + "<pre> Name%" + (w - 5) + "s Last modified Size<hr>", path,
"<body><h1>Index of %s</h1>%n" + path, "");
"<pre> Name%" + (w - 5) + "s Last modified Size<hr>", if (path.length() > 1) // add parent link if not root path
path, path, ""); f.format(" <a href=\"%s/\">Parent Directory</a>%" + (w + 5) + "s-%n", getParentPath(path), "");
if (path.length() > 1) // add parent link if not root path for (File file : dir.listFiles()) {
f.format(" <a href=\"%s/\">Parent Directory</a>%" try {
+ (w + 5) + "s-%n", getParentPath(path), ""); String name = file.getName() + (file.isDirectory() ? "/" : "");
for (File file : dir.listFiles()) { String size = file.isDirectory() ? "- " : toSizeApproxString(file.length());
try { // properly url-encode the link
String name = file.getName() + (file.isDirectory() ? "/" : ""); String link = new URI(null, path + name, null).toASCIIString();
String size = file.isDirectory() ? "- " : toSizeApproxString(file.length()); if (!file.isHidden() && !name.startsWith("."))
// properly url-encode the link f.format(" <a href=\"%s\">%s</a>%-" + (w - name.length()) + "s&#8206;%td-%<tb-%<tY %<tR%6s%n",
String link = new URI(null, path + name, null).toASCIIString(); link, name, "", file.lastModified(), size);
if (!file.isHidden() && !name.startsWith(".")) } catch (URISyntaxException ignore) {
f.format(" <a href=\"%s\">%s</a>%-" + (w - name.length()) + }
"s&#8206;%td-%<tb-%<tY %<tR%6s%n", }
link, name, "", file.lastModified(), size); f.format("</pre></body></html>");
} catch (URISyntaxException ignore) {} return f.toString();
} }
f.format("</pre></body></html>");
return f.toString();
} }
/** /**