Format all Java files with google-java-format

Having a standard tool for formatting saves reviewers' valuable time.
google-java-format is Google's standard formatter and is somewhat
inspired by gofmt[1]. This commit formats everything using
google-java-format version 1.2.

The downside of this one-off formatting is breaking blame. This can be
somewhat hacked around with a tool like git-hyper-blame[2], but it's
definitely not optimal until/unless this kind of feature makes its way
to git core.

Not in this change:
* Tool support, e.g. Eclipse. The command must be run manually [3].
* Documentation of best practice, e.g. new 100-column default.

[1] https://talks.golang.org/2015/gofmt-en.slide#3
[2] https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/git-hyper-blame.html
[3] git ls-files | grep java$ | xargs google-java-format -i

Change-Id: Id5f3c6de95ce0b68b41f0a478b5c99a93675aaa3
Signed-off-by: David Pursehouse <dpursehouse@collab.net>
This commit is contained in:
Dave Borowitz
2016-11-13 09:56:32 -08:00
committed by David Pursehouse
parent 6723b6d0fa
commit 292fa154c1
2443 changed files with 54816 additions and 57825 deletions

View File

@@ -30,14 +30,12 @@ import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.util.Providers;
import java.util.HashMap;
import java.util.Map;
/** Guice scopes for state during an Acceptance Test connection. */
public class AcceptanceTestRequestScope {
private static final Key<RequestCleanup> RC_KEY =
Key.get(RequestCleanup.class);
private static final Key<RequestCleanup> RC_KEY = Key.get(RequestCleanup.class);
private static final Key<RequestScopedReviewDbProvider> DB_KEY =
Key.get(RequestScopedReviewDbProvider.class);
@@ -53,16 +51,13 @@ public class AcceptanceTestRequestScope {
volatile long started;
volatile long finished;
private Context(SchemaFactory<ReviewDb> sf, SshSession s,
CurrentUser u, long at) {
private Context(SchemaFactory<ReviewDb> sf, SshSession s, CurrentUser u, long at) {
schemaFactory = sf;
session = s;
user = u;
created = started = finished = at;
map.put(RC_KEY, cleanup);
map.put(DB_KEY, new RequestScopedReviewDbProvider(
schemaFactory,
Providers.of(cleanup)));
map.put(DB_KEY, new RequestScopedReviewDbProvider(schemaFactory, Providers.of(cleanup)));
}
private Context(Context p, SshSession s, CurrentUser c) {
@@ -117,7 +112,9 @@ public class AcceptanceTestRequestScope {
private final AcceptanceTestRequestScope atrScope;
@Inject
Propagator(AcceptanceTestRequestScope atrScope, ThreadLocalRequestContext local,
Propagator(
AcceptanceTestRequestScope atrScope,
ThreadLocalRequestContext local,
Provider<RequestScopedReviewDbProvider> dbProviderProvider) {
super(REQUEST, current, local, dbProviderProvider);
this.atrScope = atrScope;
@@ -169,12 +166,13 @@ public class AcceptanceTestRequestScope {
public Context disableDb() {
Context old = current.get();
SchemaFactory<ReviewDb> sf = new SchemaFactory<ReviewDb>() {
@Override
public ReviewDb open() {
return new DisabledReviewDb();
}
};
SchemaFactory<ReviewDb> sf =
new SchemaFactory<ReviewDb>() {
@Override
public ReviewDb open() {
return new DisabledReviewDb();
}
};
Context ctx = new Context(sf, old.session, old.user, old.created);
current.set(ctx);
@@ -186,30 +184,30 @@ public class AcceptanceTestRequestScope {
// Setting a new context with the same fields is enough to get the ReviewDb
// provider to reopen the database.
Context old = current.get();
return set(
new Context(old.schemaFactory, old.session, old.user, old.created));
return set(new Context(old.schemaFactory, old.session, old.user, old.created));
}
/** Returns exactly one instance per command executed. */
static final Scope REQUEST = new Scope() {
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
return new Provider<T>() {
static final Scope REQUEST =
new Scope() {
@Override
public T get() {
return requireContext().get(key, creator);
public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
return new Provider<T>() {
@Override
public T get() {
return requireContext().get(key, creator);
}
@Override
public String toString() {
return String.format("%s[%s]", creator, REQUEST);
}
};
}
@Override
public String toString() {
return String.format("%s[%s]", creator, REQUEST);
return "Acceptance Test Scope.REQUEST";
}
};
}
@Override
public String toString() {
return "Acceptance Test Scope.REQUEST";
}
};
}

View File

@@ -34,11 +34,9 @@ import com.google.gerrit.testutil.SshMode;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.KeyPair;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
@@ -58,7 +56,8 @@ public class AccountCreator {
private final AccountIndexer indexer;
@Inject
AccountCreator(SchemaFactory<ReviewDb> schema,
AccountCreator(
SchemaFactory<ReviewDb> schema,
VersionedAuthorizedKeys.Accessor authorizedKeys,
GroupCache groupCache,
SshKeyCache sshKeyCache,
@@ -75,8 +74,8 @@ public class AccountCreator {
this.indexer = indexer;
}
public synchronized TestAccount create(String username, String email,
String fullName, String... groups) throws Exception {
public synchronized TestAccount create(
String username, String email, String fullName, String... groups) throws Exception {
TestAccount account = accounts.get(username);
if (account != null) {
return account;
@@ -85,8 +84,8 @@ public class AccountCreator {
Account.Id id = new Account.Id(db.nextAccountId());
AccountExternalId extUser =
new AccountExternalId(id, new AccountExternalId.Key(
AccountExternalId.SCHEME_USERNAME, username));
new AccountExternalId(
id, new AccountExternalId.Key(AccountExternalId.SCHEME_USERNAME, username));
String httpPass = "http-pass";
extUser.setPassword(httpPass);
db.accountExternalIds().insert(Collections.singleton(extUser));
@@ -107,8 +106,7 @@ public class AccountCreator {
AccountGroup.NameKey k = new AccountGroup.NameKey(n);
AccountGroup g = groupCache.get(k);
checkArgument(g != null, "group not found: %s", n);
AccountGroupMember m =
new AccountGroupMember(new AccountGroupMember.Key(id, g.getId()));
AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, g.getId()));
db.accountGroupMembers().insert(Collections.singleton(m));
}
}
@@ -125,8 +123,7 @@ public class AccountCreator {
indexer.index(id);
account =
new TestAccount(id, username, email, fullName, sshKey, httpPass);
account = new TestAccount(id, username, email, fullName, sshKey, httpPass);
accounts.put(username, account);
return account;
}
@@ -141,13 +138,11 @@ public class AccountCreator {
}
public TestAccount admin() throws Exception {
return create("admin", "admin@example.com", "Administrator",
"Administrators");
return create("admin", "admin@example.com", "Administrator", "Administrators");
}
public TestAccount admin2() throws Exception {
return create("admin2", "admin2@example.com", "Administrator2",
"Administrators");
return create("admin2", "admin2@example.com", "Administrator2", "Administrators");
}
public TestAccount user() throws Exception {
@@ -159,9 +154,7 @@ public class AccountCreator {
}
public TestAccount get(String username) {
return checkNotNull(
accounts.get(username),
"No TestAccount created for %s", username);
return checkNotNull(accounts.get(username), "No TestAccount created for %s", username);
}
private AccountExternalId.Key getEmailKey(String email) {

View File

@@ -23,9 +23,8 @@ import java.util.HashSet;
import java.util.Set;
public class AssertUtil {
public static <T> void assertPrefs(T actual, T expected,
String... fieldsToExclude)
throws IllegalArgumentException, IllegalAccessException {
public static <T> void assertPrefs(T actual, T expected, String... fieldsToExclude)
throws IllegalArgumentException, IllegalAccessException {
Set<String> exludedFields = new HashSet<>(Arrays.asList(fieldsToExclude));
for (Field field : actual.getClass().getDeclaredFields()) {
if (exludedFields.contains(field.getName()) || skipField(field)) {

View File

@@ -17,11 +17,9 @@ package com.google.gerrit.acceptance;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.eclipse.jgit.lib.Config;
import java.util.ArrayList;
import java.util.Arrays;
import org.eclipse.jgit.lib.Config;
class ConfigAnnotationParser {
private static Splitter splitter = Splitter.on(".").trimResults();
@@ -57,13 +55,11 @@ class ConfigAnnotationParser {
if (!Strings.isNullOrEmpty(c.value())) {
cfg.setString(l.get(0), l.get(1), l.get(2), c.value());
} else {
cfg.setStringList(l.get(0), l.get(1), l.get(2),
Arrays.asList(c.value()));
cfg.setStringList(l.get(0), l.get(1), l.get(2), Arrays.asList(c.value()));
}
} else {
throw new IllegalArgumentException(
"GerritConfig.name must be of the format"
+ " section.subsection.name or section.name");
"GerritConfig.name must be of the format" + " section.subsection.name or section.name");
}
}
}

View File

@@ -33,7 +33,6 @@ import com.google.gerrit.server.events.RefUpdatedEvent;
import com.google.gerrit.server.events.ReviewerDeletedEvent;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
@@ -47,7 +46,8 @@ public class EventRecorder {
private final IdentifiedUser.GenericFactory userFactory;
@Inject
Factory(DynamicSet<UserScopedEventListener> eventListeners,
Factory(
DynamicSet<UserScopedEventListener> eventListeners,
IdentifiedUser.GenericFactory userFactory) {
this.eventListeners = eventListeners;
this.userFactory = userFactory;
@@ -58,39 +58,39 @@ public class EventRecorder {
}
}
public EventRecorder(DynamicSet<UserScopedEventListener> eventListeners,
final IdentifiedUser user) {
public EventRecorder(
DynamicSet<UserScopedEventListener> eventListeners, final IdentifiedUser user) {
recordedEvents = LinkedListMultimap.create();
eventListenerRegistration = eventListeners.add(
new UserScopedEventListener() {
@Override
public void onEvent(Event e) {
if (e instanceof ReviewerDeletedEvent) {
recordedEvents.put(
ReviewerDeletedEvent.TYPE, (ReviewerDeletedEvent) e);
} else if (e instanceof RefEvent) {
RefEvent event = (RefEvent) e;
String key = refEventKey(event.getType(),
event.getProjectNameKey().get(),
event.getRefName());
recordedEvents.put(key, event);
}
}
eventListenerRegistration =
eventListeners.add(
new UserScopedEventListener() {
@Override
public void onEvent(Event e) {
if (e instanceof ReviewerDeletedEvent) {
recordedEvents.put(ReviewerDeletedEvent.TYPE, (ReviewerDeletedEvent) e);
} else if (e instanceof RefEvent) {
RefEvent event = (RefEvent) e;
String key =
refEventKey(
event.getType(), event.getProjectNameKey().get(), event.getRefName());
recordedEvents.put(key, event);
}
}
@Override
public CurrentUser getUser() {
return user;
}
});
@Override
public CurrentUser getUser() {
return user;
}
});
}
private static String refEventKey(String type, String project, String ref) {
return String.format("%s-%s-%s", type, project, ref);
}
private ImmutableList<RefUpdatedEvent> getRefUpdatedEvents(String project,
String refName, int expectedSize) {
private ImmutableList<RefUpdatedEvent> getRefUpdatedEvents(
String project, String refName, int expectedSize) {
String key = refEventKey(RefUpdatedEvent.TYPE, project, refName);
if (expectedSize == 0) {
assertThat(recordedEvents).doesNotContainKey(key);
@@ -98,16 +98,16 @@ public class EventRecorder {
}
assertThat(recordedEvents).containsKey(key);
ImmutableList<RefUpdatedEvent> events = FluentIterable
.from(recordedEvents.get(key))
.transform(RefUpdatedEvent.class::cast)
.toList();
ImmutableList<RefUpdatedEvent> events =
FluentIterable.from(recordedEvents.get(key))
.transform(RefUpdatedEvent.class::cast)
.toList();
assertThat(events).hasSize(expectedSize);
return events;
}
private ImmutableList<ChangeMergedEvent> getChangeMergedEvents(String project,
String branch, int expectedSize) {
private ImmutableList<ChangeMergedEvent> getChangeMergedEvents(
String project, String branch, int expectedSize) {
String key = refEventKey(ChangeMergedEvent.TYPE, project, branch);
if (expectedSize == 0) {
assertThat(recordedEvents).doesNotContainKey(key);
@@ -115,90 +115,80 @@ public class EventRecorder {
}
assertThat(recordedEvents).containsKey(key);
ImmutableList<ChangeMergedEvent> events = FluentIterable
.from(recordedEvents.get(key))
.transform(ChangeMergedEvent.class::cast)
.toList();
ImmutableList<ChangeMergedEvent> events =
FluentIterable.from(recordedEvents.get(key))
.transform(ChangeMergedEvent.class::cast)
.toList();
assertThat(events).hasSize(expectedSize);
return events;
}
private ImmutableList<ReviewerDeletedEvent> getReviewerDeletedEvents(
int expectedSize) {
private ImmutableList<ReviewerDeletedEvent> getReviewerDeletedEvents(int expectedSize) {
String key = ReviewerDeletedEvent.TYPE;
if (expectedSize == 0) {
assertThat(recordedEvents).doesNotContainKey(key);
return ImmutableList.of();
}
assertThat(recordedEvents).containsKey(key);
ImmutableList<ReviewerDeletedEvent> events = FluentIterable
.from(recordedEvents.get(key))
.transform(ReviewerDeletedEvent.class::cast)
.toList();
ImmutableList<ReviewerDeletedEvent> events =
FluentIterable.from(recordedEvents.get(key))
.transform(ReviewerDeletedEvent.class::cast)
.toList();
assertThat(events).hasSize(expectedSize);
return events;
}
public void assertRefUpdatedEvents(String project, String branch,
String... expected) throws Exception {
ImmutableList<RefUpdatedEvent> events = getRefUpdatedEvents(project,
branch, expected.length / 2);
public void assertRefUpdatedEvents(String project, String branch, String... expected)
throws Exception {
ImmutableList<RefUpdatedEvent> events =
getRefUpdatedEvents(project, branch, expected.length / 2);
int i = 0;
for (RefUpdatedEvent event : events) {
RefUpdateAttribute actual = event.refUpdate.get();
String oldRev = expected[i] == null
? ObjectId.zeroId().name()
: expected[i];
String newRev = expected[i+1] == null
? ObjectId.zeroId().name()
: expected[i+1];
String oldRev = expected[i] == null ? ObjectId.zeroId().name() : expected[i];
String newRev = expected[i + 1] == null ? ObjectId.zeroId().name() : expected[i + 1];
assertThat(actual.oldRev).isEqualTo(oldRev);
assertThat(actual.newRev).isEqualTo(newRev);
i += 2;
}
}
public void assertRefUpdatedEvents(String project, String branch,
RevCommit... expected) throws Exception {
ImmutableList<RefUpdatedEvent> events = getRefUpdatedEvents(project,
branch, expected.length / 2);
public void assertRefUpdatedEvents(String project, String branch, RevCommit... expected)
throws Exception {
ImmutableList<RefUpdatedEvent> events =
getRefUpdatedEvents(project, branch, expected.length / 2);
int i = 0;
for (RefUpdatedEvent event : events) {
RefUpdateAttribute actual = event.refUpdate.get();
String oldRev = expected[i] == null
? ObjectId.zeroId().name()
: expected[i].name();
String newRev = expected[i+1] == null
? ObjectId.zeroId().name()
: expected[i+1].name();
String oldRev = expected[i] == null ? ObjectId.zeroId().name() : expected[i].name();
String newRev = expected[i + 1] == null ? ObjectId.zeroId().name() : expected[i + 1].name();
assertThat(actual.oldRev).isEqualTo(oldRev);
assertThat(actual.newRev).isEqualTo(newRev);
i += 2;
}
}
public void assertChangeMergedEvents(String project, String branch,
String... expected) throws Exception {
ImmutableList<ChangeMergedEvent> events = getChangeMergedEvents(project,
branch, expected.length / 2);
public void assertChangeMergedEvents(String project, String branch, String... expected)
throws Exception {
ImmutableList<ChangeMergedEvent> events =
getChangeMergedEvents(project, branch, expected.length / 2);
int i = 0;
for (ChangeMergedEvent event : events) {
String id = event.change.get().id;
assertThat(id).isEqualTo(expected[i]);
assertThat(event.newRev).isEqualTo(expected[i+1]);
assertThat(event.newRev).isEqualTo(expected[i + 1]);
i += 2;
}
}
public void assertReviewerDeletedEvents(String... expected) {
ImmutableList<ReviewerDeletedEvent> events =
getReviewerDeletedEvents(expected.length / 2);
ImmutableList<ReviewerDeletedEvent> events = getReviewerDeletedEvents(expected.length / 2);
int i = 0;
for (ReviewerDeletedEvent event : events) {
String id = event.change.get().id;
assertThat(id).isEqualTo(expected[i]);
String reviewer = event.reviewer.get().email;
assertThat(reviewer).isEqualTo(expected[i+1]);
assertThat(reviewer).isEqualTo(expected[i + 1]);
i += 2;
}
}

View File

@@ -19,13 +19,11 @@ import static com.google.common.truth.Truth.assert_;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
public class GcAssert {
@@ -40,9 +38,9 @@ public class GcAssert {
throws RepositoryNotFoundException, IOException {
for (Project.NameKey p : projects) {
assert_()
.withFailureMessage("Project " + p.get() + " has no pack files.")
.that(getPackFiles(p))
.isNotEmpty();
.withFailureMessage("Project " + p.get() + " has no pack files.")
.that(getPackFiles(p))
.isNotEmpty();
}
}
@@ -50,22 +48,22 @@ public class GcAssert {
throws RepositoryNotFoundException, IOException {
for (Project.NameKey p : projects) {
assert_()
.withFailureMessage("Project " + p.get() + " has pack files.")
.that(getPackFiles(p))
.isEmpty();
.withFailureMessage("Project " + p.get() + " has pack files.")
.that(getPackFiles(p))
.isEmpty();
}
}
private String[] getPackFiles(Project.NameKey p)
throws RepositoryNotFoundException, IOException {
private String[] getPackFiles(Project.NameKey p) throws RepositoryNotFoundException, IOException {
try (Repository repo = repoManager.openRepository(p)) {
File packDir = new File(repo.getDirectory(), "objects/pack");
return packDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".pack");
}
});
return packDir.list(
new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".pack");
}
});
}
}
}

View File

@@ -26,6 +26,8 @@ import java.lang.annotation.Target;
@Repeatable(GerritConfigs.class)
public @interface GerritConfig {
String name();
String value() default "";
String[] values() default "";
}

View File

@@ -37,13 +37,6 @@ import com.google.gerrit.testutil.TempFileUtil;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.RepositoryCache;
import org.eclipse.jgit.util.FS;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
@@ -57,12 +50,16 @@ import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.RepositoryCache;
import org.eclipse.jgit.util.FS;
public class GerritServer {
@AutoValue
abstract static class Description {
static Description forTestClass(org.junit.runner.Description testDesc,
String configName) {
static Description forTestClass(org.junit.runner.Description testDesc, String configName) {
return new AutoValue_GerritServer_Description(
testDesc,
configName,
@@ -72,27 +69,24 @@ public class GerritServer {
has(UseSsh.class, testDesc.getTestClass()),
null, // @GerritConfig is only valid on methods.
null); // @GerritConfigs is only valid on methods.
}
static Description forTestMethod(org.junit.runner.Description testDesc,
String configName) {
static Description forTestMethod(org.junit.runner.Description testDesc, String configName) {
return new AutoValue_GerritServer_Description(
testDesc,
configName,
testDesc.getAnnotation(UseLocalDisk.class) == null,
testDesc.getAnnotation(NoHttpd.class) == null
&& !has(NoHttpd.class, testDesc.getTestClass()),
testDesc.getAnnotation(Sandboxed.class) != null ||
has(Sandboxed.class, testDesc.getTestClass()),
testDesc.getAnnotation(UseSsh.class) != null ||
has(UseSsh.class, testDesc.getTestClass()),
&& !has(NoHttpd.class, testDesc.getTestClass()),
testDesc.getAnnotation(Sandboxed.class) != null
|| has(Sandboxed.class, testDesc.getTestClass()),
testDesc.getAnnotation(UseSsh.class) != null
|| has(UseSsh.class, testDesc.getTestClass()),
testDesc.getAnnotation(GerritConfig.class),
testDesc.getAnnotation(GerritConfigs.class));
}
private static boolean has(
Class<? extends Annotation> annotation, Class<?> clazz) {
private static boolean has(Class<? extends Annotation> annotation, Class<?> clazz) {
for (; clazz != null; clazz = clazz.getSuperclass()) {
if (clazz.getAnnotation(annotation) != null) {
return true;
@@ -102,18 +96,27 @@ public class GerritServer {
}
abstract org.junit.runner.Description testDescription();
@Nullable abstract String configName();
@Nullable
abstract String configName();
abstract boolean memory();
abstract boolean httpd();
abstract boolean sandboxed();
abstract boolean useSsh();
@Nullable abstract GerritConfig config();
@Nullable abstract GerritConfigs configs();
@Nullable
abstract GerritConfig config();
@Nullable
abstract GerritConfigs configs();
private Config buildConfig(Config baseConfig) {
if (configs() != null && config() != null) {
throw new IllegalStateException(
"Use either @GerritConfigs or @GerritConfig not both");
throw new IllegalStateException("Use either @GerritConfigs or @GerritConfig not both");
}
if (configs() != null) {
return ConfigAnnotationParser.parse(baseConfig, configs());
@@ -126,21 +129,23 @@ public class GerritServer {
}
/** Returns fully started Gerrit server */
static GerritServer start(Description desc, Config baseConfig)
throws Exception {
static GerritServer start(Description desc, Config baseConfig) throws Exception {
Config cfg = desc.buildConfig(baseConfig);
Logger.getLogger("com.google.gerrit").setLevel(Level.DEBUG);
final CyclicBarrier serverStarted = new CyclicBarrier(2);
final Daemon daemon = new Daemon(new Runnable() {
@Override
public void run() {
try {
serverStarted.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
}, Paths.get(baseConfig.getString("gerrit", null, "tempSiteDir")));
final Daemon daemon =
new Daemon(
new Runnable() {
@Override
public void run() {
try {
serverStarted.await();
} catch (InterruptedException | BrokenBarrierException e) {
throw new RuntimeException(e);
}
}
},
Paths.get(baseConfig.getString("gerrit", null, "tempSiteDir")));
daemon.setEmailModuleForTesting(new FakeEmailSender.Module());
daemon.setEnableSshd(SshMode.useSsh());
@@ -158,25 +163,28 @@ public class GerritServer {
cfg.setString("gitweb", null, "cgi", "");
daemon.setEnableHttpd(desc.httpd());
daemon.setLuceneModule(LuceneIndexModule.singleVersionAllLatest(0));
daemon.setDatabaseForTesting(ImmutableList.<Module>of(
new InMemoryTestingDatabaseModule(cfg)));
daemon.setDatabaseForTesting(
ImmutableList.<Module>of(new InMemoryTestingDatabaseModule(cfg)));
daemon.start();
} else {
site = initSite(cfg);
daemonService = Executors.newSingleThreadExecutor();
daemonService.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
int rc = daemon.main(new String[] {
"-d", site.getPath(),
"--headless", "--console-log", "--show-stack-trace",});
if (rc != 0) {
System.err.println("Failed to start Gerrit daemon");
serverStarted.reset();
}
return null;
}
});
daemonService.submit(
new Callable<Void>() {
@Override
public Void call() throws Exception {
int rc =
daemon.main(
new String[] {
"-d", site.getPath(), "--headless", "--console-log", "--show-stack-trace",
});
if (rc != 0) {
System.err.println("Failed to start Gerrit daemon");
serverStarted.reset();
}
return null;
}
});
serverStarted.await();
System.out.println("Gerrit Server Started");
}
@@ -188,16 +196,17 @@ public class GerritServer {
private static File initSite(Config base) throws Exception {
File tmp = TempFileUtil.createTempDirectory();
Init init = new Init();
int rc = init.main(new String[] {
"-d", tmp.getPath(), "--batch", "--no-auto-start",
"--skip-plugins",});
int rc =
init.main(
new String[] {
"-d", tmp.getPath(), "--batch", "--no-auto-start", "--skip-plugins",
});
if (rc != 0) {
throw new RuntimeException("Couldn't initialize site");
}
MergeableFileBasedConfig cfg = new MergeableFileBasedConfig(
new File(new File(tmp, "etc"), "gerrit.config"),
FS.DETECTED);
MergeableFileBasedConfig cfg =
new MergeableFileBasedConfig(new File(new File(tmp, "etc"), "gerrit.config"), FS.DETECTED);
cfg.load();
cfg.merge(base);
mergeTestConfig(cfg);
@@ -206,8 +215,7 @@ public class GerritServer {
}
private static void mergeTestConfig(Config cfg) {
String forceEphemeralPort = String.format("%s:0",
getLocalHost().getHostName());
String forceEphemeralPort = String.format("%s:0", getLocalHost().getHostName());
String url = "http://" + forceEphemeralPort + "/";
cfg.setString("gerrit", null, "canonicalWebUrl", url);
cfg.setString("httpd", null, "listenUrl", url);
@@ -228,22 +236,24 @@ public class GerritServer {
private static Injector createTestInjector(Daemon daemon) throws Exception {
Injector sysInjector = get(daemon, "sysInjector");
Module module = new FactoryModule() {
@Override
protected void configure() {
bind(AccountCreator.class);
factory(PushOneCommit.Factory.class);
install(InProcessProtocol.module());
install(new NoSshModule());
install(new AsyncReceiveCommits.Module());
}
};
Module module =
new FactoryModule() {
@Override
protected void configure() {
bind(AccountCreator.class);
factory(PushOneCommit.Factory.class);
install(InProcessProtocol.module());
install(new NoSshModule());
install(new AsyncReceiveCommits.Module());
}
};
return sysInjector.createChildInjector(module);
}
@SuppressWarnings("unchecked")
private static <T> T get(Object obj, String field) throws SecurityException,
NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
private static <T> T get(Object obj, String field)
throws SecurityException, NoSuchFieldException, IllegalArgumentException,
IllegalAccessException {
Field f = obj.getClass().getDeclaredField(field);
f.setAccessible(true);
return (T) f.get(obj);
@@ -262,21 +272,18 @@ public class GerritServer {
private InetSocketAddress sshdAddress;
private InetSocketAddress httpAddress;
private GerritServer(Description desc, Injector testInjector, Daemon daemon,
ExecutorService daemonService) {
private GerritServer(
Description desc, Injector testInjector, Daemon daemon, ExecutorService daemonService) {
this.desc = desc;
this.testInjector = testInjector;
this.daemon = daemon;
this.daemonService = daemonService;
Config cfg = testInjector.getInstance(
Key.get(Config.class, GerritServerConfig.class));
Config cfg = testInjector.getInstance(Key.get(Config.class, GerritServerConfig.class));
url = cfg.getString("gerrit", null, "canonicalWebUrl");
URI uri = URI.create(url);
sshdAddress = SocketUtil.resolve(
cfg.getString("sshd", null, "listenAddress"),
0);
sshdAddress = SocketUtil.resolve(cfg.getString("sshd", null, "listenAddress"), 0);
httpAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
}

View File

@@ -21,11 +21,15 @@ import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import com.google.gerrit.common.FooterConstants;
import com.google.gerrit.reviewdb.client.Project;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jgit.api.FetchCommand;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.TagCommand;
@@ -48,13 +52,6 @@ import org.eclipse.jgit.transport.RemoteRefUpdate;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.util.FS;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class GitUtil {
private static final AtomicInteger testRepoCount = new AtomicInteger();
private static final int TEST_REPO_WINDOW_DAYS = 2;
@@ -67,66 +64,64 @@ public class GitUtil {
// register a JschConfigSessionFactory that adds the private key as identity
// to the JSch instance of JGit so that SSH communication via JGit can
// succeed
SshSessionFactory.setInstance(new JschConfigSessionFactory() {
@Override
protected void configure(Host hc, Session session) {
try {
final JSch jsch = getJSch(hc, FS.DETECTED);
jsch.addIdentity("KeyPair", a.privateKey(),
a.sshKey.getPublicKeyBlob(), null);
} catch (JSchException e) {
throw new RuntimeException(e);
}
}
});
SshSessionFactory.setInstance(
new JschConfigSessionFactory() {
@Override
protected void configure(Host hc, Session session) {
try {
final JSch jsch = getJSch(hc, FS.DETECTED);
jsch.addIdentity("KeyPair", a.privateKey(), a.sshKey.getPublicKeyBlob(), null);
} catch (JSchException e) {
throw new RuntimeException(e);
}
}
});
}
/**
* Create a new {@link TestRepository} with a distinct commit clock.
* <p>
* It is very easy for tests to create commits with identical subjects and
* trees; if such commits also have identical authors/committers, then the
* computed Change-Id is identical as well. Tests may generally assume that
* Change-Ids are unique, so to ensure this, we provision TestRepository
* instances with non-overlapping commit clock times.
* <p>
* Space test repos 1 day apart, which allows for about 86k ticks per repo
* before overlapping, and about 8k instances per process before hitting
* JGit's year 2038 limit.
*
* <p>It is very easy for tests to create commits with identical subjects and trees; if such
* commits also have identical authors/committers, then the computed Change-Id is identical as
* well. Tests may generally assume that Change-Ids are unique, so to ensure this, we provision
* TestRepository instances with non-overlapping commit clock times.
*
* <p>Space test repos 1 day apart, which allows for about 86k ticks per repo before overlapping,
* and about 8k instances per process before hitting JGit's year 2038 limit.
*
* @param repo repository to wrap.
* @return wrapped test repository with distinct commit time space.
*/
public static <R extends Repository> TestRepository<R> newTestRepository(
R repo) throws IOException {
public static <R extends Repository> TestRepository<R> newTestRepository(R repo)
throws IOException {
TestRepository<R> tr = new TestRepository<>(repo);
tr.tick(Ints.checkedCast(TimeUnit.SECONDS.convert(
testRepoCount.getAndIncrement() * TEST_REPO_WINDOW_DAYS,
TimeUnit.DAYS)));
tr.tick(
Ints.checkedCast(
TimeUnit.SECONDS.convert(
testRepoCount.getAndIncrement() * TEST_REPO_WINDOW_DAYS, TimeUnit.DAYS)));
return tr;
}
public static TestRepository<InMemoryRepository> cloneProject(
Project.NameKey project, String uri) throws Exception {
DfsRepositoryDescription desc =
new DfsRepositoryDescription("clone of " + project.get());
public static TestRepository<InMemoryRepository> cloneProject(Project.NameKey project, String uri)
throws Exception {
DfsRepositoryDescription desc = new DfsRepositoryDescription("clone of " + project.get());
FS fs = FS.detect();
// Avoid leaking user state into our tests.
fs.setUserHome(null);
InMemoryRepository dest = new InMemoryRepository.Builder()
.setRepositoryDescription(desc)
// SshTransport depends on a real FS to read ~/.ssh/config, but
// InMemoryRepository by default uses a null FS.
// TODO(dborowitz): Remove when we no longer depend on SSH.
.setFS(fs)
.build();
InMemoryRepository dest =
new InMemoryRepository.Builder()
.setRepositoryDescription(desc)
// SshTransport depends on a real FS to read ~/.ssh/config, but
// InMemoryRepository by default uses a null FS.
// TODO(dborowitz): Remove when we no longer depend on SSH.
.setFS(fs)
.build();
Config cfg = dest.getConfig();
cfg.setString("remote", "origin", "url", uri);
cfg.setString("remote", "origin", "fetch",
"+refs/heads/*:refs/remotes/origin/*");
cfg.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
TestRepository<InMemoryRepository> testRepo = newTestRepository(dest);
FetchResult result = testRepo.git().fetch().setRemote("origin").call();
String originMaster = "refs/remotes/origin/master";
@@ -141,51 +136,47 @@ public class GitUtil {
return cloneProject(project, sshSession.getUrl() + "/" + project.get());
}
public static Ref createAnnotatedTag(TestRepository<?> testRepo, String name,
PersonIdent tagger) throws GitAPIException {
TagCommand cmd = testRepo.git().tag()
.setName(name)
.setAnnotated(true)
.setMessage(name)
.setTagger(tagger);
public static Ref createAnnotatedTag(TestRepository<?> testRepo, String name, PersonIdent tagger)
throws GitAPIException {
TagCommand cmd =
testRepo.git().tag().setName(name).setAnnotated(true).setMessage(name).setTagger(tagger);
return cmd.call();
}
public static Ref updateAnnotatedTag(TestRepository<?> testRepo, String name,
PersonIdent tagger) throws GitAPIException {
public static Ref updateAnnotatedTag(TestRepository<?> testRepo, String name, PersonIdent tagger)
throws GitAPIException {
TagCommand tc = testRepo.git().tag().setName(name);
return tc.setAnnotated(true)
.setMessage(name)
.setTagger(tagger)
.setForceUpdate(true)
.call();
return tc.setAnnotated(true).setMessage(name).setTagger(tagger).setForceUpdate(true).call();
}
public static void fetch(TestRepository<?> testRepo, String spec)
throws GitAPIException {
public static void fetch(TestRepository<?> testRepo, String spec) throws GitAPIException {
FetchCommand fetch = testRepo.git().fetch();
fetch.setRefSpecs(new RefSpec(spec));
fetch.call();
}
public static PushResult pushHead(TestRepository<?> testRepo, String ref)
throws GitAPIException {
public static PushResult pushHead(TestRepository<?> testRepo, String ref) throws GitAPIException {
return pushHead(testRepo, ref, false);
}
public static PushResult pushHead(TestRepository<?> testRepo, String ref,
boolean pushTags) throws GitAPIException {
public static PushResult pushHead(TestRepository<?> testRepo, String ref, boolean pushTags)
throws GitAPIException {
return pushHead(testRepo, ref, pushTags, false);
}
public static PushResult pushHead(TestRepository<?> testRepo, String ref,
boolean pushTags, boolean force) throws GitAPIException {
public static PushResult pushHead(
TestRepository<?> testRepo, String ref, boolean pushTags, boolean force)
throws GitAPIException {
return pushOne(testRepo, "HEAD", ref, pushTags, force, null);
}
public static PushResult pushHead(TestRepository<?> testRepo, String ref,
boolean pushTags, boolean force, List<String> pushOptions)
throws GitAPIException {
public static PushResult pushHead(
TestRepository<?> testRepo,
String ref,
boolean pushTags,
boolean force,
List<String> pushOptions)
throws GitAPIException {
return pushOne(testRepo, "HEAD", ref, pushTags, force, pushOptions);
}
@@ -194,9 +185,14 @@ public class GitUtil {
return pushOne(testRepo, "", ref, false, true, null);
}
public static PushResult pushOne(TestRepository<?> testRepo, String source,
String target, boolean pushTags, boolean force, List<String> pushOptions)
throws GitAPIException {
public static PushResult pushOne(
TestRepository<?> testRepo,
String source,
String target,
boolean pushTags,
boolean force,
List<String> pushOptions)
throws GitAPIException {
PushCommand pushCmd = testRepo.git().push();
pushCmd.setForce(force);
pushCmd.setPushOptions(pushOptions);
@@ -210,25 +206,23 @@ public class GitUtil {
public static void assertPushOk(PushResult result, String ref) {
RemoteRefUpdate rru = result.getRemoteUpdate(ref);
assertThat(rru.getStatus()).named(rru.toString())
.isEqualTo(RemoteRefUpdate.Status.OK);
assertThat(rru.getStatus()).named(rru.toString()).isEqualTo(RemoteRefUpdate.Status.OK);
}
public static void assertPushRejected(PushResult result, String ref,
String expectedMessage) {
public static void assertPushRejected(PushResult result, String ref, String expectedMessage) {
RemoteRefUpdate rru = result.getRemoteUpdate(ref);
assertThat(rru.getStatus()).named(rru.toString())
assertThat(rru.getStatus())
.named(rru.toString())
.isEqualTo(RemoteRefUpdate.Status.REJECTED_OTHER_REASON);
assertThat(rru.getMessage()).isEqualTo(expectedMessage);
}
public static PushResult pushTag(TestRepository<?> testRepo, String tag)
throws GitAPIException {
public static PushResult pushTag(TestRepository<?> testRepo, String tag) throws GitAPIException {
return pushTag(testRepo, tag, false);
}
public static PushResult pushTag(TestRepository<?> testRepo, String tag,
boolean force) throws GitAPIException {
public static PushResult pushTag(TestRepository<?> testRepo, String tag, boolean force)
throws GitAPIException {
PushCommand pushCmd = testRepo.git().push();
pushCmd.setForce(force);
pushCmd.setRefSpecs(new RefSpec("refs/tags/" + tag + ":refs/tags/" + tag));
@@ -236,11 +230,9 @@ public class GitUtil {
return Iterables.getOnlyElement(r);
}
public static Optional<String> getChangeId(TestRepository<?> tr, ObjectId id)
throws IOException {
public static Optional<String> getChangeId(TestRepository<?> tr, ObjectId id) throws IOException {
RevCommit c = tr.getRevWalk().parseCommit(id);
tr.getRevWalk().parseBody(c);
return Lists.reverse(c.getFooterLines(FooterConstants.CHANGE_ID)).stream()
.findFirst();
return Lists.reverse(c.getFooterLines(FooterConstants.CHANGE_ID)).stream().findFirst();
}
}

View File

@@ -15,15 +15,13 @@
package com.google.gerrit.acceptance;
import com.google.common.base.Preconditions;
import org.apache.http.Header;
import org.eclipse.jgit.util.IO;
import org.eclipse.jgit.util.RawParseUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.ByteBuffer;
import org.apache.http.Header;
import org.eclipse.jgit.util.IO;
import org.eclipse.jgit.util.RawParseUtils;
public class HttpResponse {
@@ -62,23 +60,14 @@ public class HttpResponse {
}
public boolean hasContent() {
Preconditions.checkNotNull(response,
"Response is not initialized.");
Preconditions.checkNotNull(response, "Response is not initialized.");
return response.getEntity() != null;
}
public String getEntityContent() throws IOException {
Preconditions.checkNotNull(response,
"Response is not initialized.");
Preconditions.checkNotNull(response.getEntity(),
"Response.Entity is not initialized.");
ByteBuffer buf = IO.readWholeStream(
response.getEntity().getContent(),
1024);
return RawParseUtils.decode(
buf.array(),
buf.arrayOffset(),
buf.limit())
.trim();
Preconditions.checkNotNull(response, "Response is not initialized.");
Preconditions.checkNotNull(response.getEntity(), "Response.Entity is not initialized.");
ByteBuffer buf = IO.readWholeStream(response.getEntity().getContent(), 1024);
return RawParseUtils.decode(buf.array(), buf.arrayOffset(), buf.limit()).trim();
}
}

View File

@@ -16,14 +16,12 @@ package com.google.gerrit.acceptance;
import com.google.common.base.CharMatcher;
import com.google.gerrit.common.Nullable;
import java.io.IOException;
import java.net.URI;
import org.apache.http.HttpHost;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import java.io.IOException;
import java.net.URI;
public class HttpSession {
protected TestAccount account;
protected final String url;
@@ -35,9 +33,8 @@ public class HttpSession {
this.executor = Executor.newInstance();
this.account = account;
if (account != null) {
executor.auth(
new HttpHost(uri.getHost(), uri.getPort()),
account.username, account.httpPassword);
executor.auth(
new HttpHost(uri.getHost(), uri.getPort()), account.username, account.httpPassword);
}
}

View File

@@ -48,15 +48,13 @@ import com.google.inject.Provides;
import com.google.inject.ProvisionException;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.eclipse.jgit.lib.Config;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.eclipse.jgit.lib.Config;
class InMemoryTestingDatabaseModule extends LifecycleModule {
private final Config cfg;
@@ -67,19 +65,14 @@ class InMemoryTestingDatabaseModule extends LifecycleModule {
@Override
protected void configure() {
bind(Config.class)
.annotatedWith(GerritServerConfig.class)
.toInstance(cfg);
bind(Config.class).annotatedWith(GerritServerConfig.class).toInstance(cfg);
// TODO(dborowitz): Use jimfs.
Path p = Paths.get(cfg.getString("gerrit", null, "tempSiteDir"));
bind(Path.class)
.annotatedWith(SitePath.class)
.toInstance(p);
bind(Path.class).annotatedWith(SitePath.class).toInstance(p);
makeSiteDirs(p);
bind(GitRepositoryManager.class)
.to(InMemoryRepositoryManager.class);
bind(GitRepositoryManager.class).to(InMemoryRepositoryManager.class);
bind(InMemoryRepositoryManager.class).in(SINGLETON);
bind(MetricMaker.class).to(DisabledMetricMaker.class);
@@ -89,17 +82,14 @@ class InMemoryTestingDatabaseModule extends LifecycleModule {
TypeLiteral<SchemaFactory<ReviewDb>> schemaFactory =
new TypeLiteral<SchemaFactory<ReviewDb>>() {};
bind(schemaFactory).to(NotesMigrationSchemaFactory.class);
bind(Key.get(schemaFactory, ReviewDbFactory.class))
.to(InMemoryDatabase.class);
bind(Key.get(schemaFactory, ReviewDbFactory.class)).to(InMemoryDatabase.class);
bind(InMemoryDatabase.class).in(SINGLETON);
bind(ChangeBundleReader.class).to(GwtormChangeBundleReader.class);
listener().to(CreateDatabase.class);
bind(SitePaths.class);
bind(TrackingFooters.class)
.toProvider(TrackingFootersProvider.class)
.in(SINGLETON);
bind(TrackingFooters.class).toProvider(TrackingFootersProvider.class).in(SINGLETON);
install(new SchemaModule());
bind(SchemaVersion.class).to(SchemaVersion.C);

View File

@@ -55,7 +55,11 @@ import com.google.inject.Provides;
import com.google.inject.Scope;
import com.google.inject.servlet.RequestScoped;
import com.google.inject.util.Providers;
import java.io.IOException;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PostReceiveHook;
import org.eclipse.jgit.transport.PostReceiveHookChain;
@@ -68,12 +72,6 @@ import org.eclipse.jgit.transport.resolver.ReceivePackFactory;
import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException;
import org.eclipse.jgit.transport.resolver.UploadPackFactory;
import java.io.IOException;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class InProcessProtocol extends TestProtocol<Context> {
static Module module() {
return new AbstractModule() {
@@ -94,36 +92,37 @@ class InProcessProtocol extends TestProtocol<Context> {
};
}
private static final Scope REQUEST = new Scope() {
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
return new Provider<T>() {
private static final Scope REQUEST =
new Scope() {
@Override
public T get() {
Context ctx = current.get();
if (ctx == null) {
throw new OutOfScopeException("Not in TestProtocol scope");
}
return ctx.get(key, creator);
public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) {
return new Provider<T>() {
@Override
public T get() {
Context ctx = current.get();
if (ctx == null) {
throw new OutOfScopeException("Not in TestProtocol scope");
}
return ctx.get(key, creator);
}
@Override
public String toString() {
return String.format("%s[%s]", creator, REQUEST);
}
};
}
@Override
public String toString() {
return String.format("%s[%s]", creator, REQUEST);
return "InProcessProtocol.REQUEST";
}
};
}
@Override
public String toString() {
return "InProcessProtocol.REQUEST";
}
};
private static class Propagator
extends ThreadLocalRequestScopePropagator<Context> {
private static class Propagator extends ThreadLocalRequestScopePropagator<Context> {
@Inject
Propagator(ThreadLocalRequestContext local,
Propagator(
ThreadLocalRequestContext local,
Provider<RequestScopedReviewDbProvider> dbProviderProvider) {
super(REQUEST, current, local, dbProviderProvider);
}
@@ -139,22 +138,20 @@ class InProcessProtocol extends TestProtocol<Context> {
// TODO(dborowitz): Merge this with AcceptanceTestRequestScope.
/**
* Multi-purpose session/context object.
* <p>
* Confusingly, Gerrit has two ideas of what a "context" object is:
* one for Guice {@link RequestScoped}, and one for its own simplified
* version of request scoping using {@link ThreadLocalRequestContext}.
* This class provides both, in essence just delegating the {@code
*
* <p>Confusingly, Gerrit has two ideas of what a "context" object is: one for Guice {@link
* RequestScoped}, and one for its own simplified version of request scoping using {@link
* ThreadLocalRequestContext}. This class provides both, in essence just delegating the {@code
* ThreadLocalRequestContext} scoping to the Guice scoping mechanism.
* <p>
* It is also used as the session type for {@code UploadPackFactory} and
* {@code ReceivePackFactory}, since, after all, it encapsulates all the
* information about a single request.
*
* <p>It is also used as the session type for {@code UploadPackFactory} and {@code
* ReceivePackFactory}, since, after all, it encapsulates all the information about a single
* request.
*/
static class Context implements RequestContext {
private static final Key<RequestScopedReviewDbProvider> DB_KEY =
Key.get(RequestScopedReviewDbProvider.class);
private static final Key<RequestCleanup> RC_KEY =
Key.get(RequestCleanup.class);
private static final Key<RequestCleanup> RC_KEY = Key.get(RequestCleanup.class);
private static final Key<CurrentUser> USER_KEY = Key.get(CurrentUser.class);
private final SchemaFactory<ReviewDb> schemaFactory;
@@ -164,7 +161,8 @@ class InProcessProtocol extends TestProtocol<Context> {
private final RequestCleanup cleanup;
private final Map<Key<?>, Object> map;
Context(SchemaFactory<ReviewDb> schemaFactory,
Context(
SchemaFactory<ReviewDb> schemaFactory,
IdentifiedUser.GenericFactory userFactory,
Account.Id accountId,
Project.NameKey project) {
@@ -174,9 +172,7 @@ class InProcessProtocol extends TestProtocol<Context> {
this.project = project;
map = new HashMap<>();
cleanup = new RequestCleanup();
map.put(DB_KEY,
new RequestScopedReviewDbProvider(
schemaFactory, Providers.of(cleanup)));
map.put(DB_KEY, new RequestScopedReviewDbProvider(schemaFactory, Providers.of(cleanup)));
map.put(RC_KEY, cleanup);
IdentifiedUser user = userFactory.create(accountId);
@@ -255,8 +251,7 @@ class InProcessProtocol extends TestProtocol<Context> {
threadContext.setContext(req);
current.set(req);
try {
ProjectControl ctl = projectControlFactory.controlFor(
req.project, userProvider.get());
ProjectControl ctl = projectControlFactory.controlFor(req.project, userProvider.get());
if (!ctl.canRunUploadPack()) {
throw new ServiceNotAuthorizedException();
}
@@ -264,12 +259,11 @@ class InProcessProtocol extends TestProtocol<Context> {
UploadPack up = new UploadPack(repo);
up.setPackConfig(transferConfig.getPackConfig());
up.setTimeout(transferConfig.getTimeout());
up.setAdvertiseRefsHook(new VisibleRefFilter(
tagCache, changeNotesFactory, changeCache, repo, ctl,
dbProvider.get(), true));
up.setAdvertiseRefsHook(
new VisibleRefFilter(
tagCache, changeNotesFactory, changeCache, repo, ctl, dbProvider.get(), true));
List<PreUploadHook> hooks = Lists.newArrayList(preUploadHooks);
hooks.add(uploadValidatorsFactory.create(
ctl.getProject(), repo, "localhost-test"));
hooks.add(uploadValidatorsFactory.create(ctl.getProject(), repo, "localhost-test"));
up.setPreUploadHook(PreUploadHookChain.newChain(hooks));
return up;
} catch (NoSuchProjectException | IOException e) {
@@ -315,8 +309,7 @@ class InProcessProtocol extends TestProtocol<Context> {
threadContext.setContext(req);
current.set(req);
try {
ProjectControl ctl =
projectControlFactory.controlFor(req.project, userProvider.get());
ProjectControl ctl = projectControlFactory.controlFor(req.project, userProvider.get());
if (!ctl.canRunReceivePack()) {
throw new ServiceNotAuthorizedException();
}
@@ -337,8 +330,7 @@ class InProcessProtocol extends TestProtocol<Context> {
initializer.init(ctl.getProject().getNameKey(), rp);
}
rp.setPostReceiveHook(PostReceiveHookChain.newChain(
Lists.newArrayList(postReceiveHooks)));
rp.setPostReceiveHook(PostReceiveHookChain.newChain(Lists.newArrayList(postReceiveHooks)));
return rp;
} catch (NoSuchProjectException | IOException e) {
throw new RuntimeException(e);
@@ -347,8 +339,7 @@ class InProcessProtocol extends TestProtocol<Context> {
}
@Inject
InProcessProtocol(Upload uploadPackFactory,
Receive receivePackFactory) {
InProcessProtocol(Upload uploadPackFactory, Receive receivePackFactory) {
super(uploadPackFactory, receivePackFactory);
}
}

View File

@@ -18,16 +18,13 @@ import com.google.gerrit.server.PluginUser;
import com.google.gerrit.server.plugins.PluginGuiceEnvironment;
import com.google.gerrit.server.plugins.TestServerPlugin;
import com.google.inject.Inject;
import org.junit.After;
import org.junit.Before;
public class LightweightPluginDaemonTest extends AbstractDaemonTest {
@Inject
private PluginGuiceEnvironment env;
@Inject private PluginGuiceEnvironment env;
@Inject
private PluginUser.Factory pluginUserFactory;
@Inject private PluginUser.Factory pluginUserFactory;
private TestServerPlugin plugin;
@@ -35,13 +32,15 @@ public class LightweightPluginDaemonTest extends AbstractDaemonTest {
public void setUp() throws Exception {
TestPlugin testPlugin = getTestPlugin(getClass());
String name = testPlugin.name();
plugin = new TestServerPlugin(name,
canonicalWebUrl.get() + "plugins/" + name,
pluginUserFactory.create(name),
getClass().getClassLoader(),
testPlugin.sysModule(),
testPlugin.httpModule(),
testPlugin.sshModule());
plugin =
new TestServerPlugin(
name,
canonicalWebUrl.get() + "plugins/" + name,
pluginUserFactory.create(name),
getClass().getClassLoader(),
testPlugin.sysModule(),
testPlugin.httpModule(),
testPlugin.sshModule());
plugin.start(env);
env.onStartPlugin(plugin);

View File

@@ -15,16 +15,12 @@
package com.google.gerrit.acceptance;
import com.google.common.collect.Lists;
import java.io.File;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import java.io.File;
/**
* A file based Config that can merge another Config instance.
*/
/** A file based Config that can merge another Config instance. */
public class MergeableFileBasedConfig extends FileBasedConfig {
public MergeableFileBasedConfig(File cfgLocation, FS fs) {
super(cfgLocation, fs);
@@ -33,9 +29,8 @@ public class MergeableFileBasedConfig extends FileBasedConfig {
/**
* Merge another Config into this Config.
*
* In case a configuration parameter exists both in this instance and in the
* merged instance then the value in this instance will simply replaced by
* the value from the merged instance.
* <p>In case a configuration parameter exists both in this instance and in the merged instance
* then the value in this instance will simply replaced by the value from the merged instance.
*
* @param s Config to merge into this instance
*/
@@ -46,14 +41,17 @@ public class MergeableFileBasedConfig extends FileBasedConfig {
for (String section : s.getSections()) {
for (String subsection : s.getSubsections(section)) {
for (String name : s.getNames(section, subsection)) {
setStringList(section, subsection, name, Lists.newArrayList(s
.getStringList(section, subsection, name)));
setStringList(
section,
subsection,
name,
Lists.newArrayList(s.getStringList(section, subsection, name)));
}
}
for (String name : s.getNames(section, true)) {
setStringList(section, null, name,
Lists.newArrayList(s.getStringList(section, null, name)));
setStringList(
section, null, name, Lists.newArrayList(s.getStringList(section, null, name)));
}
}
}

View File

@@ -23,5 +23,4 @@ import java.lang.annotation.Target;
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface NoHttpd {
}
public @interface NoHttpd {}

View File

@@ -20,12 +20,6 @@ import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.gerrit.launcher.GerritLauncher;
import com.google.gerrit.server.config.SitePaths;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.junit.runner.Description;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ProcessBuilder.Redirect;
@@ -37,10 +31,12 @@ import java.nio.file.StandardCopyOption;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.junit.runner.Description;
/**
* @deprecated use {@link LightweightPluginDaemonTest} instead.
*/
/** @deprecated use {@link LightweightPluginDaemonTest} instead. */
@Deprecated
public abstract class PluginDaemonTest extends AbstractDaemonTest {
@@ -73,8 +69,7 @@ public abstract class PluginDaemonTest extends AbstractDaemonTest {
super.beforeTest(description);
}
protected void beforeTestServerStarts() throws Exception {
}
protected void beforeTestServerStarts() throws Exception {}
protected void setPluginConfigString(String name, String value)
throws IOException, ConfigInvalidException {
@@ -85,10 +80,8 @@ public abstract class PluginDaemonTest extends AbstractDaemonTest {
cfg.save();
}
private FileBasedConfig getGerritConfigFile(SitePaths sitePath)
throws IOException {
FileBasedConfig cfg =
new FileBasedConfig(sitePath.gerrit_config.toFile(), FS.DETECTED);
private FileBasedConfig getGerritConfigFile(SitePaths sitePath) throws IOException {
FileBasedConfig cfg = new FileBasedConfig(sitePath.gerrit_config.toFile(), FS.DETECTED);
if (!cfg.getFile().exists()) {
Path etc_path = Files.createDirectories(sitePath.etc_dir);
Files.createFile(etc_path.resolve("gerrit.config"));
@@ -97,8 +90,7 @@ public abstract class PluginDaemonTest extends AbstractDaemonTest {
}
private void locatePaths() throws IOException {
URL pluginClassesUrl =
getClass().getProtectionDomain().getCodeSource().getLocation();
URL pluginClassesUrl = getClass().getProtectionDomain().getCodeSource().getLocation();
basePath = Paths.get(pluginClassesUrl.getPath()).getParent();
int idx = 0;
@@ -141,17 +133,15 @@ public abstract class PluginDaemonTest extends AbstractDaemonTest {
return false;
}
String pathCharStringOrNone = "[a-zA-Z0-9._-]*?";
Pattern pattern = Pattern.compile(pathCharStringOrNone + "gerrit" +
pathCharStringOrNone);
Pattern pattern = Pattern.compile(pathCharStringOrNone + "gerrit" + pathCharStringOrNone);
Path partialPath = basePath;
for (int i = basePath.getNameCount(); i > 0; i--) {
int count = partialPath.getNameCount();
if (count > 1) {
String gerritDirCandidate =
partialPath.subpath(count - 2, count - 1).toString();
String gerritDirCandidate = partialPath.subpath(count - 2, count - 1).toString();
if (pattern.matcher(gerritDirCandidate).matches()) {
if (partialPath.endsWith(gerritDirCandidate + "/" + BUCKOUT) ||
partialPath.endsWith(gerritDirCandidate + "/" + ECLIPSE)) {
if (partialPath.endsWith(gerritDirCandidate + "/" + BUCKOUT)
|| partialPath.endsWith(gerritDirCandidate + "/" + ECLIPSE)) {
return false;
}
}
@@ -171,14 +161,11 @@ public abstract class PluginDaemonTest extends AbstractDaemonTest {
buildfile = pluginSource.resolve("BUILD");
}
if (!Files.exists(buildfile)) {
throw new IllegalStateException("Cannot find build file in: "
+ pluginSource);
throw new IllegalStateException("Cannot find build file in: " + pluginSource);
}
byte[] bytes = Files.readAllBytes(buildfile);
String buckContent =
new String(bytes, UTF_8).replaceAll("\\s+", "");
Matcher matcher =
Pattern.compile("gerrit_plugin\\(name='(.*?)'").matcher(buckContent);
String buckContent = new String(bytes, UTF_8).replaceAll("\\s+", "");
Matcher matcher = Pattern.compile("gerrit_plugin\\(name='(.*?)'").matcher(buckContent);
if (matcher.find()) {
pluginName = matcher.group(1);
}
@@ -196,13 +183,11 @@ public abstract class PluginDaemonTest extends AbstractDaemonTest {
String build;
if (bazel) {
dir = GerritLauncher.resolveInSourceRoot(".");
Properties properties = loadBuildProperties(
dir.resolve(".primary_build_tool"));
build = MoreObjects.firstNonNull(
properties.getProperty(BAZELLC), BAZELLC);
Properties properties = loadBuildProperties(dir.resolve(".primary_build_tool"));
build = MoreObjects.firstNonNull(properties.getProperty(BAZELLC), BAZELLC);
} else {
Properties properties = loadBuildProperties(
gen.resolve(Paths.get("tools/buck/buck.properties")));
Properties properties =
loadBuildProperties(gen.resolve(Paths.get("tools/buck/buck.properties")));
build = MoreObjects.firstNonNull(properties.getProperty(BUCKLC), BUCKLC);
}
String target;
@@ -213,7 +198,8 @@ public abstract class PluginDaemonTest extends AbstractDaemonTest {
}
ProcessBuilder processBuilder =
new ProcessBuilder(build, "build", target).directory(dir.toFile())
new ProcessBuilder(build, "build", target)
.directory(dir.toFile())
.redirectErrorStream(true);
Path forceJar = pluginSource.resolve("src/main/java/ForceJarIfMissing.java");
if (!bazel) {

View File

@@ -35,7 +35,8 @@ import com.google.gwtorm.server.OrmException;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import java.util.List;
import java.util.Map;
import org.eclipse.jgit.api.TagCommand;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.PersonIdent;
@@ -44,37 +45,32 @@ import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.RemoteRefUpdate;
import org.eclipse.jgit.transport.RemoteRefUpdate.Status;
import java.util.List;
import java.util.Map;
public class PushOneCommit {
public static final String SUBJECT = "test commit";
public static final String FILE_NAME = "a.txt";
public static final String FILE_CONTENT = "some content";
public static final String PATCH_FILE_ONLY =
"diff --git a/a.txt b/a.txt\n" +
"new file mode 100644\n" +
"index 0000000..f0eec86\n" +
"--- /dev/null\n" +
"+++ b/a.txt\n" +
"@@ -0,0 +1 @@\n" +
"+some content\n" +
"\\ No newline at end of file\n";
"diff --git a/a.txt b/a.txt\n"
+ "new file mode 100644\n"
+ "index 0000000..f0eec86\n"
+ "--- /dev/null\n"
+ "+++ b/a.txt\n"
+ "@@ -0,0 +1 @@\n"
+ "+some content\n"
+ "\\ No newline at end of file\n";
public static final String PATCH =
"From %s Mon Sep 17 00:00:00 2001\n" +
"From: Administrator <admin@example.com>\n" +
"Date: %s\n" +
"Subject: [PATCH] test commit\n" +
"\n" +
"Change-Id: %s\n" +
"---\n" +
"\n" + PATCH_FILE_ONLY;
"From %s Mon Sep 17 00:00:00 2001\n"
+ "From: Administrator <admin@example.com>\n"
+ "Date: %s\n"
+ "Subject: [PATCH] test commit\n"
+ "\n"
+ "Change-Id: %s\n"
+ "---\n"
+ "\n"
+ PATCH_FILE_ONLY;
public interface Factory {
PushOneCommit create(
ReviewDb db,
PersonIdent i,
TestRepository<?> testRepo);
PushOneCommit create(ReviewDb db, PersonIdent i, TestRepository<?> testRepo);
PushOneCommit create(
ReviewDb db,
@@ -142,30 +138,52 @@ public class PushOneCommit {
private final TestRepository<?>.CommitBuilder commitBuilder;
@AssistedInject
PushOneCommit(ChangeNotes.Factory notesFactory,
PushOneCommit(
ChangeNotes.Factory notesFactory,
ApprovalsUtil approvalsUtil,
Provider<InternalChangeQuery> queryProvider,
@Assisted ReviewDb db,
@Assisted PersonIdent i,
@Assisted TestRepository<?> testRepo) throws Exception {
this(notesFactory, approvalsUtil, queryProvider,
db, i, testRepo, SUBJECT, FILE_NAME, FILE_CONTENT);
@Assisted TestRepository<?> testRepo)
throws Exception {
this(
notesFactory,
approvalsUtil,
queryProvider,
db,
i,
testRepo,
SUBJECT,
FILE_NAME,
FILE_CONTENT);
}
@AssistedInject
PushOneCommit(ChangeNotes.Factory notesFactory,
PushOneCommit(
ChangeNotes.Factory notesFactory,
ApprovalsUtil approvalsUtil,
Provider<InternalChangeQuery> queryProvider,
@Assisted ReviewDb db,
@Assisted PersonIdent i,
@Assisted TestRepository<?> testRepo,
@Assisted("changeId") String changeId) throws Exception {
this(notesFactory, approvalsUtil, queryProvider,
db, i, testRepo, SUBJECT, FILE_NAME, FILE_CONTENT, changeId);
@Assisted("changeId") String changeId)
throws Exception {
this(
notesFactory,
approvalsUtil,
queryProvider,
db,
i,
testRepo,
SUBJECT,
FILE_NAME,
FILE_CONTENT,
changeId);
}
@AssistedInject
PushOneCommit(ChangeNotes.Factory notesFactory,
PushOneCommit(
ChangeNotes.Factory notesFactory,
ApprovalsUtil approvalsUtil,
Provider<InternalChangeQuery> queryProvider,
@Assisted ReviewDb db,
@@ -173,26 +191,38 @@ public class PushOneCommit {
@Assisted TestRepository<?> testRepo,
@Assisted("subject") String subject,
@Assisted("fileName") String fileName,
@Assisted("content") String content) throws Exception {
this(notesFactory, approvalsUtil, queryProvider,
db, i, testRepo, subject, fileName, content, null);
@Assisted("content") String content)
throws Exception {
this(
notesFactory,
approvalsUtil,
queryProvider,
db,
i,
testRepo,
subject,
fileName,
content,
null);
}
@AssistedInject
PushOneCommit(ChangeNotes.Factory notesFactory,
PushOneCommit(
ChangeNotes.Factory notesFactory,
ApprovalsUtil approvalsUtil,
Provider<InternalChangeQuery> queryProvider,
@Assisted ReviewDb db,
@Assisted PersonIdent i,
@Assisted TestRepository<?> testRepo,
@Assisted String subject,
@Assisted Map<String, String> files) throws Exception {
this(notesFactory, approvalsUtil, queryProvider, db, i, testRepo,
subject, files, null);
@Assisted Map<String, String> files)
throws Exception {
this(notesFactory, approvalsUtil, queryProvider, db, i, testRepo, subject, files, null);
}
@AssistedInject
PushOneCommit(ChangeNotes.Factory notesFactory,
PushOneCommit(
ChangeNotes.Factory notesFactory,
ApprovalsUtil approvalsUtil,
Provider<InternalChangeQuery> queryProvider,
@Assisted ReviewDb db,
@@ -201,12 +231,22 @@ public class PushOneCommit {
@Assisted("subject") String subject,
@Assisted("fileName") String fileName,
@Assisted("content") String content,
@Nullable @Assisted("changeId") String changeId) throws Exception {
this(notesFactory, approvalsUtil, queryProvider, db, i, testRepo,
subject, ImmutableMap.of(fileName, content), changeId);
@Nullable @Assisted("changeId") String changeId)
throws Exception {
this(
notesFactory,
approvalsUtil,
queryProvider,
db,
i,
testRepo,
subject,
ImmutableMap.of(fileName, content),
changeId);
}
private PushOneCommit(ChangeNotes.Factory notesFactory,
private PushOneCommit(
ChangeNotes.Factory notesFactory,
ApprovalsUtil approvalsUtil,
Provider<InternalChangeQuery> queryProvider,
ReviewDb db,
@@ -214,7 +254,8 @@ public class PushOneCommit {
TestRepository<?> testRepo,
String subject,
Map<String, String> files,
String changeId) throws Exception {
String changeId)
throws Exception {
this.db = db;
this.testRepo = testRepo;
this.notesFactory = notesFactory;
@@ -224,14 +265,11 @@ public class PushOneCommit {
this.files = files;
this.changeId = changeId;
if (changeId != null) {
commitBuilder = testRepo.amendRef("HEAD")
.insertChangeId(changeId.substring(1));
commitBuilder = testRepo.amendRef("HEAD").insertChangeId(changeId.substring(1));
} else {
commitBuilder = testRepo.branch("HEAD").commit().insertChangeId();
}
commitBuilder.message(subject)
.author(i)
.committer(new PersonIdent(i, testRepo.getDate()));
commitBuilder.message(subject).author(i).committer(new PersonIdent(i, testRepo.getDate()));
}
public void setParents(List<RevCommit> parents) throws Exception {
@@ -268,17 +306,17 @@ public class PushOneCommit {
if (tag != null) {
TagCommand tagCommand = testRepo.git().tag().setName(tag.name);
if (tag instanceof AnnotatedTag) {
AnnotatedTag annotatedTag = (AnnotatedTag)tag;
tagCommand.setAnnotated(true)
.setMessage(annotatedTag.message)
.setTagger(annotatedTag.tagger);
AnnotatedTag annotatedTag = (AnnotatedTag) tag;
tagCommand
.setAnnotated(true)
.setMessage(annotatedTag.message)
.setTagger(annotatedTag.tagger);
} else {
tagCommand.setAnnotated(false);
}
tagCommand.call();
}
return new Result(ref,
pushHead(testRepo, ref, tag != null, force, pushOptions), c, subject);
return new Result(ref, pushHead(testRepo, ref, tag != null, force, pushOptions), c, subject);
}
public void setTag(final Tag tag) {
@@ -307,8 +345,7 @@ public class PushOneCommit {
private final RevCommit commit;
private final String resSubj;
private Result(String ref, PushResult resSubj, RevCommit commit,
String subject) {
private Result(String ref, PushResult resSubj, RevCommit commit, String subject) {
this.ref = ref;
this.result = resSubj;
this.commit = commit;
@@ -316,8 +353,7 @@ public class PushOneCommit {
}
public ChangeData getChange() throws OrmException {
return Iterables.getOnlyElement(
queryProvider.get().byKeyPrefix(changeId));
return Iterables.getOnlyElement(queryProvider.get().byKeyPrefix(changeId));
}
public PatchSet getPatchSet() throws OrmException {
@@ -340,8 +376,8 @@ public class PushOneCommit {
assertEquals(pushOptions, getPushOptions());
}
public void assertChange(Change.Status expectedStatus,
String expectedTopic, TestAccount... expectedReviewers)
public void assertChange(
Change.Status expectedStatus, String expectedTopic, TestAccount... expectedReviewers)
throws OrmException {
Change c = getChange().change();
assertThat(c.getSubject()).isEqualTo(resSubj);
@@ -350,13 +386,11 @@ public class PushOneCommit {
assertReviewers(c, expectedReviewers);
}
private void assertReviewers(Change c, TestAccount... expectedReviewers)
throws OrmException {
Iterable<Account.Id> actualIds = approvalsUtil
.getReviewers(db, notesFactory.createChecked(db, c))
.all();
assertThat(actualIds).containsExactlyElementsIn(
Sets.newHashSet(TestAccount.ids(expectedReviewers)));
private void assertReviewers(Change c, TestAccount... expectedReviewers) throws OrmException {
Iterable<Account.Id> actualIds =
approvalsUtil.getReviewers(db, notesFactory.createChecked(db, c)).all();
assertThat(actualIds)
.containsExactlyElementsIn(Sets.newHashSet(TestAccount.ids(expectedReviewers)));
}
public void assertOkStatus() {
@@ -370,22 +404,19 @@ public class PushOneCommit {
public void assertErrorStatus() {
RemoteRefUpdate refUpdate = result.getRemoteUpdate(ref);
assertThat(refUpdate.getStatus())
.named(message(refUpdate))
.isEqualTo(Status.REJECTED_OTHER_REASON);
.named(message(refUpdate))
.isEqualTo(Status.REJECTED_OTHER_REASON);
}
private void assertStatus(Status expectedStatus, String expectedMessage) {
RemoteRefUpdate refUpdate = result.getRemoteUpdate(ref);
assertThat(refUpdate.getStatus())
.named(message(refUpdate))
.isEqualTo(expectedStatus);
assertThat(refUpdate.getStatus()).named(message(refUpdate)).isEqualTo(expectedStatus);
assertThat(refUpdate.getMessage()).isEqualTo(expectedMessage);
}
public void assertMessage(String expectedMessage) {
RemoteRefUpdate refUpdate = result.getRemoteUpdate(ref);
assertThat(message(refUpdate).toLowerCase())
.contains(expectedMessage.toLowerCase());
assertThat(message(refUpdate).toLowerCase()).contains(expectedMessage.toLowerCase());
}
public String getMessage() {

View File

@@ -22,7 +22,6 @@ import com.google.gerrit.server.query.DataSource;
import com.google.gerrit.server.query.Predicate;
import com.google.gerrit.server.query.QueryParseException;
import com.google.gerrit.server.query.change.ChangeData;
import java.io.IOException;
public class ReadOnlyChangeIndex implements ChangeIndex {
@@ -62,8 +61,8 @@ public class ReadOnlyChangeIndex implements ChangeIndex {
}
@Override
public DataSource<ChangeData> getSource(Predicate<ChangeData> p,
QueryOptions opts) throws QueryParseException {
public DataSource<ChangeData> getSource(Predicate<ChangeData> p, QueryOptions opts)
throws QueryParseException {
return index.getSource(p, opts);
}

View File

@@ -18,11 +18,10 @@ import static com.google.common.truth.Truth.assert_;
import static com.google.gerrit.httpd.restapi.RestApiServlet.JSON_MAGIC;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.apache.http.HttpStatus;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.http.HttpStatus;
public class RestResponse extends HttpResponse {
@@ -33,8 +32,7 @@ public class RestResponse extends HttpResponse {
@Override
public Reader getReader() throws IllegalStateException, IOException {
if (reader == null && response.getEntity() != null) {
reader = new InputStreamReader(
response.getEntity().getContent(), UTF_8);
reader = new InputStreamReader(response.getEntity().getContent(), UTF_8);
reader.skip(JSON_MAGIC.length);
}
return reader;

View File

@@ -21,7 +21,7 @@ import com.google.common.net.HttpHeaders;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.restapi.RawInput;
import com.google.gerrit.server.OutputFormat;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.fluent.Request;
@@ -30,21 +30,17 @@ import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import java.io.IOException;
public class RestSession extends HttpSession {
public RestSession(GerritServer server, @Nullable TestAccount account) {
super(server, account);
}
public RestResponse getOK(String endPoint)
throws Exception {
public RestResponse getOK(String endPoint) throws Exception {
return get(endPoint, HttpStatus.SC_OK);
}
public RestResponse get(String endPoint, int expectedStatus)
throws Exception {
public RestResponse get(String endPoint, int expectedStatus) throws Exception {
RestResponse r = get(endPoint);
r.assertStatus(expectedStatus);
return r;
@@ -55,12 +51,10 @@ public class RestSession extends HttpSession {
}
public RestResponse getJsonAccept(String endPoint) throws IOException {
return getWithHeader(endPoint,
new BasicHeader(HttpHeaders.ACCEPT, "application/json"));
return getWithHeader(endPoint, new BasicHeader(HttpHeaders.ACCEPT, "application/json"));
}
public RestResponse getWithHeader(String endPoint, Header header)
throws IOException {
public RestResponse getWithHeader(String endPoint, Header header) throws IOException {
Request get = Request.Get(getUrl(endPoint));
if (header != null) {
get.addHeader(header);
@@ -80,22 +74,19 @@ public class RestSession extends HttpSession {
return putWithHeader(endPoint, null, content);
}
public RestResponse putWithHeader(String endPoint, Header header)
throws IOException {
public RestResponse putWithHeader(String endPoint, Header header) throws IOException {
return putWithHeader(endPoint, header, null);
}
public RestResponse putWithHeader(String endPoint, Header header,
Object content) throws IOException {
public RestResponse putWithHeader(String endPoint, Header header, Object content)
throws IOException {
Request put = Request.Put(getUrl(endPoint));
if (header != null) {
put.addHeader(header);
}
if (content != null) {
put.addHeader(new BasicHeader("Content-Type", "application/json"));
put.body(new StringEntity(
OutputFormat.JSON_COMPACT.newGson().toJson(content),
UTF_8));
put.body(new StringEntity(OutputFormat.JSON_COMPACT.newGson().toJson(content), UTF_8));
}
return execute(put);
}
@@ -104,10 +95,9 @@ public class RestSession extends HttpSession {
Preconditions.checkNotNull(stream);
Request put = Request.Put(getUrl(endPoint));
put.addHeader(new BasicHeader("Content-Type", stream.getContentType()));
put.body(new BufferedHttpEntity(
new InputStreamEntity(
stream.getInputStream(),
stream.getContentLength())));
put.body(
new BufferedHttpEntity(
new InputStreamEntity(stream.getInputStream(), stream.getContentLength())));
return execute(put);
}
@@ -115,13 +105,11 @@ public class RestSession extends HttpSession {
return post(endPoint, null);
}
public RestResponse postOK(String endPoint, Object content)
throws Exception {
public RestResponse postOK(String endPoint, Object content) throws Exception {
return post(endPoint, content, HttpStatus.SC_OK);
}
public RestResponse post(String endPoint, Object content, int expectedStatus)
throws Exception {
public RestResponse post(String endPoint, Object content, int expectedStatus) throws Exception {
RestResponse r = post(endPoint, content);
r.assertStatus(expectedStatus);
return r;
@@ -131,17 +119,15 @@ public class RestSession extends HttpSession {
return postWithHeader(endPoint, content, null);
}
public RestResponse postWithHeader(String endPoint, Object content,
Header header) throws IOException {
public RestResponse postWithHeader(String endPoint, Object content, Header header)
throws IOException {
Request post = Request.Post(getUrl(endPoint));
if (header != null) {
post.addHeader(header);
}
if (content != null) {
post.addHeader(new BasicHeader("Content-Type", "application/json"));
post.body(new StringEntity(
OutputFormat.JSON_COMPACT.newGson().toJson(content),
UTF_8));
post.body(new StringEntity(OutputFormat.JSON_COMPACT.newGson().toJson(content), UTF_8));
}
return execute(post);
}

View File

@@ -23,5 +23,4 @@ import java.lang.annotation.Target;
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface Sandboxed {
}
public @interface Sandboxed {}

View File

@@ -20,7 +20,6 @@ import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
@@ -42,8 +41,7 @@ public class SshSession {
}
@SuppressWarnings("resource")
public String exec(String command, InputStream opt) throws JSchException,
IOException {
public String exec(String command, InputStream opt) throws JSchException, IOException {
ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
try {
channel.setCommand(command);
@@ -62,8 +60,7 @@ public class SshSession {
}
}
public InputStream exec2(String command, InputStream opt) throws JSchException,
IOException {
public InputStream exec2(String command, InputStream opt) throws JSchException, IOException {
ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
channel.setCommand(command);
channel.setInputStream(opt);
@@ -94,12 +91,9 @@ public class SshSession {
private Session getSession() throws JSchException {
if (session == null) {
JSch jsch = new JSch();
jsch.addIdentity("KeyPair",
account.privateKey(), account.sshKey.getPublicKeyBlob(), null);
session = jsch.getSession(
account.username,
addr.getAddress().getHostAddress(),
addr.getPort());
jsch.addIdentity("KeyPair", account.privateKey(), account.sshKey.getPublicKeyBlob(), null);
session =
jsch.getSession(account.username, addr.getAddress().getHostAddress(), addr.getPort());
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
}

View File

@@ -18,14 +18,11 @@ import static java.util.stream.Collectors.toList;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.mail.Address;
import com.jcraft.jsch.KeyPair;
import org.eclipse.jgit.lib.PersonIdent;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jgit.lib.PersonIdent;
public class TestAccount {
public static List<Account.Id> ids(List<TestAccount> accounts) {
@@ -53,8 +50,13 @@ public class TestAccount {
public final String httpPassword;
public String status;
TestAccount(Account.Id id, String username, String email, String fullName,
KeyPair sshKey, String httpPassword) {
TestAccount(
Account.Id id,
String username,
String email,
String fullName,
KeyPair sshKey,
String httpPassword) {
this.id = id;
this.username = username;
this.email = email;
@@ -75,7 +77,8 @@ public class TestAccount {
}
public String getHttpUrl(GerritServer server) {
return String.format("http://%s:%s@%s:%d",
return String.format(
"http://%s:%s@%s:%d",
username,
httpPassword,
server.getHttpAddress().getAddress().getHostAddress(),

View File

@@ -26,6 +26,8 @@ public @interface TestPlugin {
String name();
String sysModule() default "";
String httpModule() default "";
String sshModule() default "";
}

View File

@@ -19,7 +19,6 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.gerrit.extensions.client.InheritableBoolean;
import com.google.gerrit.extensions.client.SubmitType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@@ -29,18 +28,22 @@ public @interface TestProjectInput {
// Fields from ProjectInput for creating the project.
String parent() default "";
boolean createEmptyCommit() default true;
String description() default "";
// These may be null in a ProjectInput, but annotations do not allow null
// default values. Thus these defaults should match ProjectConfig.
SubmitType submitType() default SubmitType.MERGE_IF_NECESSARY;
InheritableBoolean useContributorAgreements()
default InheritableBoolean.INHERIT;
InheritableBoolean useSignedOffBy() default InheritableBoolean.INHERIT;
InheritableBoolean useContentMerge() default InheritableBoolean.INHERIT;
InheritableBoolean requireChangeId() default InheritableBoolean.INHERIT;
InheritableBoolean useContributorAgreements() default InheritableBoolean.INHERIT;
InheritableBoolean useSignedOffBy() default InheritableBoolean.INHERIT;
InheritableBoolean useContentMerge() default InheritableBoolean.INHERIT;
InheritableBoolean requireChangeId() default InheritableBoolean.INHERIT;
// Fields specific to acceptance test behavior.

View File

@@ -22,5 +22,4 @@ import java.lang.annotation.Target;
@Target({METHOD})
@Retention(RUNTIME)
public @interface UseLocalDisk {
}
public @interface UseLocalDisk {}

View File

@@ -23,5 +23,4 @@ import java.lang.annotation.Target;
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface UseSsh {
}
public @interface UseSsh {}