Use try-with-resources statements

- instead of finally blocks
- in cases of missing try-finally

Change-Id: I94f481a33d8e6a3180c436245d6e95e4d525280c
This commit is contained in:
Urs Wolfer
2015-06-11 21:44:59 +02:00
parent b17ceb8587
commit 5e90c63dea
112 changed files with 727 additions and 1332 deletions

View File

@@ -104,11 +104,8 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
rsp.setContentType("text/html");
rsp.setCharacterEncoding(HtmlDomUtil.ENC.name());
rsp.setContentLength(raw.length);
final OutputStream out = rsp.getOutputStream();
try {
try (OutputStream out = rsp.getOutputStream()) {
out.write(raw);
} finally {
out.close();
}
return;
}
@@ -129,13 +126,13 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
} else {
rsp.setContentType("text/html");
rsp.setCharacterEncoding(HtmlDomUtil.ENC.name());
final Writer out = rsp.getWriter();
out.write("<html>");
out.write("<body>");
out.write("<h1>Account Not Found</h1>");
out.write("</body>");
out.write("</html>");
out.close();
try (Writer out = rsp.getWriter()) {
out.write("<html>");
out.write("<body>");
out.write("<h1>Account Not Found</h1>");
out.write("</body>");
out.write("</html>");
}
}
}
@@ -147,8 +144,7 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
}
Element userlistElement = HtmlDomUtil.find(doc, "userlist");
ReviewDb db = schema.open();
try {
try (ReviewDb db = schema.open()) {
ResultSet<Account> accounts = db.accounts().firstNById(100);
for (Account a : accounts) {
String displayName;
@@ -168,8 +164,6 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
userlistElement.appendChild(linkElement);
userlistElement.appendChild(doc.createElement("br"));
}
} finally {
db.close();
}
return HtmlDomUtil.toUTF8(doc);
@@ -190,15 +184,10 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
}
private AuthResult byUserName(final String userName) {
try {
final ReviewDb db = schema.open();
try {
AccountExternalId.Key key =
new AccountExternalId.Key(SCHEME_USERNAME, userName);
return auth(db.accountExternalIds().get(key));
} finally {
db.close();
}
try (ReviewDb db = schema.open()) {
AccountExternalId.Key key =
new AccountExternalId.Key(SCHEME_USERNAME, userName);
return auth(db.accountExternalIds().get(key));
} catch (OrmException e) {
getServletContext().log("cannot query database", e);
return null;
@@ -206,14 +195,9 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
}
private AuthResult byPreferredEmail(final String email) {
try {
final ReviewDb db = schema.open();
try {
List<Account> matches = db.accounts().byPreferredEmail(email).toList();
return matches.size() == 1 ? auth(matches.get(0)) : null;
} finally {
db.close();
}
try (ReviewDb db = schema.open()) {
List<Account> matches = db.accounts().byPreferredEmail(email).toList();
return matches.size() == 1 ? auth(matches.get(0)) : null;
} catch (OrmException e) {
getServletContext().log("cannot query database", e);
return null;
@@ -227,13 +211,8 @@ class BecomeAnyAccountLoginServlet extends HttpServlet {
} catch (NumberFormatException nfe) {
return null;
}
try {
final ReviewDb db = schema.open();
try {
return auth(db.accounts().get(id));
} finally {
db.close();
}
try (ReviewDb db = schema.open()) {
return auth(db.accounts().get(id));
} catch (OrmException e) {
getServletContext().log("cannot query database", e);
return null;

View File

@@ -111,11 +111,8 @@ class HttpAuthFilter implements Filter {
rsp.setContentType("text/html");
rsp.setCharacterEncoding(HtmlDomUtil.ENC.name());
rsp.setContentLength(tosend.length);
final OutputStream out = rsp.getOutputStream();
try {
try (OutputStream out = rsp.getOutputStream()) {
out.write(tosend);
} finally {
out.close();
}
}
}

View File

@@ -104,12 +104,8 @@ class HttpLoginServlet extends HttpServlet {
rsp.setContentType("text/html");
rsp.setCharacterEncoding("UTF-8");
rsp.setContentLength(bin.length);
final ServletOutputStream out = rsp.getOutputStream();
try {
try (ServletOutputStream out = rsp.getOutputStream()) {
out.write(bin);
} finally {
out.flush();
out.close();
}
return;
}

View File

@@ -92,11 +92,8 @@ class LdapLoginServlet extends HttpServlet {
res.setContentType("text/html");
res.setCharacterEncoding("UTF-8");
res.setContentLength(bin.length);
ServletOutputStream out = res.getOutputStream();
try {
try (ServletOutputStream out = res.getOutputStream()) {
out.write(bin);
} finally {
out.close();
}
}

View File

@@ -72,11 +72,8 @@ class GitLogoServlet extends HttpServlet {
rsp.setDateHeader("Last-Modified", modified);
CacheHeaders.setCacheable(req, rsp, 5, TimeUnit.MINUTES);
final ServletOutputStream os = rsp.getOutputStream();
try {
try (ServletOutputStream os = rsp.getOutputStream()) {
os.write(raw);
} finally {
os.close();
}
} else {
CacheHeaders.setNotCacheable(rsp);

View File

@@ -101,11 +101,8 @@ abstract class GitwebCssServlet extends HttpServlet {
rsp.setDateHeader("Last-Modified", modified);
CacheHeaders.setCacheable(req, rsp, 5, TimeUnit.MINUTES);
final ServletOutputStream os = rsp.getOutputStream();
try {
try (ServletOutputStream os = rsp.getOutputStream()) {
os.write(toSend);
} finally {
os.close();
}
} else {
CacheHeaders.setNotCacheable(rsp);

View File

@@ -72,11 +72,8 @@ class GitwebJavaScriptServlet extends HttpServlet {
rsp.setDateHeader("Last-Modified", modified);
CacheHeaders.setCacheable(req, rsp, 5, TimeUnit.MINUTES);
final ServletOutputStream os = rsp.getOutputStream();
try {
try (ServletOutputStream os = rsp.getOutputStream()) {
os.write(raw);
} finally {
os.close();
}
} else {
CacheHeaders.setNotCacheable(rsp);

View File

@@ -414,19 +414,14 @@ class GitwebServlet extends HttpServlet {
return;
}
final Repository repo;
try {
repo = repoManager.openRepository(nameKey);
try (@SuppressWarnings("UnusedDeclaration") // only open for existence-check
Repository repo = repoManager.openRepository(nameKey)) {
CacheHeaders.setNotCacheable(rsp);
exec(req, rsp, project);
} catch (RepositoryNotFoundException e) {
getServletContext().log("Cannot open repository", e);
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
try {
CacheHeaders.setNotCacheable(rsp);
exec(req, rsp, project);
} finally {
repo.close();
}
}
@@ -476,25 +471,15 @@ class GitwebServlet extends HttpServlet {
proc.getOutputStream().close();
}
try {
final InputStream in;
try (InputStream in = new BufferedInputStream(proc.getInputStream(), bufferSize)) {
readCgiHeaders(rsp, in);
in = new BufferedInputStream(proc.getInputStream(), bufferSize);
try {
readCgiHeaders(rsp, in);
final OutputStream out = rsp.getOutputStream();
try {
final byte[] buf = new byte[bufferSize];
int n;
while ((n = in.read(buf)) > 0) {
out.write(buf, 0, n);
}
} finally {
out.close();
try (OutputStream out = rsp.getOutputStream()) {
final byte[] buf = new byte[bufferSize];
int n;
while ((n = in.read(buf)) > 0) {
out.write(buf, 0, n);
}
} finally {
in.close();
}
} catch (IOException e) {
// The browser has probably closed its input stream. We don't
@@ -651,16 +636,11 @@ class GitwebServlet extends HttpServlet {
new Thread(new Runnable() {
@Override
public void run() {
try {
final BufferedReader br =
new BufferedReader(new InputStreamReader(in, "ISO-8859-1"));
try {
String line;
while ((line = br.readLine()) != null) {
log.error("CGI: " + line);
}
} finally {
br.close();
try (BufferedReader br =
new BufferedReader(new InputStreamReader(in, "ISO-8859-1"))) {
String line;
while ((line = br.readLine()) != null) {
log.error("CGI: " + line);
}
} catch (IOException e) {
log.debug("Unexpected error copying stderr from CGI", e);

View File

@@ -411,18 +411,18 @@ class HttpPluginServlet extends HttpServlet
if (about != null) {
InputStreamReader isr = new InputStreamReader(scanner.getInputStream(about));
BufferedReader reader = new BufferedReader(isr);
StringBuilder aboutContent = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
aboutContent.append("\n");
} else {
aboutContent.append(line).append("\n");
try (BufferedReader reader = new BufferedReader(isr)) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
aboutContent.append("\n");
} else {
aboutContent.append(line).append("\n");
}
}
}
reader.close();
// Only append the About section if there was anything in it
if (aboutContent.toString().trim().length() > 0) {
@@ -641,11 +641,8 @@ class HttpPluginServlet extends HttpServlet
private static byte[] readWholeEntry(PluginContentScanner scanner, PluginEntry entry)
throws IOException {
byte[] data = new byte[entry.getSize().get().intValue()];
InputStream in = scanner.getInputStream(entry);
try {
try (InputStream in = scanner.getInputStream(entry)) {
IO.readFully(in, data, 0, data.length);
} finally {
in.close();
}
return data;
}

View File

@@ -128,25 +128,20 @@ public class HostPageServlet extends HttpServlet {
}
String src = "gerrit_ui/gerrit_ui.nocache.js";
InputStream in = servletContext.getResourceAsStream("/" + src);
if (in != null) {
Hasher md = Hashing.md5().newHasher();
try {
try {
final byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) > 0) {
md.putBytes(buf, 0, n);
}
} finally {
in.close();
try (InputStream in = servletContext.getResourceAsStream("/" + src)) {
if (in != null) {
Hasher md = Hashing.md5().newHasher();
final byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) > 0) {
md.putBytes(buf, 0, n);
}
} catch (IOException e) {
throw new IOException("Failed reading " + src, e);
src += "?content=" + md.hash().toString();
} else {
log.debug("No " + src + " in webapp root; keeping noncache.js URL");
}
src += "?content=" + md.hash().toString();
} else {
log.debug("No " + src + " in webapp root; keeping noncache.js URL");
} catch (IOException e) {
throw new IOException("Failed reading " + src, e);
}
noCacheName = src;
@@ -224,11 +219,8 @@ public class HostPageServlet extends HttpServlet {
rsp.setContentType("text/html");
rsp.setCharacterEncoding(HtmlDomUtil.ENC.name());
rsp.setContentLength(tosend.length);
final OutputStream out = rsp.getOutputStream();
try {
try (OutputStream out = rsp.getOutputStream()) {
out.write(tosend);
} finally {
out.close();
}
}

View File

@@ -70,11 +70,8 @@ public class LegacyGerritServlet extends HttpServlet {
rsp.setContentType("text/html");
rsp.setCharacterEncoding(HtmlDomUtil.ENC.name());
rsp.setContentLength(tosend.length);
final OutputStream out = rsp.getOutputStream();
try {
try (OutputStream out = rsp.getOutputStream()) {
out.write(tosend);
} finally {
out.close();
}
}
}

View File

@@ -90,11 +90,8 @@ public class SshInfoServlet extends HttpServlet {
CacheHeaders.setNotCacheable(rsp);
rsp.setCharacterEncoding("UTF-8");
rsp.setContentType("text/plain");
final PrintWriter w = rsp.getWriter();
try {
try (PrintWriter w = rsp.getWriter()) {
w.write(out);
} finally {
w.close();
}
}
}

View File

@@ -199,11 +199,8 @@ public class StaticServlet extends HttpServlet {
rsp.setHeader(ETAG, r.etag);
rsp.setContentType(r.contentType);
rsp.setContentLength(tosend.length);
final OutputStream out = rsp.getOutputStream();
try {
try (OutputStream out = rsp.getOutputStream()) {
out.write(tosend);
} finally {
out.close();
}
}

View File

@@ -82,11 +82,8 @@ public class ToolServlet extends HttpServlet {
rsp.setHeader(HDR_CACHE_CONTROL, "no-cache, must-revalidate");
rsp.setContentType("application/octet-stream");
rsp.setContentLength(tosend.length);
final OutputStream out = rsp.getOutputStream();
try {
try (OutputStream out = rsp.getOutputStream()) {
out.write(tosend);
} finally {
out.close();
}
}
@@ -148,11 +145,8 @@ public class ToolServlet extends HttpServlet {
rsp.setContentType("text/html");
rsp.setCharacterEncoding("UTF-8");
rsp.setContentLength(tosend.length);
final OutputStream out = rsp.getOutputStream();
try {
try (OutputStream out = rsp.getOutputStream()) {
out.write(tosend);
} finally {
out.close();
}
}
}

View File

@@ -522,8 +522,7 @@ public class RestApiServlet extends HttpServlet {
IllegalArgumentException, NoSuchMethodException, IllegalAccessException,
InstantiationException, InvocationTargetException, MethodNotAllowedException {
if (isType(JSON_TYPE, req.getContentType())) {
BufferedReader br = req.getReader();
try {
try (BufferedReader br = req.getReader()) {
JsonReader json = new JsonReader(br);
json.setLenient(true);
@@ -537,8 +536,6 @@ public class RestApiServlet extends HttpServlet {
return parseString(json.nextString(), type);
}
return OutputFormat.JSON.newGson().fromJson(json, type);
} finally {
br.close();
}
} else if (("PUT".equals(req.getMethod()) || "POST".equals(req.getMethod()))
&& acceptsRawInput(type)) {
@@ -548,8 +545,7 @@ public class RestApiServlet extends HttpServlet {
} else if (hasNoBody(req)) {
return createInstance(type);
} else if (isType("text/plain", req.getContentType())) {
BufferedReader br = req.getReader();
try {
try (BufferedReader br = req.getReader()) {
char[] tmp = new char[256];
StringBuilder sb = new StringBuilder();
int n;
@@ -557,8 +553,6 @@ public class RestApiServlet extends HttpServlet {
sb.append(tmp, 0, n);
}
return parseString(sb.toString(), type);
} finally {
br.close();
}
} else if ("POST".equals(req.getMethod())
&& isType(FORM_TYPE, req.getContentType())) {
@@ -772,11 +766,8 @@ public class RestApiServlet extends HttpServlet {
}
if (req == null || !"HEAD".equals(req.getMethod())) {
OutputStream dst = res.getOutputStream();
try {
try (OutputStream dst = res.getOutputStream()) {
bin.writeTo(dst);
} finally {
dst.close();
}
}
} finally {
@@ -1078,9 +1069,9 @@ public class RestApiServlet extends HttpServlet {
private static BinaryResult compress(BinaryResult bin)
throws IOException {
TemporaryBuffer.Heap buf = heap(HEAP_EST_SIZE, 20 << 20);
GZIPOutputStream gz = new GZIPOutputStream(buf);
bin.writeTo(gz);
gz.close();
try (GZIPOutputStream gz = new GZIPOutputStream(buf)) {
bin.writeTo(gz);
}
return asBinaryResult(buf).setContentType(bin.getContentType());
}