SitePaths: Convert site_path itself to Path

Also convert all remaining references that expect to resolve site_path
to a File, notably LocalDiskRepositoryManager.

Change-Id: I5ef6f6e3d7b3fe0418a470b079b4cc04bc9be4f6
This commit is contained in:
Dave Borowitz 2015-02-24 15:40:37 -08:00 committed by David Pursehouse
parent f0c38d028b
commit 62e67bede7
29 changed files with 235 additions and 231 deletions

View File

@ -93,7 +93,7 @@ class H2CacheFactory implements PersistentCacheFactory, LifecycleListener {
if (name == null) {
return null;
}
Path loc = site.resolve(name).toPath();
Path loc = site.resolve(name);
if (!Files.exists(loc)) {
try {
Files.createDirectories(loc);

View File

@ -130,7 +130,7 @@ public class GitWebConfig {
// Use the CGI script configured by the administrator, failing if it
// cannot be used as specified.
//
cgi = sitePaths.resolve(cfgCgi).toPath();
cgi = sitePaths.resolve(cfgCgi);
if (!isRegularFile(cgi)) {
throw new IllegalStateException("Cannot find gitweb.cgi: " + cgi);
}

View File

@ -303,7 +303,7 @@ class GitWebServlet extends HttpServlet {
p.print("}\n");
}
Path root = repoManager.getBasePath().toPath();
Path root = repoManager.getBasePath();
p.print("$projectroot = " + quoteForPerl(root) + ";\n");
// Permit exporting only the project we were started for.

View File

@ -14,6 +14,9 @@
package com.google.gerrit.httpd.raw;
import static java.nio.file.Files.exists;
import static java.nio.file.Files.isReadable;
import com.google.common.io.ByteStreams;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
@ -24,11 +27,11 @@ import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -58,13 +61,13 @@ public class RobotsServlet extends HttpServlet {
private static final Logger log =
LoggerFactory.getLogger(RobotsServlet.class);
private final File robotsFile;
private final Path robotsFile;
@Inject
RobotsServlet(@GerritServerConfig final Config config, final SitePaths sitePaths) {
File file = sitePaths.resolve(
Path file = sitePaths.resolve(
config.getString("httpd", null, "robotsFile"));
if (file != null && (!file.exists() || !file.canRead())) {
if (file != null && (!exists(file) || !isReadable(file))) {
log.warn("Cannot read httpd.robotsFile, using default");
file = null;
}
@ -75,23 +78,16 @@ public class RobotsServlet extends HttpServlet {
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp)
throws IOException {
rsp.setContentType("text/plain");
InputStream in = openRobotsFile();
try {
OutputStream out = rsp.getOutputStream();
try {
ByteStreams.copy(in, out);
} finally {
out.close();
}
} finally {
in.close();
try (InputStream in = openRobotsFile();
OutputStream out = rsp.getOutputStream()) {
ByteStreams.copy(in, out);
}
}
private InputStream openRobotsFile() {
if (robotsFile != null) {
try {
return new FileInputStream(robotsFile);
return Files.newInputStream(robotsFile);
} catch (IOException e) {
log.warn("Cannot read " + robotsFile + "; using default", e);
}

View File

@ -124,6 +124,7 @@ java_test(
':init',
':init-api',
':pgm',
'//gerrit-common:server',
'//gerrit-server:server',
'//lib:guava',
'//lib:junit',

View File

@ -81,6 +81,8 @@ import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Enumeration;
@ -220,22 +222,22 @@ public class JettyServer {
} else if ("https".equals(u.getScheme())) {
SslContextFactory ssl = new SslContextFactory();
final File keystore = getFile(cfg, "sslkeystore", "etc/keystore");
final Path keystore = getFile(cfg, "sslkeystore", "etc/keystore");
String password = cfg.getString("httpd", null, "sslkeypassword");
if (password == null) {
password = "gerrit";
}
ssl.setKeyStorePath(keystore.getAbsolutePath());
ssl.setTrustStorePath(keystore.getAbsolutePath());
ssl.setKeyStorePath(keystore.toAbsolutePath().toString());
ssl.setTrustStorePath(keystore.toAbsolutePath().toString());
ssl.setKeyStorePassword(password);
ssl.setTrustStorePassword(password);
if (AuthType.CLIENT_SSL_CERT_LDAP.equals(authType)) {
ssl.setNeedClientAuth(true);
File crl = getFile(cfg, "sslcrl", "etc/crl.pem");
if (crl.exists()) {
ssl.setCrlPath(crl.getAbsolutePath());
Path crl = getFile(cfg, "sslcrl", "etc/crl.pem");
if (Files.exists(crl)) {
ssl.setCrlPath(crl.toAbsolutePath().toString());
ssl.setValidatePeerCerts(true);
}
}
@ -340,7 +342,7 @@ public class JettyServer {
return r;
}
private File getFile(final Config cfg, final String name, final String def) {
private Path getFile(Config cfg, String name, String def) {
String path = cfg.getString("httpd", null, name);
if (path == null || path.length() == 0) {
path = def;

View File

@ -14,12 +14,14 @@
package com.google.gerrit.pgm.init;
import com.google.gerrit.pgm.init.api.InitUtil;
import static com.google.gerrit.pgm.init.api.InitUtil.die;
import com.google.gerrit.common.FileUtil;
import com.google.gerrit.pgm.init.api.Section;
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
import java.io.File;
import java.nio.file.Path;
class H2Initializer implements DatabaseConfigInitializer {
@ -33,18 +35,17 @@ class H2Initializer implements DatabaseConfigInitializer {
@Override
public void initConfig(Section databaseSection) {
String path = databaseSection.get("database");
Path db;
if (path == null) {
path = "db/ReviewDB";
databaseSection.set("database", path);
db = site.resolve("db").resolve("ReviewDB");
databaseSection.set("database", db.toString());
} else {
db = site.resolve(path);
}
File db = site.resolve(path);
if (db == null) {
throw InitUtil.die("database.database must be supplied for H2");
}
db = db.getParentFile();
if (!db.exists() && !db.mkdirs()) {
throw InitUtil.die("cannot create database.database "
+ db.getAbsolutePath());
throw die("database.database must be supplied for H2");
}
db = db.getParent();
FileUtil.mkdirsOrDie(db, "cannot create database.database");
}
}
}

View File

@ -14,15 +14,14 @@
package com.google.gerrit.pgm.init;
import static com.google.gerrit.pgm.init.api.InitUtil.die;
import com.google.gerrit.common.FileUtil;
import com.google.gerrit.pgm.init.api.InitStep;
import com.google.gerrit.pgm.init.api.Section;
import com.google.gerrit.server.config.SitePaths;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.File;
import java.nio.file.Path;
/** Initialize the {@code cache} configuration section. */
@Singleton
@ -52,10 +51,8 @@ class InitCache implements InitStep {
cache.set("directory", path);
}
final File loc = site.resolve(path);
if (!loc.exists() && !loc.mkdirs()) {
throw die("cannot create cache.directory " + loc.getAbsolutePath());
}
Path loc = site.resolve(path);
FileUtil.mkdirsOrDie(loc, "cannot create cache.directory");
}
@Override

View File

@ -16,13 +16,14 @@ package com.google.gerrit.pgm.init;
import static com.google.gerrit.pgm.init.api.InitUtil.die;
import com.google.gerrit.common.FileUtil;
import com.google.gerrit.pgm.init.api.ConsoleUI;
import com.google.gerrit.pgm.init.api.InitStep;
import com.google.gerrit.pgm.init.api.Section;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.File;
import java.nio.file.Path;
/** Initialize the GitRepositoryManager configuration section. */
@Singleton
@ -40,13 +41,11 @@ class InitGitManager implements InitStep {
public void run() {
ui.header("Git Repositories");
File d = gerrit.path("Location of Git repositories", "basePath", "git");
Path d = gerrit.path("Location of Git repositories", "basePath", "git");
if (d == null) {
throw die("gerrit.basePath is required");
}
if (!d.exists() && !d.mkdirs()) {
throw die("Cannot create " + d);
}
FileUtil.mkdirsOrDie(d, "Cannot create");
}
@Override

View File

@ -21,6 +21,7 @@ import static com.google.gerrit.pgm.init.api.InitUtil.mkdir;
import static com.google.gerrit.pgm.init.api.InitUtil.savePublic;
import static com.google.gerrit.pgm.init.api.InitUtil.version;
import com.google.gerrit.common.FileUtil;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.pgm.init.api.ConsoleUI;
import com.google.gerrit.pgm.init.api.InitFlags;
@ -66,12 +67,10 @@ public class SitePathInitializer {
ui.header("Gerrit Code Review %s", version());
if (site.isNew) {
if (!ui.yesno(true, "Create '%s'", site.site_path.getCanonicalPath())) {
if (!ui.yesno(true, "Create '%s'", site.site_path.toAbsolutePath())) {
throw die("aborted by user");
}
if (!site.site_path.isDirectory() && !site.site_path.mkdirs()) {
throw die("Cannot make directory " + site.site_path);
}
FileUtil.mkdirsOrDie(site.site_path, "Cannot make directory");
flags.deleteOnFailure = true;
}

View File

@ -30,8 +30,6 @@ import com.google.inject.Singleton;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
@ -39,6 +37,7 @@ import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
@ -66,7 +65,7 @@ class UpgradeFrom2_0_x implements InitStep {
private final FileBasedConfig cfg;
private final SecureStore sec;
private final File site_path;
private final Path site_path;
private final Path etc_dir;
private final Section.Factory sections;
@ -84,7 +83,7 @@ class UpgradeFrom2_0_x implements InitStep {
boolean isNeedUpgrade() {
for (String name : etcFiles) {
if (new File(site_path, name).exists()) {
if (Files.exists(site_path.resolve(name))) {
return true;
}
}
@ -97,12 +96,12 @@ class UpgradeFrom2_0_x implements InitStep {
return;
}
if (!ui.yesno(true, "Upgrade '%s'", site_path.getCanonicalPath())) {
if (!ui.yesno(true, "Upgrade '%s'", site_path.toAbsolutePath())) {
throw die("aborted by user");
}
for (String name : etcFiles) {
Path src = site_path.toPath().resolve(name);
Path src = site_path.resolve(name);
Path dst = etc_dir.resolve(name);
if (Files.exists(src)) {
if (Files.exists(dst)) {
@ -260,23 +259,18 @@ class UpgradeFrom2_0_x implements InitStep {
private Properties readGerritServerProperties() throws IOException {
final Properties srvprop = new Properties();
final String name = System.getProperty("GerritServer");
File path;
Path path;
if (name != null) {
path = new File(name);
path = Paths.get(name);
} else {
path = new File(site_path, "GerritServer.properties");
if (!path.exists()) {
path = new File("GerritServer.properties");
path = site_path.resolve("GerritServer.properties");
if (!Files.exists(path)) {
path = Paths.get("GerritServer.properties");
}
}
if (path.exists()) {
try {
final InputStream in = new FileInputStream(path);
try {
srvprop.load(in);
} finally {
in.close();
}
if (Files.exists(path)) {
try (InputStream in = Files.newInputStream(path)) {
srvprop.load(in);
} catch (IOException e) {
throw new IOException("Cannot read " + name, e);
}

View File

@ -40,6 +40,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
public class AllProjectsConfig extends VersionedMetaData {
@ -68,11 +69,11 @@ public class AllProjectsConfig extends VersionedMetaData {
}
private File getPath() {
File basePath = site.resolve(flags.cfg.getString("gerrit", null, "basePath"));
Path basePath = site.resolve(flags.cfg.getString("gerrit", null, "basePath"));
if (basePath == null) {
throw new IllegalStateException("gerrit.basePath must be configured");
}
return FileKey.resolve(new File(basePath, project), FS.DETECTED);
return FileKey.resolve(basePath.resolve(project).toFile(), FS.DETECTED);
}
public AllProjectsConfig load() throws IOException, ConfigInvalidException {

View File

@ -20,7 +20,7 @@ import com.google.gerrit.server.securestore.SecureStore;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
@ -106,7 +106,7 @@ public class Section {
return nv;
}
public File path(final String title, final String name, final String defValue) {
public Path path(final String title, final String name, final String defValue) {
return site.resolve(string(title, name, defValue));
}

View File

@ -25,7 +25,7 @@ import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
public class ErrorLogFile {
@ -48,7 +48,7 @@ public class ErrorLogFile {
}
public static LifecycleListener start(final Path sitePath)
throws FileNotFoundException {
throws IOException {
Path logdir = FileUtil.mkdirsOrDie(new SitePaths(sitePath).logs_dir,
"Cannot create log directory");
if (SystemLog.shouldConfigure()) {

View File

@ -24,12 +24,11 @@ import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
public class GarbageCollectionLogFile {
public static LifecycleListener start(Path sitePath)
throws FileNotFoundException {
public static LifecycleListener start(Path sitePath) throws IOException {
Path logdir = FileUtil.mkdirsOrDie(new SitePaths(sitePath).logs_dir,
"Cannot create log directory");
if (SystemLog.shouldConfigure()) {

View File

@ -25,12 +25,11 @@ import com.google.inject.Provider;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.nio.file.Paths;
public class LibrariesTest {
@Test
public void testCreate() throws FileNotFoundException {
public void testCreate() throws Exception {
final SitePaths site = new SitePaths(Paths.get("."));
final ConsoleUI ui = createStrictMock(ConsoleUI.class);

View File

@ -26,6 +26,7 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.google.common.io.ByteStreams;
import com.google.gerrit.common.FileUtil;
import com.google.gerrit.pgm.init.api.ConsoleUI;
import com.google.gerrit.pgm.init.api.InitFlags;
import com.google.gerrit.pgm.init.api.Section;
@ -53,8 +54,7 @@ public class UpgradeFrom2_0_xTest extends InitTestCase {
final Path p = newSitePath();
final SitePaths site = new SitePaths(p);
assertTrue(site.isNew);
assertTrue(site.site_path.mkdir());
Files.createDirectory(site.etc_dir);
FileUtil.mkdirsOrDie(site.etc_dir, "Failed to create");
for (String n : UpgradeFrom2_0_x.etcFiles) {
Files.write(p.resolve(n), ("# " + n + "\n").getBytes(UTF_8));
@ -84,7 +84,7 @@ public class UpgradeFrom2_0_xTest extends InitTestCase {
expect(ui.yesno(
eq(true),
eq("Upgrade '%s'"),
eq(p.toRealPath().normalize().toString())))
eq(p.toAbsolutePath().normalize())))
.andReturn(true);
replay(ui);

View File

@ -883,7 +883,7 @@ public class ChangeHookRunner implements ChangeHooks, EventDispatcher,
}
final Map<String, String> env = pb.environment();
env.put("GERRIT_SITE", sitePaths.site_path.getAbsolutePath());
env.put("GERRIT_SITE", sitePaths.site_path.toAbsolutePath().toString());
if (repo != null) {
pb.directory(repo.getDirectory());

View File

@ -14,6 +14,8 @@
package com.google.gerrit.rules;
import static java.nio.file.StandardOpenOption.DELETE_ON_CLOSE;
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.common.Version;
import com.google.gerrit.reviewdb.client.RefNames;
@ -35,8 +37,11 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@ -67,14 +72,14 @@ public class PrologCompiler implements Callable<PrologCompiler.Status> {
NO_RULES, COMPILED
}
private final File ruleDir;
private final Path ruleDir;
private final Repository git;
@Inject
PrologCompiler(@GerritServerConfig Config config, SitePaths site,
@Assisted Repository gitRepository) {
File cacheDir = site.resolve(config.getString("cache", null, "directory"));
ruleDir = cacheDir != null ? new File(cacheDir, "rules") : null;
Path cacheDir = site.resolve(config.getString("cache", null, "directory"));
ruleDir = cacheDir != null ? cacheDir.resolve("rules") : null;
git = gitRepository;
}
@ -93,7 +98,9 @@ public class PrologCompiler implements Callable<PrologCompiler.Status> {
if (ruleDir == null) {
throw new CompileException("Caching not enabled");
}
if (!ruleDir.isDirectory() && !ruleDir.mkdir()) {
try {
Files.createDirectory(ruleDir);
} catch (IOException e) {
throw new IOException("Cannot create " + ruleDir);
}
@ -111,9 +118,9 @@ public class PrologCompiler implements Callable<PrologCompiler.Status> {
compileProlog(rulesId, tempDir);
compileJava(tempDir);
File jarFile = new File(ruleDir, "rules-" + rulesId.getName() + ".jar");
Path jarPath = ruleDir.resolve("rules-" + rulesId.getName() + ".jar");
List<String> classFiles = getRelativePaths(tempDir, ".class");
createJar(jarFile, classFiles, tempDir, metaConfig, rulesId);
createJar(jarPath, classFiles, tempDir, metaConfig, rulesId);
return Status.COMPILED;
} finally {
@ -222,51 +229,51 @@ public class PrologCompiler implements Callable<PrologCompiler.Status> {
}
/** Takes compiled prolog .class files, puts them into the jar file. */
private void createJar(File archiveFile, List<String> toBeJared,
private void createJar(Path archiveFile, List<String> toBeJared,
File tempDir, ObjectId metaConfig, ObjectId rulesId) throws IOException {
long now = TimeUtil.nowMs();
File tmpjar = File.createTempFile(".rulec_", ".jar", archiveFile.getParentFile());
try {
Manifest mf = new Manifest();
mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
mf.getMainAttributes().putValue("Built-by", "Gerrit Code Review " + Version.getVersion());
if (git.getDirectory() != null) {
mf.getMainAttributes().putValue("Source-Repository", git.getDirectory().getPath());
}
mf.getMainAttributes().putValue("Source-Commit", metaConfig.name());
mf.getMainAttributes().putValue("Source-Blob", rulesId.name());
Manifest mf = new Manifest();
mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
mf.getMainAttributes().putValue("Built-by", "Gerrit Code Review " + Version.getVersion());
if (git.getDirectory() != null) {
mf.getMainAttributes().putValue("Source-Repository", git.getDirectory().getPath());
}
mf.getMainAttributes().putValue("Source-Commit", metaConfig.name());
mf.getMainAttributes().putValue("Source-Blob", rulesId.name());
try (FileOutputStream stream = new FileOutputStream(tmpjar);
JarOutputStream out = new JarOutputStream(stream, mf)) {
byte buffer[] = new byte[10240];
for (String path : toBeJared) {
JarEntry jarAdd = new JarEntry(path);
File f = new File(tempDir, path);
jarAdd.setTime(now);
out.putNextEntry(jarAdd);
if (f.isFile()) {
FileInputStream in = new FileInputStream(f);
try {
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0) {
break;
}
out.write(buffer, 0, nRead);
Path tmpjar =
Files.createTempFile(archiveFile.getParent(), ".rulec_", ".jar");
try (OutputStream stream = Files.newOutputStream(tmpjar, DELETE_ON_CLOSE);
JarOutputStream out = new JarOutputStream(stream, mf)) {
byte buffer[] = new byte[10240];
// TODO: fixify this loop
for (String path : toBeJared) {
JarEntry jarAdd = new JarEntry(path);
File f = new File(tempDir, path);
jarAdd.setTime(now);
out.putNextEntry(jarAdd);
if (f.isFile()) {
FileInputStream in = new FileInputStream(f);
try {
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0) {
break;
}
} finally {
in.close();
out.write(buffer, 0, nRead);
}
} finally {
in.close();
}
out.closeEntry();
}
out.closeEntry();
}
}
if (!tmpjar.renameTo(archiveFile)) {
throw new IOException("Cannot replace " + archiveFile);
}
} finally {
tmpjar.delete();
try {
Files.move(tmpjar, archiveFile);
} catch (IOException e) {
throw new IOException("Cannot replace " + archiveFile, e);
}
}

View File

@ -44,7 +44,6 @@ import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.util.RawParseUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@ -57,6 +56,8 @@ import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
@ -96,8 +97,8 @@ public class RulesCache {
}
private final boolean enableProjectRules;
private final File cacheDir;
private final File rulesDir;
private final Path cacheDir;
private final Path rulesDir;
private final GitRepositoryManager gitMgr;
private final DynamicSet<PredicateProvider> predicateProviders;
private final ClassLoader systemLoader;
@ -108,7 +109,7 @@ public class RulesCache {
GitRepositoryManager gm, DynamicSet<PredicateProvider> predicateProviders) {
enableProjectRules = config.getBoolean("rules", null, "enable", true);
cacheDir = site.resolve(config.getString("cache", null, "directory"));
rulesDir = cacheDir != null ? new File(cacheDir, "rules") : null;
rulesDir = cacheDir != null ? cacheDir.resolve("rules") : null;
gitMgr = gm;
this.predicateProviders = predicateProviders;
@ -178,9 +179,9 @@ public class RulesCache {
// that over dynamic consult as the bytecode will be faster.
//
if (rulesDir != null) {
File jarFile = new File(rulesDir, "rules-" + rulesId.getName() + ".jar");
if (jarFile.isFile()) {
URL[] cp = new URL[] {toURL(jarFile)};
Path jarPath = rulesDir.resolve("rules-" + rulesId.getName() + ".jar");
if (Files.isRegularFile(jarPath)) {
URL[] cp = new URL[] {toURL(jarPath)};
return save(newEmptyMachine(new URLClassLoader(cp, systemLoader)));
}
}
@ -254,11 +255,11 @@ public class RulesCache {
return ctl;
}
private static URL toURL(File jarFile) throws CompileException {
private static URL toURL(Path jarPath) throws CompileException {
try {
return jarFile.toURI().toURL();
return jarPath.toUri().toURL();
} catch (MalformedURLException e) {
throw new CompileException("Cannot create URL for " + jarFile, e);
throw new CompileException("Cannot create URL for " + jarPath, e);
}
}
}

View File

@ -14,12 +14,14 @@
package com.google.gerrit.server.config;
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
/** Important paths within a {@link SitePath}. */
@ -29,7 +31,7 @@ public final class SitePaths {
public static final String HEADER_FILENAME = "GerritSiteHeader.html";
public static final String FOOTER_FILENAME = "GerritSiteFooter.html";
public final File site_path;
public final Path site_path;
public final Path bin_dir;
public final Path etc_dir;
public final Path lib_dir;
@ -65,9 +67,8 @@ public final class SitePaths {
public final boolean isNew;
@Inject
public SitePaths(final @SitePath Path sitePath) throws FileNotFoundException {
// TODO(dborowitz): Convert all of these to Paths.
site_path = sitePath.toFile();
public SitePaths(@SitePath Path sitePath) throws IOException {
site_path = sitePath;
Path p = sitePath;
bin_dir = p.resolve("bin");
@ -101,18 +102,13 @@ public final class SitePaths {
site_footer = etc_dir.resolve(FOOTER_FILENAME);
site_gitweb = etc_dir.resolve("gitweb_config.perl");
if (site_path.exists()) {
final String[] contents = site_path.list();
if (contents != null) {
isNew = contents.length == 0;
} else if (site_path.isDirectory()) {
throw new FileNotFoundException("Cannot access " + site_path);
} else {
throw new FileNotFoundException("Not a directory: " + site_path);
}
} else {
boolean isNew;
try (DirectoryStream<Path> files = Files.newDirectoryStream(site_path)) {
isNew = Iterables.isEmpty(files);
} catch (NoSuchFileException e) {
isNew = true;
}
this.isNew = isNew;
}
/**
@ -123,16 +119,13 @@ public final class SitePaths {
* @param path the path string to resolve. May be null.
* @return the resolved path; null if {@code path} was null or empty.
*/
public File resolve(final String path) {
public Path resolve(String path) {
if (path != null && !path.isEmpty()) {
File loc = new File(path);
if (!loc.isAbsolute()) {
loc = new File(site_path, path);
}
Path loc = site_path.resolve(path).normalize();
try {
return loc.getCanonicalFile();
return loc.toRealPath();
} catch (IOException e) {
return loc.getAbsoluteFile();
return loc.toAbsolutePath();
}
}
return null;

View File

@ -51,7 +51,14 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.EnumSet;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.locks.Lock;
@ -128,8 +135,8 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
}
}
private final File basePath;
private final File noteDbPath;
private final Path basePath;
private final Path noteDbPath;
private final Lock namesUpdateLock;
private volatile SortedSet<Project.NameKey> names;
@ -153,7 +160,7 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
}
/** @return base directory under which all projects are stored. */
public File getBasePath() {
public Path getBasePath() {
return basePath;
}
@ -163,12 +170,12 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
return openRepository(basePath, name);
}
private Repository openRepository(File path, Project.NameKey name)
private Repository openRepository(Path path, Project.NameKey name)
throws RepositoryNotFoundException {
if (isUnreasonableName(name)) {
throw new RepositoryNotFoundException("Invalid name: " + name);
}
File gitDir = new File(path, name.get());
File gitDir = path.resolve(name.get()).toFile();
if (!names.contains(name)) {
// The this.names list does not hold the project-name but it can still exist
// on disk; for instance when the project has been created directly on the
@ -214,13 +221,13 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
return repo;
}
private Repository createRepository(File path, Project.NameKey name)
private Repository createRepository(Path path, Project.NameKey name)
throws RepositoryNotFoundException, RepositoryCaseMismatchException {
if (isUnreasonableName(name)) {
throw new RepositoryNotFoundException("Invalid name: " + name);
}
File dir = FileKey.resolve(new File(path, name.get()), FS.DETECTED);
File dir = FileKey.resolve(path.resolve(name.get()).toFile(), FS.DETECTED);
FileKey loc;
if (dir != null) {
// Already exists on disk, use the repository we found.
@ -235,7 +242,7 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
// of the repository name, so prefer the standard bare name.
//
String n = name.get() + Constants.DOT_GIT_EXT;
loc = FileKey.exact(new File(path, n), FS.DETECTED);
loc = FileKey.exact(path.resolve(n).toFile(), FS.DETECTED);
}
try {
@ -397,51 +404,68 @@ public class LocalDiskRepositoryManager implements GitRepositoryManager {
// scanning the filesystem. Don't rely on the cached names collection.
namesUpdateLock.lock();
try {
SortedSet<Project.NameKey> n = new TreeSet<>();
scanProjects(basePath, "", n);
names = Collections.unmodifiableSortedSet(n);
return n;
ProjectVisitor visitor = new ProjectVisitor();
try {
Files.walkFileTree(basePath, EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE, visitor);
} catch (IOException e) {
log.error("Error walking repository tree " + basePath.toAbsolutePath(),
e);
}
return Collections.unmodifiableSortedSet(visitor.found);
} finally {
namesUpdateLock.unlock();
}
}
private void scanProjects(final File dir, final String prefix,
final SortedSet<Project.NameKey> names) {
final File[] ls = dir.listFiles();
if (ls == null) {
return;
private class ProjectVisitor extends SimpleFileVisitor<Path> {
private final SortedSet<Project.NameKey> found = new TreeSet<>();
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) throws IOException {
if (!dir.equals(basePath) && isRepo(dir)) {
addProject(dir);
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
for (File f : ls) {
String fileName = f.getName();
if (fileName.equals(Constants.DOT_GIT)) {
// Skip repositories named only `.git`
} else if (FileKey.isGitRepository(f, FS.DETECTED)) {
Project.NameKey nameKey = getProjectName(prefix, fileName);
if (isUnreasonableName(nameKey)) {
log.warn("Ignoring unreasonably named repository " + f.getAbsolutePath());
} else {
names.add(nameKey);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
// Skip repositories named only `.git`
if (isRepo(file)) {
addProject(file);
}
return FileVisitResult.CONTINUE;
}
} else if (f.isDirectory()) {
scanProjects(f, prefix + f.getName() + "/", names);
private boolean isRepo(Path p) {
return !p.getFileName().toString().equals(Constants.DOT_GIT)
&& FileKey.isGitRepository(p.toFile(), FS.DETECTED);
}
private void addProject(Path p) {
Project.NameKey nameKey = getProjectName(p);
if (isUnreasonableName(nameKey)) {
log.warn(
"Ignoring unreasonably named repository " + p.toAbsolutePath());
} else {
found.add(nameKey);
}
}
}
private Project.NameKey getProjectName(final String prefix,
final String fileName) {
final String projectName;
if (fileName.endsWith(Constants.DOT_GIT_EXT)) {
int newLen = fileName.length() - Constants.DOT_GIT_EXT.length();
projectName = prefix + fileName.substring(0, newLen);
} else {
projectName = prefix + fileName;
private Project.NameKey getProjectName(Path p) {
String projectName = basePath.relativize(p).toString();
if (File.separatorChar != '/') {
projectName = projectName.replace(File.separatorChar, '/');
}
if (projectName.endsWith(Constants.DOT_GIT_EXT)) {
int newLen = projectName.length() - Constants.DOT_GIT_EXT.length();
projectName = projectName.substring(0, newLen);
}
return new Project.NameKey(projectName);
}
return new Project.NameKey(projectName);
}
}

View File

@ -20,9 +20,6 @@ import com.google.inject.Inject;
import org.eclipse.jgit.lib.Config;
import java.io.File;
import java.io.IOException;
class H2 extends BaseDataSourceType {
protected final Config cfg;
@ -41,12 +38,6 @@ class H2 extends BaseDataSourceType {
if (database == null || database.isEmpty()) {
database = "db/ReviewDB";
}
File db = site.resolve(database);
try {
db = db.getCanonicalFile();
} catch (IOException e) {
db = db.getAbsoluteFile();
}
return "jdbc:h2:" + db.toURI().toString();
return "jdbc:h2:" + site.resolve(database).toUri().toString();
}
}

View File

@ -55,7 +55,7 @@ public class SchemaCreator {
AllUsersCreator auc,
@GerritPersonIdent PersonIdent au,
DataSourceType dst) {
this(site.site_path.toPath(), ap, auc, au, dst);
this(site.site_path, ap, auc, au, dst);
}
public SchemaCreator(@SitePath Path site,

View File

@ -131,9 +131,9 @@ public class SchemaUpdater {
throw new OrmException("No record in system_config table");
}
try {
sc.sitePath = site.site_path.getCanonicalPath();
sc.sitePath = site.site_path.toRealPath().normalize().toString();
} catch (IOException e) {
sc.sitePath = site.site_path.getAbsolutePath();
sc.sitePath = site.site_path.toAbsolutePath().normalize().toString();
}
db.systemConfig().update(Collections.singleton(sc));
}

View File

@ -58,14 +58,14 @@ public class SchemaVersionCheck implements LifecycleListener {
throw new ProvisionException("Schema not yet initialized."
+ " Run init to initialize the schema:\n"
+ "$ java -jar gerrit.war init -d "
+ site.site_path.getAbsolutePath());
+ site.site_path.toAbsolutePath());
}
if (currentVer.versionNbr < expectedVer) {
throw new ProvisionException("Unsupported schema version "
+ currentVer.versionNbr + "; expected schema version " + expectedVer
+ ". Run init to upgrade:\n"
+ "$ java -jar " + site.gerrit_war.toAbsolutePath() + " init -d "
+ site.site_path.getAbsolutePath());
+ site.site_path.toAbsolutePath());
} else if (currentVer.versionNbr > expectedVer) {
throw new ProvisionException("Unsupported schema version "
+ currentVer.versionNbr + "; expected schema version " + expectedVer

View File

@ -25,11 +25,11 @@ import com.google.gerrit.server.util.HostPlatform;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SitePathsTest {
@Test
@ -37,7 +37,7 @@ public class SitePathsTest {
final Path root = random();
final SitePaths site = new SitePaths(root);
assertTrue(site.isNew);
assertEquals(root.toFile(), site.site_path);
assertEquals(root, site.site_path);
assertEquals(root.resolve("etc"), site.etc_dir);
}
@ -49,7 +49,7 @@ public class SitePathsTest {
final SitePaths site = new SitePaths(root);
assertTrue(site.isNew);
assertEquals(root.toFile(), site.site_path);
assertEquals(root, site.site_path);
} finally {
Files.delete(root);
}
@ -65,7 +65,7 @@ public class SitePathsTest {
final SitePaths site = new SitePaths(root);
assertFalse(site.isNew);
assertEquals(root.toFile(), site.site_path);
assertEquals(root, site.site_path);
} finally {
Files.delete(txt);
Files.delete(root);
@ -80,8 +80,8 @@ public class SitePathsTest {
try {
new SitePaths(root);
fail("Did not throw exception");
} catch (FileNotFoundException e) {
assertEquals("Not a directory: " + root, e.getMessage());
} catch (NotDirectoryException e) {
// Expected.
}
} finally {
Files.delete(root);
@ -97,12 +97,12 @@ public class SitePathsTest {
assertNull(site.resolve(""));
assertNotNull(site.resolve("a"));
assertEquals(root.resolve("a").toAbsolutePath().normalize().toFile(),
assertEquals(root.resolve("a").toAbsolutePath().normalize(),
site.resolve("a"));
final String pfx = HostPlatform.isWin32() ? "C:/" : "/";
assertNotNull(site.resolve(pfx + "a"));
assertEquals(new File(pfx + "a").getCanonicalFile(), site.resolve(pfx + "a"));
assertEquals(Paths.get(pfx + "a"), site.resolve(pfx + "a"));
}
private static Path random() throws IOException {

View File

@ -130,6 +130,6 @@ public class SchemaUpdaterTest {
db.assertSchemaVersion();
final SystemConfig sc = db.getSystemConfig();
assertEquals(paths.site_path.getCanonicalPath(), sc.sitePath);
assertEquals(paths.site_path.toAbsolutePath().toString(), sc.sitePath);
}
}

View File

@ -75,6 +75,6 @@ class IndexVersionCheck implements LifecycleListener {
private final String upgrade() {
return "\nRun reindex to rebuild the index:\n"
+ "$ java -jar gerrit.war reindex -d "
+ sitePaths.site_path.getAbsolutePath();
+ sitePaths.site_path.toAbsolutePath();
}
}