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

@@ -71,8 +71,7 @@ public class AccountCreator {
if (account != null) { if (account != null) {
return account; return account;
} }
ReviewDb db = reviewDbProvider.open(); try (ReviewDb db = reviewDbProvider.open()) {
try {
Account.Id id = new Account.Id(db.nextAccountId()); Account.Id id = new Account.Id(db.nextAccountId());
KeyPair sshKey = genSshKey(); KeyPair sshKey = genSshKey();
AccountSshKey key = AccountSshKey key =
@@ -115,8 +114,6 @@ public class AccountCreator {
new TestAccount(id, username, email, fullName, sshKey, httpPass); new TestAccount(id, username, email, fullName, sshKey, httpPass);
accounts.put(username, account); accounts.put(username, account);
return account; return account;
} finally {
db.close();
} }
} }

View File

@@ -58,8 +58,7 @@ public class GcAssert {
private String[] getPackFiles(Project.NameKey p) private String[] getPackFiles(Project.NameKey p)
throws RepositoryNotFoundException, IOException { throws RepositoryNotFoundException, IOException {
Repository repo = repoManager.openRepository(p); try (Repository repo = repoManager.openRepository(p)) {
try {
File packDir = new File(repo.getDirectory(), "objects/pack"); File packDir = new File(repo.getDirectory(), "objects/pack");
return packDir.list(new FilenameFilter() { return packDir.list(new FilenameFilter() {
@Override @Override
@@ -67,8 +66,6 @@ public class GcAssert {
return name.endsWith(".pack"); return name.endsWith(".pack");
} }
}); });
} finally {
repo.close();
} }
} }
} }

View File

@@ -115,8 +115,7 @@ public class VisibleRefFilterIT extends AbstractDaemonTest {
c2 = br.getChange().getId(); c2 = br.getChange().getId();
r2 = changeRefPrefix(c2); r2 = changeRefPrefix(c2);
Repository repo = repoManager.openRepository(project); try (Repository repo = repoManager.openRepository(project)) {
try {
// master-tag -> master // master-tag -> master
RefUpdate mtu = repo.updateRef("refs/tags/master-tag"); RefUpdate mtu = repo.updateRef("refs/tags/master-tag");
mtu.setExpectedOldObjectId(ObjectId.zeroId()); mtu.setExpectedOldObjectId(ObjectId.zeroId());
@@ -128,8 +127,6 @@ public class VisibleRefFilterIT extends AbstractDaemonTest {
btu.setExpectedOldObjectId(ObjectId.zeroId()); btu.setExpectedOldObjectId(ObjectId.zeroId());
btu.setNewObjectId(repo.getRef("refs/heads/branch").getObjectId()); btu.setNewObjectId(repo.getRef("refs/heads/branch").getObjectId());
assertThat(btu.update()).isEqualTo(RefUpdate.Result.NEW); assertThat(btu.update()).isEqualTo(RefUpdate.Result.NEW);
} finally {
repo.close();
} }
} }

View File

@@ -249,15 +249,12 @@ public abstract class AbstractSubmit extends AbstractDaemonTest {
ChangeInfo c = get(changeId, CURRENT_REVISION); ChangeInfo c = get(changeId, CURRENT_REVISION);
assertThat(c.currentRevision).isEqualTo(expectedId.name()); assertThat(c.currentRevision).isEqualTo(expectedId.name());
assertThat(c.revisions.get(expectedId.name())._number).isEqualTo(expectedNum); assertThat(c.revisions.get(expectedId.name())._number).isEqualTo(expectedNum);
Repository repo = try (Repository repo =
repoManager.openRepository(new Project.NameKey(c.project)); repoManager.openRepository(new Project.NameKey(c.project))) {
try {
Ref ref = repo.getRef( Ref ref = repo.getRef(
new PatchSet.Id(new Change.Id(c._number), expectedNum).toRefName()); new PatchSet.Id(new Change.Id(c._number), expectedNum).toRefName());
assertThat(ref).isNotNull(); assertThat(ref).isNotNull();
assertThat(ref.getObjectId()).isEqualTo(expectedId); assertThat(ref.getObjectId()).isEqualTo(expectedId);
} finally {
repo.close();
} }
} }

View File

@@ -263,13 +263,10 @@ public class CreateProjectIT extends AbstractDaemonTest {
private void assertHead(String projectName, String expectedRef) private void assertHead(String projectName, String expectedRef)
throws RepositoryNotFoundException, IOException { throws RepositoryNotFoundException, IOException {
Repository repo = try (Repository repo =
repoManager.openRepository(new Project.NameKey(projectName)); repoManager.openRepository(new Project.NameKey(projectName))) {
try {
assertThat(repo.getRef(Constants.HEAD).getTarget().getName()) assertThat(repo.getRef(Constants.HEAD).getTarget().getName())
.isEqualTo(expectedRef); .isEqualTo(expectedRef);
} finally {
repo.close();
} }
} }

View File

@@ -330,12 +330,9 @@ public class LabelTypeIT extends AbstractDaemonTest {
private void merge(PushOneCommit.Result r) throws Exception { private void merge(PushOneCommit.Result r) throws Exception {
revision(r).review(ReviewInput.approve()); revision(r).review(ReviewInput.approve());
revision(r).submit(); revision(r).submit();
Repository repo = repoManager.openRepository(project); try (Repository repo = repoManager.openRepository(project)) {
try {
assertThat(repo.getRef("refs/heads/master").getObjectId()).isEqualTo( assertThat(repo.getRef("refs/heads/master").getObjectId()).isEqualTo(
r.getCommitId()); r.getCommitId());
} finally {
repo.close();
} }
} }

View File

@@ -258,15 +258,10 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
@Override @Override
public void funnel(K from, PrimitiveSink into) { public void funnel(K from, PrimitiveSink into) {
try { try (ObjectOutputStream ser =
ObjectOutputStream ser = new ObjectOutputStream(new SinkOutputStream(into))) {
new ObjectOutputStream(new SinkOutputStream(into)); ser.writeObject(from);
try { ser.flush();
ser.writeObject(from);
ser.flush();
} finally {
ser.close();
}
} catch (IOException err) { } catch (IOException err) {
throw new RuntimeException("Cannot hash as Serializable", err); throw new RuntimeException("Cannot hash as Serializable", err);
} }

View File

@@ -77,19 +77,14 @@ public class CssLinker extends AbstractLinker {
private String name(final TreeLogger logger, final PublicResource r) private String name(final TreeLogger logger, final PublicResource r)
throws UnableToCompleteException { throws UnableToCompleteException {
final InputStream in = r.getContents(logger);
final ByteArrayOutputStream tmp = new ByteArrayOutputStream(); final ByteArrayOutputStream tmp = new ByteArrayOutputStream();
try { try (InputStream in = r.getContents(logger)) {
try { final byte[] buf = new byte[2048];
final byte[] buf = new byte[2048]; int n;
int n; while ((n = in.read(buf)) >= 0) {
while ((n = in.read(buf)) >= 0) { tmp.write(buf, 0, n);
tmp.write(buf, 0, n);
}
tmp.close();
} finally {
in.close();
} }
tmp.close();
} catch (IOException e) { } catch (IOException e) {
final UnableToCompleteException ute = new UnableToCompleteException(); final UnableToCompleteException ute = new UnableToCompleteException();
ute.initCause(e); ute.initCause(e);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -199,11 +199,8 @@ public class StaticServlet extends HttpServlet {
rsp.setHeader(ETAG, r.etag); rsp.setHeader(ETAG, r.etag);
rsp.setContentType(r.contentType); rsp.setContentType(r.contentType);
rsp.setContentLength(tosend.length); rsp.setContentLength(tosend.length);
final OutputStream out = rsp.getOutputStream(); try (OutputStream out = rsp.getOutputStream()) {
try {
out.write(tosend); 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.setHeader(HDR_CACHE_CONTROL, "no-cache, must-revalidate");
rsp.setContentType("application/octet-stream"); rsp.setContentType("application/octet-stream");
rsp.setContentLength(tosend.length); rsp.setContentLength(tosend.length);
final OutputStream out = rsp.getOutputStream(); try (OutputStream out = rsp.getOutputStream()) {
try {
out.write(tosend); out.write(tosend);
} finally {
out.close();
} }
} }
@@ -148,11 +145,8 @@ public class ToolServlet extends HttpServlet {
rsp.setContentType("text/html"); rsp.setContentType("text/html");
rsp.setCharacterEncoding("UTF-8"); rsp.setCharacterEncoding("UTF-8");
rsp.setContentLength(tosend.length); rsp.setContentLength(tosend.length);
final OutputStream out = rsp.getOutputStream(); try (OutputStream out = rsp.getOutputStream()) {
try {
out.write(tosend); out.write(tosend);
} finally {
out.close();
} }
} }
} }

View File

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

View File

@@ -102,16 +102,11 @@ public final class GerritLauncher {
return ""; return "";
} }
try { try (JarFile jar = new JarFile(me)) {
final JarFile jar = new JarFile(me); Manifest mf = jar.getManifest();
try { Attributes att = mf.getMainAttributes();
Manifest mf = jar.getManifest(); String val = att.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
Attributes att = mf.getMainAttributes(); return val != null ? val : "";
String val = att.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
return val != null ? val : "";
} finally {
jar.close();
}
} catch (IOException e) { } catch (IOException e) {
return ""; return "";
} }
@@ -202,28 +197,23 @@ public final class GerritLauncher {
} }
final SortedMap<String, URL> jars = new TreeMap<>(); final SortedMap<String, URL> jars = new TreeMap<>();
try { try (ZipFile zf = new ZipFile(path)) {
final ZipFile zf = new ZipFile(path); final Enumeration<? extends ZipEntry> e = zf.entries();
try { while (e.hasMoreElements()) {
final Enumeration<? extends ZipEntry> e = zf.entries(); final ZipEntry ze = e.nextElement();
while (e.hasMoreElements()) { if (ze.isDirectory()) {
final ZipEntry ze = e.nextElement(); continue;
if (ze.isDirectory()) { }
continue;
}
String name = ze.getName(); String name = ze.getName();
if (name.startsWith("WEB-INF/lib/")) { if (name.startsWith("WEB-INF/lib/")) {
extractJar(zf, ze, jars);
} else if (name.startsWith("WEB-INF/pgm-lib/")) {
// Some Prolog tools are restricted.
if (prologCompiler || !name.startsWith("WEB-INF/pgm-lib/prolog-")) {
extractJar(zf, ze, jars); extractJar(zf, ze, jars);
} else if (name.startsWith("WEB-INF/pgm-lib/")) {
// Some Prolog tools are restricted.
if (prologCompiler || !name.startsWith("WEB-INF/pgm-lib/prolog-")) {
extractJar(zf, ze, jars);
}
} }
} }
} finally {
zf.close();
} }
} catch (IOException e) { } catch (IOException e) {
throw new IOException("Cannot obtain libraries from " + path, e); throw new IOException("Cannot obtain libraries from " + path, e);
@@ -257,20 +247,13 @@ public final class GerritLauncher {
private static void extractJar(ZipFile zf, ZipEntry ze, private static void extractJar(ZipFile zf, ZipEntry ze,
SortedMap<String, URL> jars) throws IOException { SortedMap<String, URL> jars) throws IOException {
File tmp = createTempFile(safeName(ze), ".jar"); File tmp = createTempFile(safeName(ze), ".jar");
FileOutputStream out = new FileOutputStream(tmp); try (FileOutputStream out = new FileOutputStream(tmp);
try { InputStream in = zf.getInputStream(ze)) {
InputStream in = zf.getInputStream(ze); byte[] buf = new byte[4096];
try { int n;
byte[] buf = new byte[4096]; while ((n = in.read(buf, 0, buf.length)) > 0) {
int n; out.write(buf, 0, n);
while ((n = in.read(buf, 0, buf.length)) > 0) {
out.write(buf, 0, n);
}
} finally {
in.close();
} }
} finally {
out.close();
} }
String name = ze.getName(); String name = ze.getName();
@@ -363,24 +346,16 @@ public final class GerritLauncher {
final CodeSource src = final CodeSource src =
GerritLauncher.class.getProtectionDomain().getCodeSource(); GerritLauncher.class.getProtectionDomain().getCodeSource();
if (src != null) { if (src != null) {
try { try (InputStream in = src.getLocation().openStream()) {
final InputStream in = src.getLocation().openStream(); final File tmp = createTempFile("gerrit_", ".zip");
try { try (FileOutputStream out = new FileOutputStream(tmp)) {
final File tmp = createTempFile("gerrit_", ".zip"); final byte[] buf = new byte[4096];
final FileOutputStream out = new FileOutputStream(tmp); int n;
try { while ((n = in.read(buf, 0, buf.length)) > 0) {
final byte[] buf = new byte[4096]; out.write(buf, 0, n);
int n;
while ((n = in.read(buf, 0, buf.length)) > 0) {
out.write(buf, 0, n);
}
} finally {
out.close();
} }
return tmp;
} finally {
in.close();
} }
return tmp;
} catch (IOException e) { } catch (IOException e) {
// Nope, that didn't work. // Nope, that didn't work.
// //

View File

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

View File

@@ -63,11 +63,8 @@ class XrdsServlet extends HttpServlet {
rsp.setContentType("application/xrds+xml"); rsp.setContentType("application/xrds+xml");
rsp.setCharacterEncoding(ENC); rsp.setCharacterEncoding(ENC);
final ServletOutputStream out = rsp.getOutputStream(); try (ServletOutputStream out = rsp.getOutputStream()) {
try {
out.write(raw); out.write(raw);
} finally {
out.close();
} }
} }
} }

View File

@@ -40,13 +40,12 @@ public class Cat extends AbstractProgram {
name = "WEB-INF/" + fileName; name = "WEB-INF/" + fileName;
} }
final InputStream in = open(name); try (InputStream in = open(name)) {
if (in == null) { if (in == null) {
System.err.println("error: no such file " + fileName); System.err.println("error: no such file " + fileName);
return 1; return 1;
} }
try {
try { try {
final byte[] buf = new byte[4096]; final byte[] buf = new byte[4096];
int n; int n;
@@ -56,8 +55,6 @@ public class Cat extends AbstractProgram {
} finally { } finally {
System.out.flush(); System.out.flush();
} }
} finally {
in.close();
} }
return 0; return 0;
} }

View File

@@ -60,14 +60,11 @@ public class LocalUsernamesToLowerCase extends SiteProgram {
manager.start(); manager.start();
dbInjector.injectMembers(this); dbInjector.injectMembers(this);
final ReviewDb db = database.open(); try (ReviewDb db = database.open()) {
try {
todo = db.accountExternalIds().all().toList(); todo = db.accountExternalIds().all().toList();
synchronized (monitor) { synchronized (monitor) {
monitor.beginTask("Converting local username", todo.size()); monitor.beginTask("Converting local username", todo.size());
} }
} finally {
db.close();
} }
final List<Worker> workers = new ArrayList<>(threads); final List<Worker> workers = new ArrayList<>(threads);

View File

@@ -26,8 +26,7 @@ import java.util.zip.ZipFile;
public class Ls extends AbstractProgram { public class Ls extends AbstractProgram {
@Override @Override
public int run() throws IOException { public int run() throws IOException {
final ZipFile zf = new ZipFile(GerritLauncher.getDistributionArchive()); try (ZipFile zf = new ZipFile(GerritLauncher.getDistributionArchive())) {
try {
final Enumeration<? extends ZipEntry> e = zf.entries(); final Enumeration<? extends ZipEntry> e = zf.entries();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
final ZipEntry ze = e.nextElement(); final ZipEntry ze = e.nextElement();
@@ -48,8 +47,6 @@ public class Ls extends AbstractProgram {
System.out.println(name); System.out.println(name);
} }
} }
} finally {
zf.close();
} }
return 0; return 0;
} }

View File

@@ -47,14 +47,11 @@ public class ProtoGen extends AbstractProgram {
PrintWriter out = new PrintWriter( PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(o, "UTF-8")))) { new BufferedWriter(new OutputStreamWriter(o, "UTF-8")))) {
String header; String header;
InputStream in = getClass().getResourceAsStream("ProtoGenHeader.txt"); try (InputStream in = getClass().getResourceAsStream("ProtoGenHeader.txt")) {
try {
ByteBuffer buf = IO.readWholeStream(in, 1024); ByteBuffer buf = IO.readWholeStream(in, 1024);
int ptr = buf.arrayOffset() + buf.position(); int ptr = buf.arrayOffset() + buf.position();
int len = buf.remaining(); int len = buf.remaining();
header = new String(buf.array(), ptr, len, "UTF-8"); header = new String(buf.array(), ptr, len, "UTF-8");
} finally {
in.close();
} }
String version = com.google.gerrit.common.Version.getVersion(); String version = com.google.gerrit.common.Version.getVersion();

View File

@@ -92,11 +92,9 @@ public class ProtobufImport extends SiteProgram {
}); });
dbInjector.injectMembers(this); dbInjector.injectMembers(this);
ReviewDb db = schemaFactory.open();
ProgressMonitor progress = new TextProgressMonitor(); ProgressMonitor progress = new TextProgressMonitor();
progress.beginTask("Importing entities", ProgressMonitor.UNKNOWN); progress.beginTask("Importing entities", ProgressMonitor.UNKNOWN);
try { try (ReviewDb db = schemaFactory.open()) {
for (RelationModel model for (RelationModel model
: new JavaSchemaModel(ReviewDb.class).getRelations()) { : new JavaSchemaModel(ReviewDb.class).getRelations()) {
relations.put(model.getRelationID(), Relation.create(model, db)); relations.put(model.getRelationID(), Relation.create(model, db));
@@ -119,8 +117,6 @@ public class ProtobufImport extends SiteProgram {
} }
} }
progress.endTask(); progress.endTask();
} finally {
db.close();
} }
return 0; return 0;

View File

@@ -113,13 +113,11 @@ public class RebuildNotedb extends SiteProgram {
sysInjector.getInstance(GitRepositoryManager.class); sysInjector.getInstance(GitRepositoryManager.class);
final Project.NameKey allUsersName = final Project.NameKey allUsersName =
sysInjector.getInstance(AllUsersName.class); sysInjector.getInstance(AllUsersName.class);
final Repository allUsersRepo = try (Repository allUsersRepo =
repoManager.openMetadataRepository(allUsersName); repoManager.openMetadataRepository(allUsersName)) {
try {
deleteDraftRefs(allUsersRepo); deleteDraftRefs(allUsersRepo);
for (final Project.NameKey project : changesByProject.keySet()) { for (final Project.NameKey project : changesByProject.keySet()) {
final Repository repo = repoManager.openMetadataRepository(project); try (Repository repo = repoManager.openMetadataRepository(project)) {
try {
final BatchRefUpdate bru = repo.getRefDatabase().newBatchUpdate(); final BatchRefUpdate bru = repo.getRefDatabase().newBatchUpdate();
final BatchRefUpdate bruForDrafts = final BatchRefUpdate bruForDrafts =
allUsersRepo.getRefDatabase().newBatchUpdate(); allUsersRepo.getRefDatabase().newBatchUpdate();
@@ -158,12 +156,8 @@ public class RebuildNotedb extends SiteProgram {
log.error("Error rebuilding notedb", e); log.error("Error rebuilding notedb", e);
ok.set(false); ok.set(false);
break; break;
} finally {
repo.close();
} }
} }
} finally {
allUsersRepo.close();
} }
double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d; double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d;
@@ -231,16 +225,13 @@ public class RebuildNotedb extends SiteProgram {
// rebuilder threads to use the full connection pool. // rebuilder threads to use the full connection pool.
SchemaFactory<ReviewDb> schemaFactory = sysInjector.getInstance(Key.get( SchemaFactory<ReviewDb> schemaFactory = sysInjector.getInstance(Key.get(
new TypeLiteral<SchemaFactory<ReviewDb>>() {})); new TypeLiteral<SchemaFactory<ReviewDb>>() {}));
ReviewDb db = schemaFactory.open();
Multimap<Project.NameKey, Change> changesByProject = Multimap<Project.NameKey, Change> changesByProject =
ArrayListMultimap.create(); ArrayListMultimap.create();
try { try (ReviewDb db = schemaFactory.open()) {
for (Change c : db.changes().all()) { for (Change c : db.changes().all()) {
changesByProject.put(c.getProject(), c); changesByProject.put(c.getProject(), c);
} }
return changesByProject; return changesByProject;
} finally {
db.close();
} }
} }

View File

@@ -149,21 +149,18 @@ public class Reindex extends SiteProgram {
} }
private int indexAll() throws Exception { private int indexAll() throws Exception {
ReviewDb db = sysInjector.getInstance(ReviewDb.class);
ProgressMonitor pm = new TextProgressMonitor(); ProgressMonitor pm = new TextProgressMonitor();
pm.start(1); pm.start(1);
pm.beginTask("Collecting projects", ProgressMonitor.UNKNOWN); pm.beginTask("Collecting projects", ProgressMonitor.UNKNOWN);
Set<Project.NameKey> projects = Sets.newTreeSet(); Set<Project.NameKey> projects = Sets.newTreeSet();
int changeCount = 0; int changeCount = 0;
try { try (ReviewDb db = sysInjector.getInstance(ReviewDb.class)) {
for (Change change : db.changes().all()) { for (Change change : db.changes().all()) {
changeCount++; changeCount++;
if (projects.add(change.getProject())) { if (projects.add(change.getProject())) {
pm.update(1); pm.update(1);
} }
} }
} finally {
db.close();
} }
pm.endTask(); pm.endTask();

View File

@@ -81,8 +81,7 @@ public class Rulec extends SiteProgram {
boolean error = false; boolean error = false;
for (Project.NameKey project : names) { for (Project.NameKey project : names) {
Repository git = gitManager.openRepository(project); try (Repository git = gitManager.openRepository(project)) {
try {
switch (jarFactory.create(git).call()) { switch (jarFactory.create(git).call()) {
case NO_RULES: case NO_RULES:
if (!all || projectNames.contains(project.get())) { if (!all || projectNames.contains(project.get())) {
@@ -105,8 +104,6 @@ public class Rulec extends SiteProgram {
System.err.println("fatal: " + err.getMessage()); System.err.println("fatal: " + err.getMessage());
} }
error = true; error = true;
} finally {
git.close();
} }
} }

View File

@@ -56,11 +56,8 @@ class HiddenErrorHandler extends ErrorHandler {
try { try {
CacheHeaders.setNotCacheable(res); CacheHeaders.setNotCacheable(res);
} finally { } finally {
ServletOutputStream out = res.getOutputStream(); try (ServletOutputStream out = res.getOutputStream()) {
try {
out.write(msg); out.write(msg);
} finally {
out.close();
} }
} }
} }

View File

@@ -520,8 +520,7 @@ public class JettyServer {
} }
private static void unpack(File srcwar, File dstwar) throws IOException { private static void unpack(File srcwar, File dstwar) throws IOException {
final ZipFile zf = new ZipFile(srcwar); try (ZipFile zf = new ZipFile(srcwar)) {
try {
final Enumeration<? extends ZipEntry> e = zf.entries(); final Enumeration<? extends ZipEntry> e = zf.entries();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
final ZipEntry ze = e.nextElement(); final ZipEntry ze = e.nextElement();
@@ -539,24 +538,15 @@ public class JettyServer {
mkdir(rawtmp.getParentFile()); mkdir(rawtmp.getParentFile());
rawtmp.deleteOnExit(); rawtmp.deleteOnExit();
final FileOutputStream rawout = new FileOutputStream(rawtmp); try (FileOutputStream rawout = new FileOutputStream(rawtmp);
try { InputStream in = zf.getInputStream(ze)) {
final InputStream in = zf.getInputStream(ze); final byte[] buf = new byte[4096];
try { int n;
final byte[] buf = new byte[4096]; while ((n = in.read(buf, 0, buf.length)) > 0) {
int n; rawout.write(buf, 0, n);
while ((n = in.read(buf, 0, buf.length)) > 0) {
rawout.write(buf, 0, n);
}
} finally {
in.close();
} }
} finally {
rawout.close();
} }
} }
} finally {
zf.close();
} }
} }
@@ -632,14 +622,14 @@ public class JettyServer {
CacheHeaders.setNotCacheable(res); CacheHeaders.setNotCacheable(res);
Escaper html = HtmlEscapers.htmlEscaper(); Escaper html = HtmlEscapers.htmlEscaper();
PrintWriter w = res.getWriter(); try (PrintWriter w = res.getWriter()) {
w.write("<html><title>BUILD FAILED</title><body>"); w.write("<html><title>BUILD FAILED</title><body>");
w.format("<h1>%s FAILED</h1>", html.escape(rule)); w.format("<h1>%s FAILED</h1>", html.escape(rule));
w.write("<pre>"); w.write("<pre>");
w.write(html.escape(RawParseUtils.decode(why))); w.write(html.escape(RawParseUtils.decode(why)));
w.write("</pre>"); w.write("</pre>");
w.write("</body></html>"); w.write("</body></html>");
w.close(); }
} }
@Override @Override
@@ -667,12 +657,10 @@ public class JettyServer {
long start = TimeUtil.nowMs(); long start = TimeUtil.nowMs();
Process rebuild = proc.start(); Process rebuild = proc.start();
byte[] out; byte[] out;
InputStream in = rebuild.getInputStream(); try (InputStream in = rebuild.getInputStream()) {
try {
out = ByteStreams.toByteArray(in); out = ByteStreams.toByteArray(in);
} finally { } finally {
rebuild.getOutputStream().close(); rebuild.getOutputStream().close();
in.close();
} }
int status; int status;
@@ -692,12 +680,9 @@ public class JettyServer {
private static Properties loadBuckProperties(File gen) private static Properties loadBuckProperties(File gen)
throws FileNotFoundException, IOException { throws FileNotFoundException, IOException {
Properties properties = new Properties(); Properties properties = new Properties();
InputStream in = new FileInputStream( try (InputStream in = new FileInputStream(
new File(new File(gen, "tools"), "buck.properties")); new File(new File(gen, "tools"), "buck.properties"))) {
try {
properties.load(in); properties.load(in);
} finally {
in.close();
} }
return properties; return properties;
} }

View File

@@ -68,8 +68,7 @@ public class InitAdminUser implements InitStep {
return; return;
} }
ReviewDb db = dbFactory.open(); try (ReviewDb db = dbFactory.open()) {
try {
if (db.accounts().anyAccounts().toList().isEmpty()) { if (db.accounts().anyAccounts().toList().isEmpty()) {
ui.header("Gerrit Administrator"); ui.header("Gerrit Administrator");
if (ui.yesno(true, "Create administrator user")) { if (ui.yesno(true, "Create administrator user")) {
@@ -111,8 +110,6 @@ public class InitAdminUser implements InitStep {
} }
} }
} }
} finally {
db.close();
} }
} }

View File

@@ -171,13 +171,10 @@ public class InitPlugins implements InitStep {
} }
private static String getVersion(Path plugin) throws IOException { private static String getVersion(Path plugin) throws IOException {
JarFile jarFile = new JarFile(plugin.toFile()); try (JarFile jarFile = new JarFile(plugin.toFile())) {
try {
Manifest manifest = jarFile.getManifest(); Manifest manifest = jarFile.getManifest();
Attributes main = manifest.getMainAttributes(); Attributes main = manifest.getMainAttributes();
return main.getValue(Attributes.Name.IMPLEMENTATION_VERSION); return main.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
} finally {
jarFile.close();
} }
} }
} }

View File

@@ -79,11 +79,8 @@ public class AllProjectsConfig extends VersionedMetaData {
public AllProjectsConfig load() throws IOException, ConfigInvalidException { public AllProjectsConfig load() throws IOException, ConfigInvalidException {
File path = getPath(); File path = getPath();
if (path != null) { if (path != null) {
Repository repo = new FileRepository(path); try (Repository repo = new FileRepository(path)) {
try {
load(repo); load(repo);
} finally {
repo.close();
} }
} }
return this; return this;

View File

@@ -139,11 +139,8 @@ public class PrologCompiler implements Callable<PrologCompiler.Status> {
// Any leak of tmp caused by this method failing will be cleaned // Any leak of tmp caused by this method failing will be cleaned
// up by our caller when tempDir is recursively deleted. // up by our caller when tempDir is recursively deleted.
File tmp = File.createTempFile("rules", ".pl", tempDir); File tmp = File.createTempFile("rules", ".pl", tempDir);
FileOutputStream out = new FileOutputStream(tmp); try (FileOutputStream out = new FileOutputStream(tmp)) {
try {
git.open(blobId).copyTo(out); git.open(blobId).copyTo(out);
} finally {
out.close();
} }
return tmp; return tmp;
} }
@@ -157,9 +154,8 @@ public class PrologCompiler implements Callable<PrologCompiler.Status> {
DiagnosticCollector<JavaFileObject> diagnostics = DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<>(); new DiagnosticCollector<>();
StandardJavaFileManager fileManager = try (StandardJavaFileManager fileManager =
compiler.getStandardFileManager(diagnostics, null, null); compiler.getStandardFileManager(diagnostics, null, null)) {
try {
Iterable<? extends JavaFileObject> compilationUnits = fileManager Iterable<? extends JavaFileObject> compilationUnits = fileManager
.getJavaFileObjectsFromFiles(getAllFiles(tempDir, ".java")); .getJavaFileObjectsFromFiles(getAllFiles(tempDir, ".java"));
ArrayList<String> options = new ArrayList<>(); ArrayList<String> options = new ArrayList<>();
@@ -195,8 +191,6 @@ public class PrologCompiler implements Callable<PrologCompiler.Status> {
} }
throw new CompileException(msg.toString()); throw new CompileException(msg.toString());
} }
} finally {
fileManager.close();
} }
} }
@@ -247,8 +241,7 @@ public class PrologCompiler implements Callable<PrologCompiler.Status> {
jarAdd.setTime(now); jarAdd.setTime(now);
out.putNextEntry(jarAdd); out.putNextEntry(jarAdd);
if (f.isFile()) { if (f.isFile()) {
FileInputStream in = new FileInputStream(f); try (FileInputStream in = new FileInputStream(f)) {
try {
while (true) { while (true) {
int nRead = in.read(buffer, 0, buffer.length); int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0) { if (nRead <= 0) {
@@ -256,8 +249,6 @@ public class PrologCompiler implements Callable<PrologCompiler.Status> {
} }
out.write(buffer, 0, nRead); out.write(buffer, 0, nRead);
} }
} finally {
in.close();
} }
} }
out.closeEntry(); out.closeEntry();

View File

@@ -943,15 +943,10 @@ public class ChangeHookRunner implements ChangeHooks, EventDispatcher,
ps = pb.start(); ps = pb.start();
ps.getOutputStream().close(); ps.getOutputStream().close();
InputStream is = ps.getInputStream();
String output = null; String output = null;
try { try (InputStream is = ps.getInputStream()) {
output = readOutput(is); output = readOutput(is);
} finally { } finally {
try {
is.close();
} catch (IOException closeErr) {
}
ps.waitFor(); ps.waitFor();
result = new HookResult(ps.exitValue(), output); result = new HookResult(ps.exitValue(), output);
} }

View File

@@ -265,27 +265,19 @@ public class RulesCache {
private String read(Project.NameKey project, ObjectId rulesId) private String read(Project.NameKey project, ObjectId rulesId)
throws CompileException { throws CompileException {
Repository git; try (Repository git = gitMgr.openRepository(project)) {
try { try {
git = gitMgr.openRepository(project); ObjectLoader ldr = git.open(rulesId, Constants.OBJ_BLOB);
} catch (RepositoryNotFoundException e) { byte[] raw = ldr.getCachedBytes(SRC_LIMIT);
throw new CompileException("Cannot open repository " + project, e); return RawParseUtils.decode(raw);
} catch (LargeObjectException e) {
throw new CompileException("rules of " + project + " are too large", e);
} catch (RuntimeException | IOException e) {
throw new CompileException("Cannot load rules of " + project, e);
}
} catch (IOException e) { } catch (IOException e) {
throw new CompileException("Cannot open repository " + project, e); throw new CompileException("Cannot open repository " + project, e);
} }
try {
ObjectLoader ldr = git.open(rulesId, Constants.OBJ_BLOB);
byte[] raw = ldr.getCachedBytes(SRC_LIMIT);
return RawParseUtils.decode(raw);
} catch (LargeObjectException e) {
throw new CompileException("rules of " + project + " are too large", e);
} catch (RuntimeException e) {
throw new CompileException("Cannot load rules of " + project, e);
} catch (IOException e) {
throw new CompileException("Cannot load rules of " + project, e);
} finally {
git.close();
}
} }
private BufferingPrologControl newEmptyMachine(ClassLoader cl) { private BufferingPrologControl newEmptyMachine(ClassLoader cl) {

View File

@@ -106,9 +106,8 @@ public class ApprovalCopier {
TreeMap<Integer, PatchSet> patchSets = getPatchSets(cd); TreeMap<Integer, PatchSet> patchSets = getPatchSets(cd);
NavigableSet<Integer> allPsIds = patchSets.navigableKeySet(); NavigableSet<Integer> allPsIds = patchSets.navigableKeySet();
Repository repo = try (Repository repo =
repoManager.openRepository(project.getProject().getNameKey()); repoManager.openRepository(project.getProject().getNameKey())) {
try {
// Walk patch sets strictly less than current in descending order. // Walk patch sets strictly less than current in descending order.
Collection<PatchSet> allPrior = patchSets.descendingMap() Collection<PatchSet> allPrior = patchSets.descendingMap()
.tailMap(ps.getId().get(), false) .tailMap(ps.getId().get(), false)
@@ -132,8 +131,6 @@ public class ApprovalCopier {
} }
} }
return labelNormalizer.normalize(ctl, byUser.values()).getNormalized(); return labelNormalizer.normalize(ctl, byUser.values()).getNormalized();
} finally {
repo.close();
} }
} catch (IOException e) { } catch (IOException e) {
throw new OrmException(e); throw new OrmException(e);

View File

@@ -382,8 +382,7 @@ public class ChangeUtil {
throw new NoSuchChangeException(patchSetId.getParentKey()); throw new NoSuchChangeException(patchSetId.getParentKey());
} }
Repository repo = gitManager.openRepository(change.getProject()); try (Repository repo = gitManager.openRepository(change.getProject())) {
try {
RefUpdate update = repo.updateRef(patch.getRefName()); RefUpdate update = repo.updateRef(patch.getRefName());
update.setForceUpdate(true); update.setForceUpdate(true);
update.disableRefLog(); update.disableRefLog();
@@ -399,8 +398,6 @@ public class ChangeUtil {
" in " + repo.getDirectory() + ": " + update.getResult()); " in " + repo.getDirectory() + ": " + update.getResult());
} }
gitRefUpdated.fire(change.getProject(), update, ReceiveCommand.Type.DELETE); gitRefUpdated.fire(change.getProject(), update, ReceiveCommand.Type.DELETE);
} finally {
repo.close();
} }
ReviewDb db = this.db.get(); ReviewDb db = this.db.get();

View File

@@ -364,19 +364,11 @@ public class PatchLineCommentsUtil {
} }
private Set<String> getRefNamesAllUsers(String prefix) throws OrmException { private Set<String> getRefNamesAllUsers(String prefix) throws OrmException {
Repository repo; try (Repository repo = repoManager.openRepository(allUsers)) {
try {
repo = repoManager.openRepository(allUsers);
} catch (IOException e) {
throw new OrmException(e);
}
try {
RefDatabase refDb = repo.getRefDatabase(); RefDatabase refDb = repo.getRefDatabase();
return refDb.getRefs(prefix).keySet(); return refDb.getRefs(prefix).keySet();
} catch (IOException e) { } catch (IOException e) {
throw new OrmException(e); throw new OrmException(e);
} finally {
repo.close();
} }
} }

View File

@@ -39,15 +39,12 @@ public class ProjectUtil {
public static boolean branchExists(final GitRepositoryManager repoManager, public static boolean branchExists(final GitRepositoryManager repoManager,
final Branch.NameKey branch) throws RepositoryNotFoundException, final Branch.NameKey branch) throws RepositoryNotFoundException,
IOException { IOException {
final Repository repo = repoManager.openRepository(branch.getParentKey()); try (Repository repo = repoManager.openRepository(branch.getParentKey())) {
try {
boolean exists = repo.getRefDatabase().exactRef(branch.get()) != null; boolean exists = repo.getRefDatabase().exactRef(branch.get()) != null;
if (!exists) { if (!exists) {
exists = repo.getFullBranch().equals(branch.get()); exists = repo.getFullBranch().equals(branch.get());
} }
return exists; return exists;
} finally {
repo.close();
} }
} }
} }

View File

@@ -92,8 +92,7 @@ public class AccountByEmailCacheImpl implements AccountByEmailCache {
@Override @Override
public Set<Account.Id> load(String email) throws Exception { public Set<Account.Id> load(String email) throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
Set<Account.Id> r = Sets.newHashSet(); Set<Account.Id> r = Sets.newHashSet();
for (Account a : db.accounts().byPreferredEmail(email)) { for (Account a : db.accounts().byPreferredEmail(email)) {
r.add(a.getId()); r.add(a.getId());
@@ -103,8 +102,6 @@ public class AccountByEmailCacheImpl implements AccountByEmailCache {
r.add(a.getAccountId()); r.add(a.getAccountId());
} }
return ImmutableSet.copyOf(r); return ImmutableSet.copyOf(r);
} finally {
db.close();
} }
} }
} }

View File

@@ -142,16 +142,13 @@ public class AccountCacheImpl implements AccountCache {
@Override @Override
public AccountState load(Account.Id key) throws Exception { public AccountState load(Account.Id key) throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
final AccountState state = load(db, key); final AccountState state = load(db, key);
String user = state.getUserName(); String user = state.getUserName();
if (user != null) { if (user != null) {
byName.put(user, Optional.of(state.getAccount().getId())); byName.put(user, Optional.of(state.getAccount().getId()));
} }
return state; return state;
} finally {
db.close();
} }
} }
@@ -192,8 +189,7 @@ public class AccountCacheImpl implements AccountCache {
@Override @Override
public Optional<Account.Id> load(String username) throws Exception { public Optional<Account.Id> load(String username) throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
final AccountExternalId.Key key = new AccountExternalId.Key( // final AccountExternalId.Key key = new AccountExternalId.Key( //
AccountExternalId.SCHEME_USERNAME, // AccountExternalId.SCHEME_USERNAME, //
username); username);
@@ -202,8 +198,6 @@ public class AccountCacheImpl implements AccountCache {
return Optional.of(id.getAccountId()); return Optional.of(id.getAccountId());
} }
return Optional.absent(); return Optional.absent();
} finally {
db.close();
} }
} }
} }

View File

@@ -83,13 +83,10 @@ public class AccountManager {
*/ */
public Account.Id lookup(String externalId) throws AccountException { public Account.Id lookup(String externalId) throws AccountException {
try { try {
ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
AccountExternalId ext = AccountExternalId ext =
db.accountExternalIds().get(new AccountExternalId.Key(externalId)); db.accountExternalIds().get(new AccountExternalId.Key(externalId));
return ext != null ? ext.getAccountId() : null; return ext != null ? ext.getAccountId() : null;
} finally {
db.close();
} }
} catch (OrmException e) { } catch (OrmException e) {
throw new AccountException("Cannot lookup account " + externalId, e); throw new AccountException("Cannot lookup account " + externalId, e);
@@ -107,8 +104,7 @@ public class AccountManager {
public AuthResult authenticate(AuthRequest who) throws AccountException { public AuthResult authenticate(AuthRequest who) throws AccountException {
who = realm.authenticate(who); who = realm.authenticate(who);
try { try {
ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
AccountExternalId.Key key = id(who); AccountExternalId.Key key = id(who);
AccountExternalId id = db.accountExternalIds().get(key); AccountExternalId id = db.accountExternalIds().get(key);
if (id == null) { if (id == null) {
@@ -128,8 +124,6 @@ public class AccountManager {
return new AuthResult(id.getAccountId(), key, false); return new AuthResult(id.getAccountId(), key, false);
} }
} finally {
db.close();
} }
} catch (OrmException e) { } catch (OrmException e) {
throw new AccountException("Authentication error", e); throw new AccountException("Authentication error", e);
@@ -324,8 +318,7 @@ public class AccountManager {
*/ */
public AuthResult link(Account.Id to, AuthRequest who) public AuthResult link(Account.Id to, AuthRequest who)
throws AccountException, OrmException { throws AccountException, OrmException {
ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
who = realm.link(db, to, who); who = realm.link(db, to, who);
AccountExternalId.Key key = id(who); AccountExternalId.Key key = id(who);
@@ -357,8 +350,6 @@ public class AccountManager {
return new AuthResult(to, key, false); return new AuthResult(to, key, false);
} finally {
db.close();
} }
} }
@@ -377,8 +368,7 @@ public class AccountManager {
*/ */
public AuthResult updateLink(Account.Id to, AuthRequest who) throws OrmException, public AuthResult updateLink(Account.Id to, AuthRequest who) throws OrmException,
AccountException { AccountException {
ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
AccountExternalId.Key key = id(who); AccountExternalId.Key key = id(who);
List<AccountExternalId.Key> filteredKeysByScheme = List<AccountExternalId.Key> filteredKeysByScheme =
filterKeysByScheme(key.getScheme(), db.accountExternalIds() filterKeysByScheme(key.getScheme(), db.accountExternalIds()
@@ -390,8 +380,6 @@ public class AccountManager {
} }
byIdCache.evict(to); byIdCache.evict(to);
return link(to, who); return link(to, who);
} finally {
db.close();
} }
} }
@@ -417,8 +405,7 @@ public class AccountManager {
*/ */
public AuthResult unlink(Account.Id from, AuthRequest who) public AuthResult unlink(Account.Id from, AuthRequest who)
throws AccountException, OrmException { throws AccountException, OrmException {
ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
who = realm.unlink(db, from, who); who = realm.unlink(db, from, who);
AccountExternalId.Key key = id(who); AccountExternalId.Key key = id(who);
@@ -446,8 +433,6 @@ public class AccountManager {
return new AuthResult(from, key, false); return new AuthResult(from, key, false);
} finally {
db.close();
} }
} }

View File

@@ -86,14 +86,11 @@ public class GetPreferences implements RestReadView<AccountResource> {
throw new ResourceNotFoundException(); throw new ResourceNotFoundException();
} }
Repository git = gitMgr.openRepository(allUsersName); try (Repository git = gitMgr.openRepository(allUsersName)) {
try {
VersionedAccountPreferences p = VersionedAccountPreferences p =
VersionedAccountPreferences.forUser(rsrc.getUser().getAccountId()); VersionedAccountPreferences.forUser(rsrc.getUser().getAccountId());
p.load(git); p.load(git);
return new PreferenceInfo(a.getGeneralPreferences(), p, git); return new PreferenceInfo(a.getGeneralPreferences(), p, git);
} finally {
git.close();
} }
} }

View File

@@ -152,13 +152,8 @@ public class GroupCacheImpl implements GroupCache {
@Override @Override
public Iterable<AccountGroup> all() { public Iterable<AccountGroup> all() {
try { try (ReviewDb db = schema.open()) {
ReviewDb db = schema.open(); return Collections.unmodifiableList(db.accountGroups().all().toList());
try {
return Collections.unmodifiableList(db.accountGroups().all().toList());
} finally {
db.close();
}
} catch (OrmException e) { } catch (OrmException e) {
log.warn("Cannot list internal groups", e); log.warn("Cannot list internal groups", e);
return Collections.emptyList(); return Collections.emptyList();
@@ -187,11 +182,8 @@ public class GroupCacheImpl implements GroupCache {
@Override @Override
public Optional<AccountGroup> load(final AccountGroup.Id key) public Optional<AccountGroup> load(final AccountGroup.Id key)
throws Exception { throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
return Optional.fromNullable(db.accountGroups().get(key)); return Optional.fromNullable(db.accountGroups().get(key));
} finally {
db.close();
} }
} }
} }
@@ -207,16 +199,13 @@ public class GroupCacheImpl implements GroupCache {
@Override @Override
public Optional<AccountGroup> load(String name) public Optional<AccountGroup> load(String name)
throws Exception { throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
AccountGroup.NameKey key = new AccountGroup.NameKey(name); AccountGroup.NameKey key = new AccountGroup.NameKey(name);
AccountGroupName r = db.accountGroupNames().get(key); AccountGroupName r = db.accountGroupNames().get(key);
if (r != null) { if (r != null) {
return Optional.fromNullable(db.accountGroups().get(r.getId())); return Optional.fromNullable(db.accountGroups().get(r.getId()));
} }
return Optional.absent(); return Optional.absent();
} finally {
db.close();
} }
} }
} }
@@ -232,8 +221,7 @@ public class GroupCacheImpl implements GroupCache {
@Override @Override
public Optional<AccountGroup> load(String uuid) public Optional<AccountGroup> load(String uuid)
throws Exception { throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
List<AccountGroup> r; List<AccountGroup> r;
r = db.accountGroups().byUUID(new AccountGroup.UUID(uuid)).toList(); r = db.accountGroups().byUUID(new AccountGroup.UUID(uuid)).toList();
@@ -244,8 +232,6 @@ public class GroupCacheImpl implements GroupCache {
} else { } else {
throw new OrmDuplicateKeyException("Duplicate group UUID " + uuid); throw new OrmDuplicateKeyException("Duplicate group UUID " + uuid);
} }
} finally {
db.close();
} }
} }
} }

View File

@@ -144,8 +144,7 @@ public class GroupIncludeCacheImpl implements GroupIncludeCache {
@Override @Override
public Set<AccountGroup.UUID> load(AccountGroup.UUID key) throws Exception { public Set<AccountGroup.UUID> load(AccountGroup.UUID key) throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
List<AccountGroup> group = db.accountGroups().byUUID(key).toList(); List<AccountGroup> group = db.accountGroups().byUUID(key).toList();
if (group.size() != 1) { if (group.size() != 1) {
return Collections.emptySet(); return Collections.emptySet();
@@ -157,8 +156,6 @@ public class GroupIncludeCacheImpl implements GroupIncludeCache {
ids.add(agi.getIncludeUUID()); ids.add(agi.getIncludeUUID());
} }
return ImmutableSet.copyOf(ids); return ImmutableSet.copyOf(ids);
} finally {
db.close();
} }
} }
} }
@@ -174,8 +171,7 @@ public class GroupIncludeCacheImpl implements GroupIncludeCache {
@Override @Override
public Set<AccountGroup.UUID> load(AccountGroup.UUID key) throws Exception { public Set<AccountGroup.UUID> load(AccountGroup.UUID key) throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
Set<AccountGroup.Id> ids = Sets.newHashSet(); Set<AccountGroup.Id> ids = Sets.newHashSet();
for (AccountGroupById agi : db.accountGroupById() for (AccountGroupById agi : db.accountGroupById()
.byIncludeUUID(key)) { .byIncludeUUID(key)) {
@@ -187,8 +183,6 @@ public class GroupIncludeCacheImpl implements GroupIncludeCache {
groupArray.add(g.getGroupUUID()); groupArray.add(g.getGroupUUID());
} }
return ImmutableSet.copyOf(groupArray); return ImmutableSet.copyOf(groupArray);
} finally {
db.close();
} }
} }
} }
@@ -204,8 +198,7 @@ public class GroupIncludeCacheImpl implements GroupIncludeCache {
@Override @Override
public Set<AccountGroup.UUID> load(String key) throws Exception { public Set<AccountGroup.UUID> load(String key) throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
Set<AccountGroup.UUID> ids = Sets.newHashSet(); Set<AccountGroup.UUID> ids = Sets.newHashSet();
for (AccountGroupById agi : db.accountGroupById().all()) { for (AccountGroupById agi : db.accountGroupById().all()) {
if (!AccountGroup.isInternalGroup(agi.getIncludeUUID())) { if (!AccountGroup.isInternalGroup(agi.getIncludeUUID())) {
@@ -213,8 +206,6 @@ public class GroupIncludeCacheImpl implements GroupIncludeCache {
} }
} }
return ImmutableSet.copyOf(ids); return ImmutableSet.copyOf(ids);
} finally {
db.close();
} }
} }
} }

View File

@@ -307,8 +307,7 @@ public class LdapRealm extends AbstractRealm {
@Override @Override
public Optional<Account.Id> load(String username) throws Exception { public Optional<Account.Id> load(String username) throws Exception {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
final AccountExternalId extId = final AccountExternalId extId =
db.accountExternalIds().get( db.accountExternalIds().get(
new AccountExternalId.Key(SCHEME_GERRIT, username)); new AccountExternalId.Key(SCHEME_GERRIT, username));
@@ -316,8 +315,6 @@ public class LdapRealm extends AbstractRealm {
return Optional.of(extId.getAccountId()); return Optional.of(extId.getAccountId());
} }
return Optional.absent(); return Optional.absent();
} finally {
db.close();
} }
} }
} }

View File

@@ -109,8 +109,7 @@ public class Mergeable implements RestReadView<RevisionResource> {
} }
result.submitType = rec.type; result.submitType = rec.type;
Repository git = gitManager.openRepository(change.getProject()); try (Repository git = gitManager.openRepository(change.getProject())) {
try {
ObjectId commit = toId(ps); ObjectId commit = toId(ps);
if (commit == null) { if (commit == null) {
result.mergeable = false; result.mergeable = false;
@@ -150,8 +149,6 @@ public class Mergeable implements RestReadView<RevisionResource> {
} }
} }
} }
} finally {
git.close();
} }
return result; return result;
} }

View File

@@ -356,25 +356,19 @@ public class RebaseChange {
public boolean canRebase(Project.NameKey project, PatchSet.Id patchSetId, public boolean canRebase(Project.NameKey project, PatchSet.Id patchSetId,
Branch.NameKey branch) { Branch.NameKey branch) {
Repository git; try (Repository git = gitManager.openRepository(project)) {
try { try (RevWalk rw = new RevWalk(git)) {
git = gitManager.openRepository(project); findBaseRevision(patchSetId, db.get(), branch, git, rw);
} catch (RepositoryNotFoundException err) { return true;
return false; } catch (InvalidChangeOperationException e) {
return false;
} catch (OrmException | IOException e) {
log.warn("Error checking if patch set " + patchSetId + " on " + branch
+ " can be rebased", e);
return false;
}
} catch (IOException err) { } catch (IOException err) {
return false; return false;
} }
try (RevWalk rw = new RevWalk(git)) {
findBaseRevision(patchSetId, db.get(), branch, git, rw);
return true;
} catch (InvalidChangeOperationException e) {
return false;
} catch (OrmException | IOException e) {
log.warn("Error checking if patch set " + patchSetId + " on " + branch
+ " can be rebased", e);
return false;
} finally {
git.close();
}
} }
} }

View File

@@ -41,14 +41,11 @@ public class GetPreferences implements RestReadView<ConfigResource> {
@Override @Override
public PreferenceInfo apply(ConfigResource rsrc) public PreferenceInfo apply(ConfigResource rsrc)
throws IOException, ConfigInvalidException { throws IOException, ConfigInvalidException {
Repository git = gitMgr.openRepository(allUsersName); try (Repository git = gitMgr.openRepository(allUsersName)) {
try {
VersionedAccountPreferences p = VersionedAccountPreferences p =
VersionedAccountPreferences.forDefault(); VersionedAccountPreferences.forDefault();
p.load(git); p.load(git);
return new PreferenceInfo(null, p, git); return new PreferenceInfo(null, p, git);
} finally {
git.close();
} }
} }
} }

View File

@@ -176,11 +176,10 @@ class EncryptedContactStore implements ContactStore {
final byte[] zText = compress(name, date, rawText); final byte[] zText = compress(name, date, rawText);
final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final ByteArrayOutputStream buf = new ByteArrayOutputStream();
final ArmoredOutputStream aout = new ArmoredOutputStream(buf); try (ArmoredOutputStream aout = new ArmoredOutputStream(buf);
final OutputStream cout = cpk().open(aout, zText.length); OutputStream cout = cpk().open(aout, zText.length)) {
cout.write(zText); cout.write(zText);
cout.close(); }
aout.close();
return buf.toByteArray(); return buf.toByteArray();
} }
@@ -195,12 +194,13 @@ class EncryptedContactStore implements ContactStore {
} }
comdg = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); comdg = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
final OutputStream out = try (OutputStream out =
new PGPLiteralDataGenerator().open(comdg.open(buf), new PGPLiteralDataGenerator().open(comdg.open(buf),
PGPLiteralData.BINARY, fileName, len, fileDate); PGPLiteralData.BINARY, fileName, len, fileDate)) {
out.write(plainText); out.write(plainText);
out.close(); } finally {
comdg.close(); comdg.close(); // PGPCompressedDataGenerator doesn't implement Closable
}
return buf.toByteArray(); return buf.toByteArray();
} }
@@ -220,30 +220,25 @@ class EncryptedContactStore implements ContactStore {
field(b, "Full-Name", account.getFullName()); field(b, "Full-Name", account.getFullName());
field(b, "Preferred-Email", account.getPreferredEmail()); field(b, "Preferred-Email", account.getPreferredEmail());
try { try (ReviewDb db = schema.open()) {
final ReviewDb db = schema.open(); for (final AccountExternalId e : db.accountExternalIds().byAccount(
try { account.getId())) {
for (final AccountExternalId e : db.accountExternalIds().byAccount( final StringBuilder oistr = new StringBuilder();
account.getId())) { if (e.getEmailAddress() != null && e.getEmailAddress().length() > 0) {
final StringBuilder oistr = new StringBuilder(); if (oistr.length() > 0) {
if (e.getEmailAddress() != null && e.getEmailAddress().length() > 0) { oistr.append(' ');
if (oistr.length() > 0) {
oistr.append(' ');
}
oistr.append(e.getEmailAddress());
} }
if (e.isScheme(AccountExternalId.SCHEME_MAILTO)) { oistr.append(e.getEmailAddress());
if (oistr.length() > 0) {
oistr.append(' ');
}
oistr.append('<');
oistr.append(e.getExternalId());
oistr.append('>');
}
field(b, "Identity", oistr.toString());
} }
} finally { if (e.isScheme(AccountExternalId.SCHEME_MAILTO)) {
db.close(); if (oistr.length() > 0) {
oistr.append(' ');
}
oistr.append('<');
oistr.append(e.getExternalId());
oistr.append('>');
}
field(b, "Identity", oistr.toString());
} }
} catch (OrmException e) { } catch (OrmException e) {
throw new ContactInformationStoreException(e); throw new ContactInformationStoreException(e);

View File

@@ -55,11 +55,8 @@ public class HttpContactStoreConnection implements ContactStoreConnection {
throw new IOException("Connection failed: " + conn.getResponseCode()); throw new IOException("Connection failed: " + conn.getResponseCode());
} }
final byte[] dst = new byte[2]; final byte[] dst = new byte[2];
final InputStream in = conn.getInputStream(); try (InputStream in = conn.getInputStream()) {
try {
IO.readFully(in, dst, 0, 2); IO.readFully(in, dst, 0, 2);
} finally {
in.close();
} }
if (dst[0] != 'O' || dst[1] != 'K') { if (dst[0] != 'O' || dst[1] != 'K') {
throw new IOException("Store failed: " + dst[0] + dst[1]); throw new IOException("Store failed: " + dst[0] + dst[1]);

View File

@@ -156,17 +156,10 @@ public class MarkdownFormatter {
throw new FileNotFoundException("Resource " + name); throw new FileNotFoundException("Resource " + name);
} }
file.set("file".equals(url.getProtocol())); file.set("file".equals(url.getProtocol()));
InputStream in = url.openStream(); try (InputStream in = url.openStream();
try { TemporaryBuffer.Heap tmp = new TemporaryBuffer.Heap(128 * 1024)) {
TemporaryBuffer.Heap tmp = new TemporaryBuffer.Heap(128 * 1024); tmp.copy(in);
try { return new String(tmp.toByteArray(), "UTF-8");
tmp.copy(in);
return new String(tmp.toByteArray(), "UTF-8");
} finally {
tmp.close();
}
} finally {
in.close();
} }
} }
} }

View File

@@ -110,19 +110,16 @@ public class QueryDocumentationExecutor {
return null; return null;
} }
ZipInputStream zip = new ZipInputStream(index); try (ZipInputStream zip = new ZipInputStream(index)) {
try {
ZipEntry entry; ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) { while ((entry = zip.getNextEntry()) != null) {
IndexOutput out = dir.createOutput(entry.getName(), null); try (IndexOutput out = dir.createOutput(entry.getName(), null)) {
int count; int count;
while ((count = zip.read(buffer)) != -1) { while ((count = zip.read(buffer)) != -1) {
out.writeBytes(buffer, count); out.writeBytes(buffer, count);
}
} }
out.close();
} }
} finally {
zip.close();
} }
// We must NOT call dir.close() here, as DirectoryReader.open() expects an opened directory. // We must NOT call dir.close() here, as DirectoryReader.open() expects an opened directory.
return dir; return dir;

View File

@@ -180,11 +180,8 @@ public class ChangeEditUtil {
public void delete(ChangeEdit edit) public void delete(ChangeEdit edit)
throws IOException { throws IOException {
Change change = edit.getChange(); Change change = edit.getChange();
Repository repo = gitManager.openRepository(change.getProject()); try (Repository repo = gitManager.openRepository(change.getProject())) {
try {
deleteRef(repo, edit); deleteRef(repo, edit);
} finally {
repo.close();
} }
indexer.index(db.get(), change); indexer.index(db.get(), change);
} }

View File

@@ -229,39 +229,34 @@ public class EventFactory {
public void addDependencies(ChangeAttribute ca, Change change) { public void addDependencies(ChangeAttribute ca, Change change) {
ca.dependsOn = new ArrayList<>(); ca.dependsOn = new ArrayList<>();
ca.neededBy = new ArrayList<>(); ca.neededBy = new ArrayList<>();
try { try (ReviewDb db = schema.open()) {
final ReviewDb db = schema.open(); final PatchSet.Id psId = change.currentPatchSetId();
try { for (PatchSetAncestor a : db.patchSetAncestors().ancestorsOf(psId)) {
final PatchSet.Id psId = change.currentPatchSetId(); for (PatchSet p :
for (PatchSetAncestor a : db.patchSetAncestors().ancestorsOf(psId)) { db.patchSets().byRevision(a.getAncestorRevision())) {
for (PatchSet p : Change c = db.changes().get(p.getId().getParentKey());
db.patchSets().byRevision(a.getAncestorRevision())) { ca.dependsOn.add(newDependsOn(c, p));
Change c = db.changes().get(p.getId().getParentKey());
ca.dependsOn.add(newDependsOn(c, p));
}
} }
}
final PatchSet ps = db.patchSets().get(psId); final PatchSet ps = db.patchSets().get(psId);
if (ps == null) { if (ps == null) {
log.error("Error while generating the list of descendants for" log.error("Error while generating the list of descendants for"
+ " PatchSet " + psId + ": Cannot find PatchSet entry in" + " PatchSet " + psId + ": Cannot find PatchSet entry in"
+ " database."); + " database.");
} else { } else {
final RevId revId = ps.getRevision(); final RevId revId = ps.getRevision();
for (PatchSetAncestor a : db.patchSetAncestors().descendantsOf(revId)) { for (PatchSetAncestor a : db.patchSetAncestors().descendantsOf(revId)) {
final PatchSet p = db.patchSets().get(a.getPatchSet()); final PatchSet p = db.patchSets().get(a.getPatchSet());
if (p == null) { if (p == null) {
log.error("Error while generating the list of descendants for" log.error("Error while generating the list of descendants for"
+ " revision " + revId.get() + ": Cannot find PatchSet entry in" + " revision " + revId.get() + ": Cannot find PatchSet entry in"
+ " database for " + a.getPatchSet()); + " database for " + a.getPatchSet());
continue; continue;
}
final Change c = db.changes().get(p.getId().getParentKey());
ca.neededBy.add(newNeededBy(c, p));
} }
final Change c = db.changes().get(p.getId().getParentKey());
ca.neededBy.add(newNeededBy(c, p));
} }
} finally {
db.close();
} }
} catch (OrmException e) { } catch (OrmException e) {
// Squash DB exceptions and leave dependency lists partially filled. // Squash DB exceptions and leave dependency lists partially filled.
@@ -401,38 +396,33 @@ public class EventFactory {
p.createdOn = patchSet.getCreatedOn().getTime() / 1000L; p.createdOn = patchSet.getCreatedOn().getTime() / 1000L;
p.isDraft = patchSet.isDraft(); p.isDraft = patchSet.isDraft();
final PatchSet.Id pId = patchSet.getId(); final PatchSet.Id pId = patchSet.getId();
try { try (ReviewDb db = schema.open()) {
final ReviewDb db = schema.open(); p.parents = new ArrayList<>();
try { for (PatchSetAncestor a : db.patchSetAncestors().ancestorsOf(
p.parents = new ArrayList<>(); patchSet.getId())) {
for (PatchSetAncestor a : db.patchSetAncestors().ancestorsOf( p.parents.add(a.getAncestorRevision().get());
patchSet.getId())) {
p.parents.add(a.getAncestorRevision().get());
}
UserIdentity author = psInfoFactory.get(db, pId).getAuthor();
if (author.getAccount() == null) {
p.author = new AccountAttribute();
p.author.email = author.getEmail();
p.author.name = author.getName();
p.author.username = "";
} else {
p.author = asAccountAttribute(author.getAccount());
}
Change change = db.changes().get(pId.getParentKey());
List<Patch> list =
patchListCache.get(change, patchSet).toPatchList(pId);
for (Patch pe : list) {
if (!Patch.COMMIT_MSG.equals(pe.getFileName())) {
p.sizeDeletions -= pe.getDeletions();
p.sizeInsertions += pe.getInsertions();
}
}
p.kind = changeKindCache.getChangeKind(db, change, patchSet);
} finally {
db.close();
} }
UserIdentity author = psInfoFactory.get(db, pId).getAuthor();
if (author.getAccount() == null) {
p.author = new AccountAttribute();
p.author.email = author.getEmail();
p.author.name = author.getName();
p.author.username = "";
} else {
p.author = asAccountAttribute(author.getAccount());
}
Change change = db.changes().get(pId.getParentKey());
List<Patch> list =
patchListCache.get(change, patchSet).toPatchList(pId);
for (Patch pe : list) {
if (!Patch.COMMIT_MSG.equals(pe.getFileName())) {
p.sizeDeletions -= pe.getDeletions();
p.sizeInsertions += pe.getInsertions();
}
}
p.kind = changeKindCache.getChangeKind(db, change, patchSet);
} catch (OrmException e) { } catch (OrmException e) {
log.error("Cannot load patch set data for " + patchSet.getId(), e); log.error("Cannot load patch set data for " + patchSet.getId(), e);
} catch (PatchSetInfoNotAvailableException e) { } catch (PatchSetInfoNotAvailableException e) {

View File

@@ -86,9 +86,7 @@ public class GarbageCollection {
GarbageCollectionResult.Error.Type.GC_ALREADY_SCHEDULED, projectName)); GarbageCollectionResult.Error.Type.GC_ALREADY_SCHEDULED, projectName));
} }
for (Project.NameKey p : projectsToGc) { for (Project.NameKey p : projectsToGc) {
Repository repo = null; try (Repository repo = repoManager.openRepository(p)) {
try {
repo = repoManager.openRepository(p);
logGcConfiguration(p, repo, aggressive); logGcConfiguration(p, repo, aggressive);
print(writer, "collecting garbage for \"" + p + "\":\n"); print(writer, "collecting garbage for \"" + p + "\":\n");
GarbageCollectCommand gc = Git.wrap(repo).gc(); GarbageCollectCommand gc = Git.wrap(repo).gc();
@@ -110,9 +108,6 @@ public class GarbageCollection {
result.addError(new GarbageCollectionResult.Error( result.addError(new GarbageCollectionResult.Error(
GarbageCollectionResult.Error.Type.GC_FAILED, p)); GarbageCollectionResult.Error.Type.GC_FAILED, p));
} finally { } finally {
if (repo != null) {
repo.close();
}
gcQueue.gcFinished(p); gcQueue.gcFinished(p);
} }
} }

View File

@@ -302,11 +302,8 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
@Override @Override
public String getProjectDescription(final Project.NameKey name) public String getProjectDescription(final Project.NameKey name)
throws RepositoryNotFoundException, IOException { throws RepositoryNotFoundException, IOException {
final Repository e = openRepository(name); try (Repository e = openRepository(name)) {
try {
return getProjectDescription(e); return getProjectDescription(e);
} finally {
e.close();
} }
} }
@@ -337,31 +334,26 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
final String description) { final String description) {
// Update git's description file, in case gitweb is being used // Update git's description file, in case gitweb is being used
// //
try { try (Repository e = openRepository(name)) {
final Repository e = openRepository(name); final String old = getProjectDescription(e);
try { if ((old == null && description == null)
final String old = getProjectDescription(e); || (old != null && old.equals(description))) {
if ((old == null && description == null) return;
|| (old != null && old.equals(description))) { }
return;
}
final LockFile f = new LockFile(new File(e.getDirectory(), "description"), FS.DETECTED); final LockFile f = new LockFile(new File(e.getDirectory(), "description"), FS.DETECTED);
if (f.lock()) { if (f.lock()) {
String d = description; String d = description;
if (d != null) { if (d != null) {
d = d.trim(); d = d.trim();
if (d.length() > 0) { if (d.length() > 0) {
d += "\n"; d += "\n";
}
} else {
d = "";
} }
f.write(Constants.encode(d)); } else {
f.commit(); d = "";
} }
} finally { f.write(Constants.encode(d));
e.close(); f.commit();
} }
} catch (RepositoryNotFoundException e) { } catch (RepositoryNotFoundException e) {
log.error("Cannot update description for " + name, e); log.error("Cannot update description for " + name, e);

View File

@@ -1031,13 +1031,8 @@ public class MergeOp {
@Override @Override
public void run() { public void run() {
PatchSet patchSet; PatchSet patchSet;
try { try (ReviewDb reviewDb = schemaFactory.open()) {
ReviewDb reviewDb = schemaFactory.open(); patchSet = reviewDb.patchSets().get(c.currentPatchSetId());
try {
patchSet = reviewDb.patchSets().get(c.currentPatchSetId());
} finally {
reviewDb.close();
}
} catch (Exception e) { } catch (Exception e) {
logError("Cannot send email for submitted patch set " + c.getId(), e); logError("Cannot send email for submitted patch set " + c.getId(), e);
return; return;
@@ -1193,13 +1188,8 @@ public class MergeOp {
@Override @Override
public void run() { public void run() {
PatchSet patchSet; PatchSet patchSet;
try { try (ReviewDb reviewDb = schemaFactory.open()) {
ReviewDb reviewDb = schemaFactory.open(); patchSet = reviewDb.patchSets().get(c.currentPatchSetId());
try {
patchSet = reviewDb.patchSets().get(c.currentPatchSetId());
} finally {
reviewDb.close();
}
} catch (Exception e) { } catch (Exception e) {
logError("Cannot send email notifications about merge failure", e); logError("Cannot send email notifications about merge failure", e);
return; return;

View File

@@ -1719,11 +1719,8 @@ public class ReceiveCommits {
if (caller == Thread.currentThread()) { if (caller == Thread.currentThread()) {
insertChange(db); insertChange(db);
} else { } else {
ReviewDb db = schemaFactory.open(); try (ReviewDb db = schemaFactory.open()) {
try {
insertChange(db); insertChange(db);
} finally {
db.close();
} }
} }
synchronized (newProgress) { synchronized (newProgress) {
@@ -2093,11 +2090,8 @@ public class ReceiveCommits {
} else if (caller == Thread.currentThread()) { } else if (caller == Thread.currentThread()) {
return insertPatchSet(db); return insertPatchSet(db);
} else { } else {
ReviewDb db = schemaFactory.open(); try (ReviewDb db = schemaFactory.open()) {
try {
return insertPatchSet(db); return insertPatchSet(db);
} finally {
db.close();
} }
} }
} finally { } finally {
@@ -2347,11 +2341,8 @@ public class ReceiveCommits {
if (caller == Thread.currentThread()) { if (caller == Thread.currentThread()) {
updateGroups(db); updateGroups(db);
} else { } else {
ReviewDb db = schemaFactory.open(); try (ReviewDb db = schemaFactory.open()) {
try {
updateGroups(db); updateGroups(db);
} finally {
db.close();
} }
} }
return null; return null;

View File

@@ -95,8 +95,8 @@ public class ScanningChangeCacheImpl implements ChangeCache {
@Override @Override
public List<Change> load(Project.NameKey key) throws Exception { public List<Change> load(Project.NameKey key) throws Exception {
Repository repo = repoManager.openRepository(key); try (Repository repo = repoManager.openRepository(key);
try (ManualRequestContext ctx = requestContext.open()) { ManualRequestContext ctx = requestContext.open()) {
ReviewDb db = ctx.getReviewDbProvider().get(); ReviewDb db = ctx.getReviewDbProvider().get();
Map<String, Ref> refs = Map<String, Ref> refs =
repo.getRefDatabase().getRefs(RefNames.REFS_CHANGES); repo.getRefDatabase().getRefs(RefNames.REFS_CHANGES);
@@ -114,8 +114,6 @@ public class ScanningChangeCacheImpl implements ChangeCache {
Iterables.addAll(changes, db.changes().get(batch)); Iterables.addAll(changes, db.changes().get(batch));
} }
return changes; return changes;
} finally {
repo.close();
} }
} }

View File

@@ -67,13 +67,8 @@ class DbGroupMemberAuditListener implements GroupMemberAuditListener {
new AccountGroupMemberAudit(m, me, TimeUtil.nowTs()); new AccountGroupMemberAudit(m, me, TimeUtil.nowTs());
auditInserts.add(audit); auditInserts.add(audit);
} }
try { try (ReviewDb db = schema.open()) {
ReviewDb db = schema.open(); db.accountGroupMembersAudit().insert(auditInserts);
try {
db.accountGroupMembersAudit().insert(auditInserts);
} finally {
db.close();
}
} catch (OrmException e) { } catch (OrmException e) {
logOrmExceptionForAccounts( logOrmExceptionForAccounts(
"Cannot log add accounts to group event performed by user", me, "Cannot log add accounts to group event performed by user", me,
@@ -86,33 +81,28 @@ class DbGroupMemberAuditListener implements GroupMemberAuditListener {
Collection<AccountGroupMember> removed) { Collection<AccountGroupMember> removed) {
List<AccountGroupMemberAudit> auditInserts = Lists.newLinkedList(); List<AccountGroupMemberAudit> auditInserts = Lists.newLinkedList();
List<AccountGroupMemberAudit> auditUpdates = Lists.newLinkedList(); List<AccountGroupMemberAudit> auditUpdates = Lists.newLinkedList();
try { try (ReviewDb db = schema.open()) {
ReviewDb db = schema.open(); for (AccountGroupMember m : removed) {
try { AccountGroupMemberAudit audit = null;
for (AccountGroupMember m : removed) { for (AccountGroupMemberAudit a : db.accountGroupMembersAudit()
AccountGroupMemberAudit audit = null; .byGroupAccount(m.getAccountGroupId(), m.getAccountId())) {
for (AccountGroupMemberAudit a : db.accountGroupMembersAudit() if (a.isActive()) {
.byGroupAccount(m.getAccountGroupId(), m.getAccountId())) { audit = a;
if (a.isActive()) { break;
audit = a;
break;
}
}
if (audit != null) {
audit.removed(me, TimeUtil.nowTs());
auditUpdates.add(audit);
} else {
audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs());
audit.removedLegacy();
auditInserts.add(audit);
} }
} }
db.accountGroupMembersAudit().update(auditUpdates);
db.accountGroupMembersAudit().insert(auditInserts); if (audit != null) {
} finally { audit.removed(me, TimeUtil.nowTs());
db.close(); auditUpdates.add(audit);
} else {
audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs());
audit.removedLegacy();
auditInserts.add(audit);
}
} }
db.accountGroupMembersAudit().update(auditUpdates);
db.accountGroupMembersAudit().insert(auditInserts);
} catch (OrmException e) { } catch (OrmException e) {
logOrmExceptionForAccounts( logOrmExceptionForAccounts(
"Cannot log delete accounts from group event performed by user", me, "Cannot log delete accounts from group event performed by user", me,
@@ -129,13 +119,8 @@ class DbGroupMemberAuditListener implements GroupMemberAuditListener {
new AccountGroupByIdAud(groupInclude, me, TimeUtil.nowTs()); new AccountGroupByIdAud(groupInclude, me, TimeUtil.nowTs());
includesAudit.add(audit); includesAudit.add(audit);
} }
try { try (ReviewDb db = schema.open()) {
ReviewDb db = schema.open(); db.accountGroupByIdAud().insert(includesAudit);
try {
db.accountGroupByIdAud().insert(includesAudit);
} finally {
db.close();
}
} catch (OrmException e) { } catch (OrmException e) {
logOrmExceptionForGroups( logOrmExceptionForGroups(
"Cannot log add groups to group event performed by user", me, added, "Cannot log add groups to group event performed by user", me, added,
@@ -147,28 +132,23 @@ class DbGroupMemberAuditListener implements GroupMemberAuditListener {
public void onDeleteGroupsFromGroup(Account.Id me, public void onDeleteGroupsFromGroup(Account.Id me,
Collection<AccountGroupById> removed) { Collection<AccountGroupById> removed) {
final List<AccountGroupByIdAud> auditUpdates = Lists.newLinkedList(); final List<AccountGroupByIdAud> auditUpdates = Lists.newLinkedList();
try { try (ReviewDb db = schema.open()) {
ReviewDb db = schema.open(); for (final AccountGroupById g : removed) {
try { AccountGroupByIdAud audit = null;
for (final AccountGroupById g : removed) { for (AccountGroupByIdAud a : db.accountGroupByIdAud()
AccountGroupByIdAud audit = null; .byGroupInclude(g.getGroupId(), g.getIncludeUUID())) {
for (AccountGroupByIdAud a : db.accountGroupByIdAud() if (a.isActive()) {
.byGroupInclude(g.getGroupId(), g.getIncludeUUID())) { audit = a;
if (a.isActive()) { break;
audit = a;
break;
}
}
if (audit != null) {
audit.removed(me, TimeUtil.nowTs());
auditUpdates.add(audit);
} }
} }
db.accountGroupByIdAud().update(auditUpdates);
} finally { if (audit != null) {
db.close(); audit.removed(me, TimeUtil.nowTs());
auditUpdates.add(audit);
}
} }
db.accountGroupByIdAud().update(auditUpdates);
} catch (OrmException e) { } catch (OrmException e) {
logOrmExceptionForGroups( logOrmExceptionForGroups(
"Cannot log delete groups from group event performed by user", me, "Cannot log delete groups from group event performed by user", me,

View File

@@ -235,12 +235,12 @@ public class SiteIndexer {
@Override @Override
public Void call() throws Exception { public Void call() throws Exception {
Multimap<ObjectId, ChangeData> byId = ArrayListMultimap.create(); Multimap<ObjectId, ChangeData> byId = ArrayListMultimap.create();
Repository repo = null; // TODO(dborowitz): Opening all repositories in a live server may be
ReviewDb db = null; // wasteful; see if we can determine which ones it is safe to close
try { // with RepositoryCache.close(repo).
repo = repoManager.openRepository(project); try (Repository repo = repoManager.openRepository(project);
ReviewDb db = schemaFactory.open()) {
Map<String, Ref> refs = repo.getRefDatabase().getRefs(ALL); Map<String, Ref> refs = repo.getRefDatabase().getRefs(ALL);
db = schemaFactory.open();
for (Change c : changeCache.get(project)) { for (Change c : changeCache.get(project)) {
Ref r = refs.get(c.currentPatchSetId().toRefName()); Ref r = refs.get(c.currentPatchSetId().toRefName());
if (r != null) { if (r != null) {
@@ -256,16 +256,6 @@ public class SiteIndexer {
verboseWriter).call(); verboseWriter).call();
} catch (RepositoryNotFoundException rnfe) { } catch (RepositoryNotFoundException rnfe) {
log.error(rnfe.getMessage()); log.error(rnfe.getMessage());
} finally {
if (db != null) {
db.close();
}
if (repo != null) {
repo.close();
}
// TODO(dborowitz): Opening all repositories in a live server may be
// wasteful; see if we can determine which ones it is safe to close
// with RepositoryCache.close(repo).
} }
return null; return null;
} }

View File

@@ -406,27 +406,23 @@ public abstract class ChangeEmail extends NotificationEmail {
TemporaryBuffer.Heap buf = TemporaryBuffer.Heap buf =
new TemporaryBuffer.Heap(Math.min(HEAP_EST_SIZE, maxSize), maxSize); new TemporaryBuffer.Heap(Math.min(HEAP_EST_SIZE, maxSize), maxSize);
try (DiffFormatter fmt = new DiffFormatter(buf)) { try (DiffFormatter fmt = new DiffFormatter(buf)) {
Repository git; try (Repository git = args.server.openRepository(change.getProject())) {
try { try {
git = args.server.openRepository(change.getProject()); fmt.setRepository(git);
fmt.setDetectRenames(true);
fmt.format(patchList.getOldId(), patchList.getNewId());
return RawParseUtils.decode(buf.toByteArray());
} catch (IOException e) {
if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
return "";
}
log.error("Cannot format patch", e);
return "";
}
} catch (IOException e) { } catch (IOException e) {
log.error("Cannot open repository to format patch", e); log.error("Cannot open repository to format patch", e);
return ""; return "";
} }
try {
fmt.setRepository(git);
fmt.setDetectRenames(true);
fmt.format(patchList.getOldId(), patchList.getNewId());
return RawParseUtils.decode(buf.toByteArray());
} catch (IOException e) {
if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
return "";
}
log.error("Cannot format patch", e);
return "";
} finally {
git.close();
}
} }
} }
} }

View File

@@ -116,8 +116,7 @@ public class CommentSender extends ReplyToChangeSender {
public String getInlineComments(int lines) { public String getInlineComments(int lines) {
StringBuilder cmts = new StringBuilder(); StringBuilder cmts = new StringBuilder();
final Repository repo = getRepository(); try (Repository repo = getRepository()) {
try {
PatchList patchList = null; PatchList patchList = null;
if (repo != null) { if (repo != null) {
try { try {
@@ -164,10 +163,6 @@ public class CommentSender extends ReplyToChangeSender {
} }
cmts.append("\n\n"); cmts.append("\n\n");
} }
} finally {
if (repo != null) {
repo.close();
}
} }
return cmts.toString(); return cmts.toString();
} }

View File

@@ -192,8 +192,8 @@ public class SmtpEmailSender implements EmailSender {
} }
} }
Writer w = client.sendMessageData(); Writer messageDataWriter = client.sendMessageData();
if (w == null) { if (messageDataWriter == null) {
/* Include rejected recipient error messages here to not lose that /* Include rejected recipient error messages here to not lose that
* information. That piece of the puzzle is vital if zero recipients * information. That piece of the puzzle is vital if zero recipients
* are accepted and the server consequently rejects the DATA command. * are accepted and the server consequently rejects the DATA command.
@@ -201,21 +201,20 @@ public class SmtpEmailSender implements EmailSender {
throw new EmailException(rejected + "Server " + smtpHost throw new EmailException(rejected + "Server " + smtpHost
+ " rejected DATA command: " + client.getReplyString()); + " rejected DATA command: " + client.getReplyString());
} }
w = new BufferedWriter(w); try (Writer w = new BufferedWriter(messageDataWriter)) {
for (Map.Entry<String, EmailHeader> h : hdrs.entrySet()) {
for (Map.Entry<String, EmailHeader> h : hdrs.entrySet()) { if (!h.getValue().isEmpty()) {
if (!h.getValue().isEmpty()) { w.write(h.getKey());
w.write(h.getKey()); w.write(": ");
w.write(": "); h.getValue().write(w);
h.getValue().write(w); w.write("\r\n");
w.write("\r\n"); }
} }
}
w.write("\r\n"); w.write("\r\n");
w.write(body); w.write(body);
w.flush(); w.flush();
w.close(); }
if (!client.completePendingCommand()) { if (!client.completePendingCommand()) {
throw new EmailException("Server " + smtpHost throw new EmailException("Server " + smtpHost

View File

@@ -54,19 +54,11 @@ public abstract class AbstractChangeNotes<T> extends VersionedMetaData {
loadDefaults(); loadDefaults();
return self(); return self();
} }
Repository repo; try (Repository repo = repoManager.openMetadataRepository(getProjectName())) {
try {
repo = repoManager.openMetadataRepository(getProjectName());
} catch (IOException e) {
throw new OrmException(e);
}
try {
load(repo); load(repo);
loaded = true; loaded = true;
} catch (ConfigInvalidException | IOException e) { } catch (ConfigInvalidException | IOException e) {
throw new OrmException(e); throw new OrmException(e);
} finally {
repo.close();
} }
return self(); return self();
} }
@@ -77,15 +69,9 @@ public abstract class AbstractChangeNotes<T> extends VersionedMetaData {
} else if (!migration.enabled()) { } else if (!migration.enabled()) {
return null; return null;
} }
Repository repo; try (Repository repo = repoManager.openMetadataRepository(getProjectName())) {
try { Ref ref = repo.getRefDatabase().exactRef(getRefName());
repo = repoManager.openMetadataRepository(getProjectName()); return ref != null ? ref.getObjectId() : null;
try {
Ref ref = repo.getRefDatabase().exactRef(getRefName());
return ref != null ? ref.getObjectId() : null;
} finally {
repo.close();
}
} catch (IOException e) { } catch (IOException e) {
throw new OrmException(e); throw new OrmException(e);
} }

View File

@@ -93,13 +93,10 @@ public abstract class AbstractChangeUpdate extends VersionedMetaData {
private void load() throws IOException { private void load() throws IOException {
if (migration.writeChanges() && getRevision() == null) { if (migration.writeChanges() && getRevision() == null) {
Repository repo = repoManager.openMetadataRepository(getProjectName()); try (Repository repo = repoManager.openMetadataRepository(getProjectName())) {
try {
load(repo); load(repo);
} catch (ConfigInvalidException e) { } catch (ConfigInvalidException e) {
throw new IOException(e); throw new IOException(e);
} finally {
repo.close();
} }
} }
} }

View File

@@ -439,82 +439,82 @@ public class CommentsInNotesUtil {
public byte[] buildNote(List<PatchLineComment> comments) { public byte[] buildNote(List<PatchLineComment> comments) {
ByteArrayOutputStream buf = new ByteArrayOutputStream(); ByteArrayOutputStream buf = new ByteArrayOutputStream();
OutputStreamWriter streamWriter = new OutputStreamWriter(buf, UTF_8); OutputStreamWriter streamWriter = new OutputStreamWriter(buf, UTF_8);
PrintWriter writer = new PrintWriter(streamWriter); try (PrintWriter writer = new PrintWriter(streamWriter)) {
PatchLineComment first = comments.get(0); PatchLineComment first = comments.get(0);
short side = first.getSide(); short side = first.getSide();
PatchSet.Id psId = PatchLineCommentsUtil.getCommentPsId(first); PatchSet.Id psId = PatchLineCommentsUtil.getCommentPsId(first);
appendHeaderField(writer, side == 0 appendHeaderField(writer, side == 0
? BASE_PATCH_SET ? BASE_PATCH_SET
: PATCH_SET, : PATCH_SET,
Integer.toString(psId.get())); Integer.toString(psId.get()));
appendHeaderField(writer, REVISION, first.getRevId().get()); appendHeaderField(writer, REVISION, first.getRevId().get());
String currentFilename = null; String currentFilename = null;
for (PatchLineComment c : comments) { for (PatchLineComment c : comments) {
PatchSet.Id currentPsId = PatchLineCommentsUtil.getCommentPsId(c); PatchSet.Id currentPsId = PatchLineCommentsUtil.getCommentPsId(c);
checkArgument(psId.equals(currentPsId), checkArgument(psId.equals(currentPsId),
"All comments being added must all have the same PatchSet.Id. The" "All comments being added must all have the same PatchSet.Id. The"
+ "comment below does not have the same PatchSet.Id as the others " + "comment below does not have the same PatchSet.Id as the others "
+ "(%s).\n%s", psId.toString(), c.toString()); + "(%s).\n%s", psId.toString(), c.toString());
checkArgument(side == c.getSide(), checkArgument(side == c.getSide(),
"All comments being added must all have the same side. The" "All comments being added must all have the same side. The"
+ "comment below does not have the same side as the others " + "comment below does not have the same side as the others "
+ "(%s).\n%s", side, c.toString()); + "(%s).\n%s", side, c.toString());
String commentFilename = String commentFilename =
QuotedString.GIT_PATH.quote(c.getKey().getParentKey().getFileName()); QuotedString.GIT_PATH.quote(c.getKey().getParentKey().getFileName());
if (!commentFilename.equals(currentFilename)) { if (!commentFilename.equals(currentFilename)) {
currentFilename = commentFilename; currentFilename = commentFilename;
writer.print("File: "); writer.print("File: ");
writer.print(commentFilename); writer.print(commentFilename);
writer.print("\n\n");
}
// The CommentRange field for a comment is allowed to be null.
// If it is indeed null, then in the first line, we simply use the line
// number field for a comment instead. If it isn't null, we write the
// comment range itself.
CommentRange range = c.getRange();
if (range != null) {
writer.print(range.getStartLine());
writer.print(':');
writer.print(range.getStartCharacter());
writer.print('-');
writer.print(range.getEndLine());
writer.print(':');
writer.print(range.getEndCharacter());
} else {
writer.print(c.getLine());
}
writer.print("\n");
writer.print(formatTime(serverIdent, c.getWrittenOn()));
writer.print("\n");
PersonIdent ident =
newIdent(accountCache.get(c.getAuthor()).getAccount(),
c.getWrittenOn());
String nameString = ident.getName() + " <" + ident.getEmailAddress()
+ ">";
appendHeaderField(writer, AUTHOR, nameString);
String parent = c.getParentUuid();
if (parent != null) {
appendHeaderField(writer, PARENT, parent);
}
appendHeaderField(writer, UUID, c.getKey().get());
byte[] messageBytes = c.getMessage().getBytes(UTF_8);
appendHeaderField(writer, LENGTH,
Integer.toString(messageBytes.length));
writer.print(c.getMessage());
writer.print("\n\n"); writer.print("\n\n");
} }
// The CommentRange field for a comment is allowed to be null.
// If it is indeed null, then in the first line, we simply use the line
// number field for a comment instead. If it isn't null, we write the
// comment range itself.
CommentRange range = c.getRange();
if (range != null) {
writer.print(range.getStartLine());
writer.print(':');
writer.print(range.getStartCharacter());
writer.print('-');
writer.print(range.getEndLine());
writer.print(':');
writer.print(range.getEndCharacter());
} else {
writer.print(c.getLine());
}
writer.print("\n");
writer.print(formatTime(serverIdent, c.getWrittenOn()));
writer.print("\n");
PersonIdent ident =
newIdent(accountCache.get(c.getAuthor()).getAccount(),
c.getWrittenOn());
String nameString = ident.getName() + " <" + ident.getEmailAddress()
+ ">";
appendHeaderField(writer, AUTHOR, nameString);
String parent = c.getParentUuid();
if (parent != null) {
appendHeaderField(writer, PARENT, parent);
}
appendHeaderField(writer, UUID, c.getKey().get());
byte[] messageBytes = c.getMessage().getBytes(UTF_8);
appendHeaderField(writer, LENGTH,
Integer.toString(messageBytes.length));
writer.print(c.getMessage());
writer.print("\n\n");
} }
writer.close();
return buf.toByteArray(); return buf.toByteArray();
} }

View File

@@ -163,8 +163,7 @@ public class PatchList implements Serializable {
private void writeObject(final ObjectOutputStream output) throws IOException { private void writeObject(final ObjectOutputStream output) throws IOException {
final ByteArrayOutputStream buf = new ByteArrayOutputStream(); final ByteArrayOutputStream buf = new ByteArrayOutputStream();
final DeflaterOutputStream out = new DeflaterOutputStream(buf); try (DeflaterOutputStream out = new DeflaterOutputStream(buf)) {
try {
writeCanBeNull(out, oldId); writeCanBeNull(out, oldId);
writeNotNull(out, newId); writeNotNull(out, newId);
writeVarInt32(out, againstParent ? 1 : 0); writeVarInt32(out, againstParent ? 1 : 0);
@@ -174,16 +173,13 @@ public class PatchList implements Serializable {
for (PatchListEntry p : patches) { for (PatchListEntry p : patches) {
p.writeTo(out); p.writeTo(out);
} }
} finally {
out.close();
} }
writeBytes(output, buf.toByteArray()); writeBytes(output, buf.toByteArray());
} }
private void readObject(final ObjectInputStream input) throws IOException { private void readObject(final ObjectInputStream input) throws IOException {
final ByteArrayInputStream buf = new ByteArrayInputStream(readBytes(input)); final ByteArrayInputStream buf = new ByteArrayInputStream(readBytes(input));
final InflaterInputStream in = new InflaterInputStream(buf); try (InflaterInputStream in = new InflaterInputStream(buf)) {
try {
oldId = readCanBeNull(in); oldId = readCanBeNull(in);
newId = readNotNull(in); newId = readNotNull(in);
againstParent = readVarInt32(in) != 0; againstParent = readVarInt32(in) != 0;
@@ -195,8 +191,6 @@ public class PatchList implements Serializable {
all[i] = PatchListEntry.readFrom(in); all[i] = PatchListEntry.readFrom(in);
} }
patches = all; patches = all;
} finally {
in.close();
} }
} }
} }

View File

@@ -106,11 +106,8 @@ public class PatchListLoader extends CacheLoader<PatchListKey, PatchList> {
@Override @Override
public PatchList load(final PatchListKey key) throws IOException, public PatchList load(final PatchListKey key) throws IOException,
PatchListNotAvailableException { PatchListNotAvailableException {
final Repository repo = repoManager.openRepository(key.projectKey); try (Repository repo = repoManager.openRepository(key.projectKey)) {
try {
return readPatchList(key, repo); return readPatchList(key, repo);
} finally {
repo.close();
} }
} }
@@ -384,11 +381,8 @@ public class PatchListLoader extends CacheLoader<PatchListKey, PatchList> {
fmt.formatMerge(buf, p, "BASE", oursName, theirsName, "UTF-8"); fmt.formatMerge(buf, p, "BASE", oursName, theirsName, "UTF-8");
buf.close(); buf.close();
InputStream in = buf.openInputStream(); try (InputStream in = buf.openInputStream()) {
try {
resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in)); resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in));
} finally {
in.close();
} }
} finally { } finally {
buf.destroy(); buf.destroy();

View File

@@ -155,9 +155,25 @@ public class PatchScriptFactory implements Callable<PatchScript> {
throw new NoSuchChangeException(changeId); throw new NoSuchChangeException(changeId);
} }
final Repository git; try (Repository git = repoManager.openRepository(projectKey)) {
try { try {
git = repoManager.openRepository(projectKey); final PatchList list = listFor(keyFor(diffPrefs.getIgnoreWhitespace()));
final PatchScriptBuilder b = newBuilder(list, git);
final PatchListEntry content = list.get(fileName);
loadCommentsAndHistory(content.getChangeType(), //
content.getOldName(), //
content.getNewName());
return b.toPatchScript(content, comments, history);
} catch (PatchListNotAvailableException e) {
throw new NoSuchChangeException(changeId, e);
} catch (IOException e) {
log.error("File content unavailable", e);
throw new NoSuchChangeException(changeId, e);
} catch (org.eclipse.jgit.errors.LargeObjectException err) {
throw new LargeObjectException("File content is too large", err);
}
} catch (RepositoryNotFoundException e) { } catch (RepositoryNotFoundException e) {
log.error("Repository " + projectKey + " not found", e); log.error("Repository " + projectKey + " not found", e);
throw new NoSuchChangeException(changeId, e); throw new NoSuchChangeException(changeId, e);
@@ -165,26 +181,6 @@ public class PatchScriptFactory implements Callable<PatchScript> {
log.error("Cannot open repository " + projectKey, e); log.error("Cannot open repository " + projectKey, e);
throw new NoSuchChangeException(changeId, e); throw new NoSuchChangeException(changeId, e);
} }
try {
final PatchList list = listFor(keyFor(diffPrefs.getIgnoreWhitespace()));
final PatchScriptBuilder b = newBuilder(list, git);
final PatchListEntry content = list.get(fileName);
loadCommentsAndHistory(content.getChangeType(), //
content.getOldName(), //
content.getNewName());
return b.toPatchScript(content, comments, history);
} catch (PatchListNotAvailableException e) {
throw new NoSuchChangeException(changeId, e);
} catch (IOException e) {
log.error("File content unavailable", e);
throw new NoSuchChangeException(changeId, e);
} catch (org.eclipse.jgit.errors.LargeObjectException err) {
throw new LargeObjectException("File content is too large", err);
} finally {
git.close();
}
} }
private PatchListKey keyFor(final Whitespace whitespace) { private PatchListKey keyFor(final Whitespace whitespace) {

View File

@@ -79,13 +79,8 @@ public class PatchSetInfoFactory {
public PatchSetInfo get(Change change, PatchSet patchSet) public PatchSetInfo get(Change change, PatchSet patchSet)
throws PatchSetInfoNotAvailableException { throws PatchSetInfoNotAvailableException {
Repository repo; try (Repository repo = repoManager.openRepository(change.getProject());
try { RevWalk rw = new RevWalk(repo)) {
repo = repoManager.openRepository(change.getProject());
} catch (IOException e) {
throw new PatchSetInfoNotAvailableException(e);
}
try (RevWalk rw = new RevWalk(repo)) {
final RevCommit src = final RevCommit src =
rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
PatchSetInfo info = get(src, patchSet.getId()); PatchSetInfo info = get(src, patchSet.getId());
@@ -93,8 +88,6 @@ public class PatchSetInfoFactory {
return info; return info;
} catch (IOException e) { } catch (IOException e) {
throw new PatchSetInfoNotAvailableException(e); throw new PatchSetInfoNotAvailableException(e);
} finally {
repo.close();
} }
} }

View File

@@ -185,11 +185,8 @@ public class JarScanner implements PluginContentScanner {
private static byte[] read(JarFile jarFile, JarEntry entry) private static byte[] read(JarFile jarFile, JarEntry entry)
throws IOException { throws IOException {
byte[] data = new byte[(int) entry.getSize()]; byte[] data = new byte[(int) entry.getSize()];
InputStream in = jarFile.getInputStream(entry); try (InputStream in = jarFile.getInputStream(entry)) {
try {
IO.readFully(in, data, 0, data.length); IO.readFully(in, data, 0, data.length);
} finally {
in.close();
} }
return data; return data;
} }

View File

@@ -117,8 +117,7 @@ public class CreateBranch implements RestModifyView<ProjectResource, Input> {
final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref); final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref);
final RefControl refControl = rsrc.getControl().controlForRef(name); final RefControl refControl = rsrc.getControl().controlForRef(name);
final Repository repo = repoManager.openRepository(rsrc.getNameKey()); try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
try {
final ObjectId revid = parseBaseRevision(repo, rsrc.getNameKey(), input.revision); final ObjectId revid = parseBaseRevision(repo, rsrc.getNameKey(), input.revision);
final RevWalk rw = verifyConnected(repo, revid); final RevWalk rw = verifyConnected(repo, revid);
RevObject object = rw.parseAny(revid); RevObject object = rw.parseAny(revid);
@@ -184,8 +183,6 @@ public class CreateBranch implements RestModifyView<ProjectResource, Input> {
} }
} catch (InvalidRevisionException e) { } catch (InvalidRevisionException e) {
throw new BadRequestException("invalid revision \"" + input.revision + "\""); throw new BadRequestException("invalid revision \"" + input.revision + "\"");
} finally {
repo.close();
} }
} }

View File

@@ -229,8 +229,7 @@ public class CreateProject implements RestModifyView<TopLevelResource, ProjectIn
final String head = final String head =
args.permissionsOnly ? RefNames.REFS_CONFIG args.permissionsOnly ? RefNames.REFS_CONFIG
: args.branch.get(0); : args.branch.get(0);
Repository repo = repoManager.createRepository(nameKey); try (Repository repo = repoManager.createRepository(nameKey)) {
try {
NewProjectCreatedListener.Event event = new NewProjectCreatedListener.Event() { NewProjectCreatedListener.Event event = new NewProjectCreatedListener.Event() {
@Override @Override
public String getProjectName() { public String getProjectName() {
@@ -262,8 +261,6 @@ public class CreateProject implements RestModifyView<TopLevelResource, ProjectIn
} }
return projectCache.get(nameKey).getProject(); return projectCache.get(nameKey).getProject();
} finally {
repo.close();
} }
} catch (RepositoryCaseMismatchException e) { } catch (RepositoryCaseMismatchException e) {
throw new ResourceConflictException("Cannot create " + nameKey.get() throw new ResourceConflictException("Cannot create " + nameKey.get()
@@ -273,16 +270,11 @@ public class CreateProject implements RestModifyView<TopLevelResource, ProjectIn
} catch (RepositoryNotFoundException badName) { } catch (RepositoryNotFoundException badName) {
throw new BadRequestException("invalid project name: " + nameKey); throw new BadRequestException("invalid project name: " + nameKey);
} catch (IllegalStateException err) { } catch (IllegalStateException err) {
try { try (Repository repo = repoManager.openRepository(nameKey)) {
Repository repo = repoManager.openRepository(nameKey); if (repo.getObjectDatabase().exists()) {
try { throw new ResourceConflictException("project \"" + nameKey + "\" exists");
if (repo.getObjectDatabase().exists()) {
throw new ResourceConflictException("project \"" + nameKey + "\" exists");
}
throw err;
} finally {
repo.close();
} }
throw err;
} catch (IOException ioErr) { } catch (IOException ioErr) {
String msg = "Cannot create " + nameKey; String msg = "Cannot create " + nameKey;
log.error(msg, err); log.error(msg, err);

View File

@@ -132,21 +132,15 @@ class DashboardsCollection implements
throw new ResourceNotFoundException(id); throw new ResourceNotFoundException(id);
} }
Repository git; try (Repository git = gitManager.openRepository(ctl.getProject().getNameKey())) {
try {
git = gitManager.openRepository(ctl.getProject().getNameKey());
} catch (RepositoryNotFoundException e) {
throw new ResourceNotFoundException(id);
}
try {
ObjectId objId = git.resolve(ref + ":" + path); ObjectId objId = git.resolve(ref + ":" + path);
if (objId == null) { if (objId == null) {
throw new ResourceNotFoundException(id); throw new ResourceNotFoundException(id);
} }
BlobBasedConfig cfg = new BlobBasedConfig(null, git, objId); BlobBasedConfig cfg = new BlobBasedConfig(null, git, objId);
return new DashboardResource(myCtl, ref, path, cfg, false); return new DashboardResource(myCtl, ref, path, cfg, false);
} finally { } catch (RepositoryNotFoundException e) {
git.close(); throw new ResourceNotFoundException(id);
} }
} }

View File

@@ -82,8 +82,7 @@ public class DeleteBranch implements RestModifyView<BranchResource, Input>{
+ " has open changes"); + " has open changes");
} }
Repository r = repoManager.openRepository(rsrc.getNameKey()); try (Repository r = repoManager.openRepository(rsrc.getNameKey())) {
try {
RefUpdate.Result result; RefUpdate.Result result;
RefUpdate u = r.updateRef(rsrc.getRef()); RefUpdate u = r.updateRef(rsrc.getRef());
u.setForceUpdate(true); u.setForceUpdate(true);
@@ -129,8 +128,6 @@ public class DeleteBranch implements RestModifyView<BranchResource, Input>{
log.error("Cannot delete " + rsrc.getBranchKey() + ": " + result.name()); log.error("Cannot delete " + rsrc.getBranchKey() + ": " + result.name());
throw new ResourceConflictException("cannot delete branch: " + result.name()); throw new ResourceConflictException("cannot delete branch: " + result.name());
} }
} finally {
r.close();
} }
return Response.none(); return Response.none();
} }

View File

@@ -93,8 +93,7 @@ class DeleteBranches implements RestModifyView<ProjectResource, Input> {
public Response<?> apply(ProjectResource project, Input input) public Response<?> apply(ProjectResource project, Input input)
throws OrmException, IOException, ResourceConflictException { throws OrmException, IOException, ResourceConflictException {
input = Input.init(input); input = Input.init(input);
Repository r = repoManager.openRepository(project.getNameKey()); try (Repository r = repoManager.openRepository(project.getNameKey())) {
try {
BatchRefUpdate batchUpdate = r.getRefDatabase().newBatchUpdate(); BatchRefUpdate batchUpdate = r.getRefDatabase().newBatchUpdate();
for (String branch : input.branches) { for (String branch : input.branches) {
batchUpdate.addCommand(createDeleteCommand(project, r, branch)); batchUpdate.addCommand(createDeleteCommand(project, r, branch));
@@ -113,8 +112,6 @@ class DeleteBranches implements RestModifyView<ProjectResource, Input> {
if (errorMessages.length() > 0) { if (errorMessages.length() > 0) {
throw new ResourceConflictException(errorMessages.toString()); throw new ResourceConflictException(errorMessages.toString());
} }
} finally {
r.close();
} }
return Response.none(); return Response.none();
} }

View File

@@ -78,8 +78,7 @@ public class GetReflog implements RestReadView<BranchResource> {
throw new AuthException("not project owner"); throw new AuthException("not project owner");
} }
Repository repo = repoManager.openRepository(rsrc.getNameKey()); try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
try {
ReflogReader r = repo.getReflogReader(rsrc.getRef()); ReflogReader r = repo.getReflogReader(rsrc.getRef());
if (r == null) { if (r == null) {
throw new ResourceNotFoundException(rsrc.getRef()); throw new ResourceNotFoundException(rsrc.getRef());
@@ -108,8 +107,6 @@ public class GetReflog implements RestReadView<BranchResource> {
public ReflogEntryInfo apply(ReflogEntry e) { public ReflogEntryInfo apply(ReflogEntry e) {
return new ReflogEntryInfo(e); return new ReflogEntryInfo(e);
}}); }});
} finally {
repo.close();
} }
} }

View File

@@ -45,18 +45,13 @@ public class GetStatistics implements RestReadView<ProjectResource> {
@Override @Override
public RepositoryStatistics apply(ProjectResource rsrc) public RepositoryStatistics apply(ProjectResource rsrc)
throws ResourceNotFoundException, ResourceConflictException { throws ResourceNotFoundException, ResourceConflictException {
try { try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
Repository repo = repoManager.openRepository(rsrc.getNameKey()); GarbageCollectCommand gc = Git.wrap(repo).gc();
try { return new RepositoryStatistics(gc.getStatistics());
GarbageCollectCommand gc = Git.wrap(repo).gc(); } catch (GitAPIException e) {
return new RepositoryStatistics(gc.getStatistics()); throw new ResourceConflictException(e.getMessage());
} catch (GitAPIException e) { } catch (JGitInternalException e) {
throw new ResourceConflictException(e.getMessage()); throw new ResourceConflictException(e.getMessage());
} catch (JGitInternalException e) {
throw new ResourceConflictException(e.getMessage());
} finally {
repo.close();
}
} catch (IOException e) { } catch (IOException e) {
throw new ResourceNotFoundException(rsrc.getName()); throw new ResourceNotFoundException(rsrc.getName());
} }

View File

@@ -343,8 +343,7 @@ public class ListProjects implements RestReadView<TopLevelResource> {
try { try {
if (!showBranch.isEmpty()) { if (!showBranch.isEmpty()) {
Repository git = repoManager.openRepository(projectName); try (Repository git = repoManager.openRepository(projectName)) {
try {
if (!type.matches(git)) { if (!type.matches(git)) {
continue; continue;
} }
@@ -363,17 +362,12 @@ public class ListProjects implements RestReadView<TopLevelResource> {
info.branches.put(showBranch.get(i), ref.getObjectId().name()); info.branches.put(showBranch.get(i), ref.getObjectId().name());
} }
} }
} finally {
git.close();
} }
} else if (!showTree && type != FilterType.ALL) { } else if (!showTree && type != FilterType.ALL) {
Repository git = repoManager.openRepository(projectName); try (Repository git = repoManager.openRepository(projectName)) {
try {
if (!type.matches(git)) { if (!type.matches(git)) {
continue; continue;
} }
} finally {
git.close();
} }
} }
@@ -511,20 +505,15 @@ public class ListProjects implements RestReadView<TopLevelResource> {
private List<Ref> getBranchRefs(Project.NameKey projectName, private List<Ref> getBranchRefs(Project.NameKey projectName,
ProjectControl projectControl) { ProjectControl projectControl) {
Ref[] result = new Ref[showBranch.size()]; Ref[] result = new Ref[showBranch.size()];
try { try (Repository git = repoManager.openRepository(projectName)) {
Repository git = repoManager.openRepository(projectName); for (int i = 0; i < showBranch.size(); i++) {
try { Ref ref = git.getRef(showBranch.get(i));
for (int i = 0; i < showBranch.size(); i++) { if (ref != null
Ref ref = git.getRef(showBranch.get(i)); && ref.getObjectId() != null
if (ref != null && (projectControl.controlForRef(ref.getLeaf().getName()).isVisible())
&& ref.getObjectId() != null || (all && projectControl.isOwner())) {
&& (projectControl.controlForRef(ref.getLeaf().getName()).isVisible()) result[i] = ref;
|| (all && projectControl.isOwner())) {
result[i] = ref;
}
} }
} finally {
git.close();
} }
} catch (IOException ioe) { } catch (IOException ioe) {
// Fall through and return what is available. // Fall through and return what is available.

View File

@@ -69,9 +69,7 @@ public class ListTags implements RestReadView<ProjectResource> {
ResourceNotFoundException { ResourceNotFoundException {
List<TagInfo> tags = Lists.newArrayList(); List<TagInfo> tags = Lists.newArrayList();
Repository repo = getRepository(resource.getNameKey()); try (Repository repo = getRepository(resource.getNameKey())) {
try {
RevWalk rw = new RevWalk(repo); RevWalk rw = new RevWalk(repo);
try { try {
Map<String, Ref> all = visibleTags(resource.getControl(), repo, Map<String, Ref> all = visibleTags(resource.getControl(), repo,
@@ -82,8 +80,6 @@ public class ListTags implements RestReadView<ProjectResource> {
} finally { } finally {
rw.dispose(); rw.dispose();
} }
} finally {
repo.close();
} }
Collections.sort(tags, new Comparator<TagInfo>() { Collections.sort(tags, new Comparator<TagInfo>() {

View File

@@ -288,13 +288,10 @@ public class ProjectCacheImpl implements ProjectCache {
@Override @Override
public ProjectState load(String projectName) throws Exception { public ProjectState load(String projectName) throws Exception {
Project.NameKey key = new Project.NameKey(projectName); Project.NameKey key = new Project.NameKey(projectName);
Repository git = mgr.openRepository(key); try (Repository git = mgr.openRepository(key)) {
try {
ProjectConfig cfg = new ProjectConfig(key); ProjectConfig cfg = new ProjectConfig(key);
cfg.load(git); cfg.load(git);
return projectStateFactory.create(cfg); return projectStateFactory.create(cfg);
} finally {
git.close();
} }
} }
} }

View File

@@ -535,14 +535,9 @@ public class ProjectControl {
} }
public boolean canReadCommit(ReviewDb db, RevWalk rw, RevCommit commit) { public boolean canReadCommit(ReviewDb db, RevWalk rw, RevCommit commit) {
try { try (Repository repo = openRepository()) {
Repository repo = openRepository(); return isMergedIntoVisibleRef(repo, db, rw, commit,
try { repo.getAllRefs().values());
return isMergedIntoVisibleRef(repo, db, rw, commit,
repo.getAllRefs().values());
} finally {
repo.close();
}
} catch (IOException e) { } catch (IOException e) {
String msg = String.format( String msg = String.format(
"Cannot verify permissions to commit object %s in repository %s", "Cannot verify permissions to commit object %s in repository %s",

View File

@@ -163,17 +163,12 @@ public class ProjectState {
} }
private boolean isRevisionOutOfDate() { private boolean isRevisionOutOfDate() {
try { try (Repository git = gitMgr.openRepository(getProject().getNameKey())) {
Repository git = gitMgr.openRepository(getProject().getNameKey()); Ref ref = git.getRefDatabase().exactRef(RefNames.REFS_CONFIG);
try { if (ref == null || ref.getObjectId() == null) {
Ref ref = git.getRefDatabase().exactRef(RefNames.REFS_CONFIG); return true;
if (ref == null || ref.getObjectId() == null) {
return true;
}
return !ref.getObjectId().equals(config.getRevision());
} finally {
git.close();
} }
return !ref.getObjectId().equals(config.getRevision());
} catch (IOException gone) { } catch (IOException gone) {
return true; return true;
} }
@@ -228,13 +223,8 @@ public class ProjectState {
} }
ProjectLevelConfig cfg = new ProjectLevelConfig(fileName, this); ProjectLevelConfig cfg = new ProjectLevelConfig(fileName, this);
try { try (Repository git = gitMgr.openRepository(getProject().getNameKey())) {
Repository git = gitMgr.openRepository(getProject().getNameKey()); cfg.load(git);
try {
cfg.load(git);
} finally {
git.close();
}
} catch (IOException e) { } catch (IOException e) {
log.warn("Failed to load " + fileName + " for " + getProject().getName(), e); log.warn("Failed to load " + fileName + " for " + getProject().getName(), e);
} catch (ConfigInvalidException e) { } catch (ConfigInvalidException e) {

View File

@@ -328,17 +328,12 @@ public class RefControl {
private boolean isMergedIntoBranchOrTag(ReviewDb db, RevWalk rw, private boolean isMergedIntoBranchOrTag(ReviewDb db, RevWalk rw,
RevCommit commit) { RevCommit commit) {
try { try (Repository repo = projectControl.openRepository()) {
Repository repo = projectControl.openRepository(); List<Ref> refs = new ArrayList<>(
try { repo.getRefDatabase().getRefs(Constants.R_HEADS).values());
List<Ref> refs = new ArrayList<>( refs.addAll(repo.getRefDatabase().getRefs(Constants.R_TAGS).values());
repo.getRefDatabase().getRefs(Constants.R_HEADS).values()); return projectControl.isMergedIntoVisibleRef(
refs.addAll(repo.getRefDatabase().getRefs(Constants.R_TAGS).values()); repo, db, rw, commit, refs);
return projectControl.isMergedIntoVisibleRef(
repo, db, rw, commit, refs);
} finally {
repo.close();
}
} catch (IOException e) { } catch (IOException e) {
String msg = String.format( String msg = String.format(
"Cannot verify permissions to commit object %s in repository %s", "Cannot verify permissions to commit object %s in repository %s",

View File

@@ -76,9 +76,7 @@ public class SetHead implements RestModifyView<ProjectResource, Input> {
} }
String ref = RefNames.fullName(input.ref); String ref = RefNames.fullName(input.ref);
Repository repo = null; try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
try {
repo = repoManager.openRepository(rsrc.getNameKey());
Map<String, Ref> cur = Map<String, Ref> cur =
repo.getRefDatabase().exactRef(Constants.HEAD, ref); repo.getRefDatabase().exactRef(Constants.HEAD, ref);
if (!cur.containsKey(ref)) { if (!cur.containsKey(ref)) {
@@ -129,10 +127,6 @@ public class SetHead implements RestModifyView<ProjectResource, Input> {
return ref; return ref;
} catch (RepositoryNotFoundException e) { } catch (RepositoryNotFoundException e) {
throw new ResourceNotFoundException(rsrc.getName()); throw new ResourceNotFoundException(rsrc.getName());
} finally {
if (repo != null) {
repo.close();
}
} }
} }
} }

View File

@@ -90,8 +90,7 @@ public class SchemaUpdater {
} }
public void update(final UpdateUI ui) throws OrmException { public void update(final UpdateUI ui) throws OrmException {
final ReviewDb db = schema.open(); try (ReviewDb db = schema.open()) {
try {
final SchemaVersion u = updater.get(); final SchemaVersion u = updater.get();
final CurrentSchemaVersion version = getSchemaVersion(db); final CurrentSchemaVersion version = getSchemaVersion(db);
if (version == null) { if (version == null) {
@@ -112,8 +111,6 @@ public class SchemaUpdater {
updateSystemConfig(db); updateSystemConfig(db);
} }
} finally {
db.close();
} }
} }

View File

@@ -48,31 +48,26 @@ public class SchemaVersionCheck implements LifecycleListener {
@Override @Override
public void start() { public void start() {
try { try (ReviewDb db = schema.open()) {
final ReviewDb db = schema.open(); final CurrentSchemaVersion currentVer = getSchemaVersion(db);
try { final int expectedVer = SchemaVersion.getBinaryVersion();
final CurrentSchemaVersion currentVer = getSchemaVersion(db);
final int expectedVer = SchemaVersion.getBinaryVersion();
if (currentVer == null) { if (currentVer == null) {
throw new ProvisionException("Schema not yet initialized." throw new ProvisionException("Schema not yet initialized."
+ " Run init to initialize the schema:\n" + " Run init to initialize the schema:\n"
+ "$ java -jar gerrit.war init -d " + "$ java -jar gerrit.war init -d "
+ site.site_path.toAbsolutePath()); + site.site_path.toAbsolutePath());
} }
if (currentVer.versionNbr < expectedVer) { if (currentVer.versionNbr < expectedVer) {
throw new ProvisionException("Unsupported schema version " throw new ProvisionException("Unsupported schema version "
+ currentVer.versionNbr + "; expected schema version " + expectedVer + currentVer.versionNbr + "; expected schema version " + expectedVer
+ ". Run init to upgrade:\n" + ". Run init to upgrade:\n"
+ "$ java -jar " + site.gerrit_war.toAbsolutePath() + " init -d " + "$ java -jar " + site.gerrit_war.toAbsolutePath() + " init -d "
+ site.site_path.toAbsolutePath()); + site.site_path.toAbsolutePath());
} else if (currentVer.versionNbr > expectedVer) { } else if (currentVer.versionNbr > expectedVer) {
throw new ProvisionException("Unsupported schema version " throw new ProvisionException("Unsupported schema version "
+ currentVer.versionNbr + "; expected schema version " + expectedVer + currentVer.versionNbr + "; expected schema version " + expectedVer
+ ". Downgrade is not supported."); + ". Downgrade is not supported.");
}
} finally {
db.close();
} }
} catch (OrmException e) { } catch (OrmException e) {
throw new ProvisionException("Cannot read schema_version", e); throw new ProvisionException("Cannot read schema_version", e);

View File

@@ -61,38 +61,33 @@ public class Schema_106 extends SchemaVersion {
ui.message(String.format("creating reflog files for %s branches ...", ui.message(String.format("creating reflog files for %s branches ...",
RefNames.REFS_CONFIG)); RefNames.REFS_CONFIG));
for (Project.NameKey project : repoList) { for (Project.NameKey project : repoList) {
try { try (Repository repo = repoManager.openRepository(project)) {
Repository repo = repoManager.openRepository(project); File metaConfigLog =
try { new File(repo.getDirectory(), "logs/" + RefNames.REFS_CONFIG);
File metaConfigLog = if (metaConfigLog.exists()) {
new File(repo.getDirectory(), "logs/" + RefNames.REFS_CONFIG); continue;
if (metaConfigLog.exists()) { }
continue;
}
if (!metaConfigLog.getParentFile().mkdirs() if (!metaConfigLog.getParentFile().mkdirs()
|| !metaConfigLog.createNewFile()) { || !metaConfigLog.createNewFile()) {
throw new IOException(String.format( throw new IOException(String.format(
"Failed to create reflog for %s in repository %s", "Failed to create reflog for %s in repository %s",
RefNames.REFS_CONFIG, project)); RefNames.REFS_CONFIG, project));
} }
ObjectId metaConfigId = repo.resolve(RefNames.REFS_CONFIG); ObjectId metaConfigId = repo.resolve(RefNames.REFS_CONFIG);
if (metaConfigId != null) { if (metaConfigId != null) {
try (PrintWriter writer = try (PrintWriter writer =
new PrintWriter(metaConfigLog, UTF_8.name())) { new PrintWriter(metaConfigLog, UTF_8.name())) {
writer.print(ObjectId.zeroId().name()); writer.print(ObjectId.zeroId().name());
writer.print(" "); writer.print(" ");
writer.print(metaConfigId.name()); writer.print(metaConfigId.name());
writer.print(" "); writer.print(" ");
writer.print(serverUser.toExternalString()); writer.print(serverUser.toExternalString());
writer.print("\t"); writer.print("\t");
writer.print("create reflog"); writer.print("create reflog");
writer.println(); writer.println();
}
} }
} finally {
repo.close();
} }
} catch (IOException e) { } catch (IOException e) {
ui.message(String.format("ERROR: Failed to create reflog file for the" ui.message(String.format("ERROR: Failed to create reflog file for the"

View File

@@ -31,11 +31,8 @@ public class Schema_107 extends SchemaVersion {
@Override @Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException { protected void migrateData(ReviewDb db, UpdateUI ui) throws SQLException {
Statement stmt = ((JdbcSchema) db).getConnection().createStatement(); try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement()) {
try {
stmt.executeUpdate("UPDATE accounts set mute_common_path_prefixes = 'Y'"); stmt.executeUpdate("UPDATE accounts set mute_common_path_prefixes = 'Y'");
} finally {
stmt.close();
} }
} }
} }

View File

@@ -73,8 +73,7 @@ class ScriptRunner {
} }
private List<String> parse(final InputStream in) throws IOException { private List<String> parse(final InputStream in) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); try (BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {
try {
String delimiter = ";"; String delimiter = ";";
List<String> commands = new ArrayList<>(); List<String> commands = new ArrayList<>();
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
@@ -107,8 +106,6 @@ class ScriptRunner {
commands.add(buffer.toString()); commands.add(buffer.toString());
} }
return commands; return commands;
} finally {
br.close();
} }
} }

View File

@@ -109,21 +109,15 @@ public class ToolsCatalog {
private static byte[] read(String path) { private static byte[] read(String path) {
String name = "root/" + path; String name = "root/" + path;
InputStream in = ToolsCatalog.class.getResourceAsStream(name); try (InputStream in = ToolsCatalog.class.getResourceAsStream(name)) {
if (in == null) { if (in == null) {
return null; return null;
} }
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream out = new ByteArrayOutputStream();
try { final byte[] buf = new byte[8192];
final byte[] buf = new byte[8192]; int n;
int n; while ((n = in.read(buf, 0, buf.length)) > 0) {
while ((n = in.read(buf, 0, buf.length)) > 0) { out.write(buf, 0, n);
out.write(buf, 0, n);
}
} finally {
in.close();
} }
return out.toByteArray(); return out.toByteArray();
} catch (Exception e) { } catch (Exception e) {

Some files were not shown because too many files have changed in this diff Show More