Replace anonymous classes with lambdas

Change-Id: Ia50a1a6a8f7de93941702878b9b9966a565deec8
This commit is contained in:
Dave Borowitz 2019-01-02 10:58:37 -08:00
parent 30b00a9f15
commit 4e4cdfe2ea
69 changed files with 248 additions and 732 deletions

View File

@ -20,7 +20,6 @@ import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.inject.Inject;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Repository;
@ -53,13 +52,7 @@ public class GcAssert {
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((dir, name) -> name.endsWith(".pack"));
}
}
}

View File

@ -100,10 +100,8 @@ public abstract class StandaloneSiteTest {
private final TemporaryFolder tempSiteDir = new TemporaryFolder();
private final TestRule testRunner =
new TestRule() {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
(base, description) ->
new Statement() {
@Override
public void evaluate() throws Throwable {
try {
@ -114,8 +112,6 @@ public abstract class StandaloneSiteTest {
}
}
};
}
};
@Rule public RuleChain ruleChain = RuleChain.outerRule(tempSiteDir).around(testRunner);

View File

@ -19,7 +19,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.io.ByteStreams;
import java.io.BufferedReader;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
@ -168,14 +167,7 @@ public class AsciiDoctor {
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(Paths.get(zipFile)))) {
renderFiles(inputFiles, zip);
File[] cssFiles =
tmpdir.listFiles(
new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".css");
}
});
File[] cssFiles = tmpdir.listFiles((dir, name) -> name.endsWith(".css"));
for (File css : cssFiles) {
zipFile(css, css.getName(), zip);
}

View File

@ -50,12 +50,9 @@ public final class SiteLibraryLoaderUtil {
public static List<Path> listJars(Path dir) throws IOException {
DirectoryStream.Filter<Path> filter =
new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
String name = entry.getFileName().toString();
return (name.endsWith(".jar") || name.endsWith(".zip")) && Files.isRegularFile(entry);
}
entry -> {
String name = entry.getFileName().toString();
return (name.endsWith(".jar") || name.endsWith(".zip")) && Files.isRegularFile(entry);
};
try (DirectoryStream<Path> jars = Files.newDirectoryStream(dir, filter)) {
return new Ordering<Path>() {

View File

@ -184,12 +184,7 @@ public class DynamicItem<T> {
}
final Extension<T> defaultItem = old;
return new RegistrationHandle() {
@Override
public void remove() {
ref.compareAndSet(item, defaultItem);
}
};
return () -> ref.compareAndSet(item, defaultItem);
}
/**

View File

@ -167,10 +167,8 @@ public class DynamicSet<T> implements Iterable<T> {
public Iterable<Extension<T>> entries() {
final Iterator<AtomicReference<Extension<T>>> itr = items.iterator();
return new Iterable<Extension<T>>() {
@Override
public Iterator<Extension<T>> iterator() {
return new Iterator<Extension<T>>() {
return () ->
new Iterator<Extension<T>>() {
private Extension<T> next;
@Override
@ -199,8 +197,6 @@ public class DynamicSet<T> implements Iterable<T> {
throw new UnsupportedOperationException();
}
};
}
};
}
/**
@ -266,12 +262,9 @@ public class DynamicSet<T> implements Iterable<T> {
final AtomicReference<Extension<T>> ref =
new AtomicReference<>(new Extension<>(pluginName, item));
items.add(ref);
return new RegistrationHandle() {
@Override
public void remove() {
if (ref.compareAndSet(ref.get(), null)) {
items.remove(ref);
}
return () -> {
if (ref.compareAndSet(ref.get(), null)) {
items.remove(ref);
}
};
}

View File

@ -36,12 +36,7 @@ public class PrivateInternals_DynamicMapImpl<T> extends DynamicMap<T> {
requireNonNull(item);
final NamePair key = new NamePair(pluginName, exportName);
items.put(key, item);
return new RegistrationHandle() {
@Override
public void remove() {
items.remove(key, item);
}
};
return () -> items.remove(key, item);
}
/**

View File

@ -32,7 +32,6 @@ import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.config.AuthConfig;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.internal.UniqueAnnotations;
import com.google.inject.servlet.ServletModule;
import java.io.IOException;
@ -171,15 +170,7 @@ class UrlModule extends ServletModule {
private Key<HttpServlet> key(HttpServlet servlet) {
final Key<HttpServlet> srv = Key.get(HttpServlet.class, UniqueAnnotations.create());
bind(srv)
.toProvider(
new Provider<HttpServlet>() {
@Override
public HttpServlet get() {
return servlet;
}
})
.in(SINGLETON);
bind(srv).toProvider(() -> servlet).in(SINGLETON);
return srv;
}

View File

@ -35,7 +35,6 @@ import com.google.common.collect.Maps;
import com.google.common.flogger.FluentLogger;
import com.google.common.io.ByteStreams;
import com.google.common.net.HttpHeaders;
import com.google.gerrit.extensions.registration.RegistrationHandle;
import com.google.gerrit.httpd.resources.Resource;
import com.google.gerrit.httpd.resources.ResourceKey;
import com.google.gerrit.httpd.resources.SmallResource;
@ -84,8 +83,6 @@ import javax.servlet.FilterChain;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -174,13 +171,7 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
GuiceFilter filter = load(plugin);
final String name = plugin.getName();
final PluginHolder holder = new PluginHolder(plugin, filter);
plugin.add(
new RegistrationHandle() {
@Override
public void remove() {
plugins.remove(name, holder);
}
});
plugin.add(() -> plugins.remove(name, holder));
plugins.put(name, holder);
}
@ -234,12 +225,7 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
HttpServletRequest wr = wrapper.create(req, name);
FilterChain chain =
new FilterChain() {
@Override
public void doFilter(ServletRequest req, ServletResponse res) throws IOException {
onDefault(holder, (HttpServletRequest) req, (HttpServletResponse) res);
}
};
(sreq, sres) -> onDefault(holder, (HttpServletRequest) sreq, (HttpServletResponse) sres);
if (holder.filter != null) {
holder.filter.doFilter(wr, res, chain);
} else {

View File

@ -19,7 +19,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.registration.RegistrationHandle;
import com.google.gerrit.httpd.resources.Resource;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.plugins.Plugin;
@ -40,8 +39,6 @@ import javax.servlet.FilterChain;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -66,12 +63,7 @@ public class LfsPluginServlet extends HttpServlet
LfsPluginServlet(@GerritServerConfig Config cfg) {
this.pluginName = cfg.getString("lfs", null, "plugin");
this.chain =
new FilterChain() {
@Override
public void doFilter(ServletRequest req, ServletResponse res) throws IOException {
Resource.NOT_FOUND.send((HttpServletRequest) req, (HttpServletResponse) res);
}
};
(req, res) -> Resource.NOT_FOUND.send((HttpServletRequest) req, (HttpServletResponse) res);
this.filter = new AtomicReference<>();
}
@ -123,13 +115,7 @@ public class LfsPluginServlet extends HttpServlet
return;
}
final GuiceFilter guiceFilter = load(plugin);
plugin.add(
new RegistrationHandle() {
@Override
public void remove() {
filter.compareAndSet(guiceFilter, null);
}
});
plugin.add(() -> filter.compareAndSet(guiceFilter, null));
filter.set(guiceFilter);
}

View File

@ -16,7 +16,6 @@ package com.google.gerrit.index;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
@ -176,24 +175,21 @@ public class Schema<T> {
public final Iterable<Values<T>> buildFields(T obj) {
return FluentIterable.from(fields.values())
.transform(
new Function<FieldDef<T, ?>, Values<T>>() {
@Override
public Values<T> apply(FieldDef<T, ?> f) {
Object v;
try {
v = f.get(obj);
} catch (OrmException e) {
logger.atSevere().withCause(e).log(
"error getting field %s of %s", f.getName(), obj);
return null;
}
if (v == null) {
return null;
} else if (f.isRepeatable()) {
return new Values<>(f, (Iterable<?>) v);
} else {
return new Values<>(f, Collections.singleton(v));
}
f -> {
Object v;
try {
v = f.get(obj);
} catch (OrmException e) {
logger.atSevere().withCause(e).log(
"error getting field %s of %s", f.getName(), obj);
return null;
}
if (v == null) {
return null;
} else if (f.isRepeatable()) {
return new Values<>(f, (Iterable<?>) v);
} else {
return new Values<>(f, Collections.singleton(v));
}
})
.filter(Predicates.notNull());

View File

@ -187,9 +187,6 @@ public class DisabledMetricMaker extends MetricMaker {
@Override
public RegistrationHandle newTrigger(Set<CallbackMetric<?>> metrics, Runnable trigger) {
return new RegistrationHandle() {
@Override
public void remove() {}
};
return () -> {};
}
}

View File

@ -14,6 +14,7 @@
package com.google.gerrit.metrics.dropwizard;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.google.gerrit.metrics.CallbackMetric0;
@ -71,12 +72,10 @@ class CallbackMetricImpl0<V> extends CallbackMetric0<V> implements CallbackMetri
public void register(Runnable trigger) {
registry.register(
name,
new com.codahale.metrics.Gauge<V>() {
@Override
public V getValue() {
trigger.run();
return value;
}
});
(Gauge<V>)
() -> {
trigger.run();
return value;
});
}
}

View File

@ -305,14 +305,7 @@ public class DropWizardMetricMaker extends MetricMaker {
}
trigger.run();
return new RegistrationHandle() {
@Override
public void remove() {
for (CallbackMetricGlue m : all) {
m.remove();
}
}
};
return () -> all.forEach(CallbackMetricGlue::remove);
}
synchronized void remove(String name) {

View File

@ -15,7 +15,6 @@
package com.google.gerrit.metrics.proc;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.gerrit.common.Version;
import com.google.gerrit.metrics.CallbackMetric0;
@ -74,12 +73,7 @@ public class ProcMetricModule extends MetricModule {
"proc/cpu/usage",
Double.class,
new Description("CPU time used by the process").setCumulative().setUnit(Units.SECONDS),
new Supplier<Double>() {
@Override
public Double get() {
return provider.getProcessCpuTime() / 1e9;
}
});
() -> provider.getProcessCpuTime() / 1e9);
}
if (provider.getOpenFileDescriptorCount() != -1) {

View File

@ -114,7 +114,6 @@ import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Stage;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@ -229,12 +228,7 @@ public class Daemon extends SiteProgram {
}
mustHaveValidSite();
Thread.setDefaultUncaughtExceptionHandler(
new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
logger.atSevere().withCause(e).log("Thread %s threw exception", t.getName());
}
});
(t, e) -> logger.atSevere().withCause(e).log("Thread %s threw exception", t.getName()));
if (runId != null) {
runFile = getSitePath().resolve("logs").resolve("gerrit.run");

View File

@ -49,7 +49,6 @@ import org.eclipse.jetty.server.ForwardedRequestCustomizer;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
@ -241,13 +240,9 @@ public class JettyServer {
defaultPort = 8080;
config.addCustomizer(new ForwardedRequestCustomizer());
config.addCustomizer(
new HttpConfiguration.Customizer() {
@Override
public void customize(
Connector connector, HttpConfiguration channelConfig, Request request) {
request.setScheme(HttpScheme.HTTPS.asString());
request.setSecure(true);
}
(connector, channelConfig, request) -> {
request.setScheme(HttpScheme.HTTPS.asString());
request.setSecure(true);
});
c = newServerConnector(server, acceptors, config);

View File

@ -39,12 +39,7 @@ public class StaleLibraryRemover {
public void remove(String pattern) {
if (!Strings.isNullOrEmpty(pattern)) {
DirectoryStream.Filter<Path> filter =
new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) {
return entry.getFileName().toString().matches("^" + pattern + "$");
}
};
entry -> entry.getFileName().toString().matches("^" + pattern + "$");
try (DirectoryStream<Path> paths = Files.newDirectoryStream(lib_dir, filter)) {
for (Path p : paths) {
String old = p.getFileName().toString();

View File

@ -36,10 +36,8 @@ public class EditList {
}
public Iterable<Hunk> getHunks() {
return new Iterable<Hunk>() {
@Override
public Iterator<Hunk> iterator() {
return new Iterator<Hunk>() {
return () ->
new Iterator<Hunk>() {
private int curIdx;
@Override
@ -60,8 +58,6 @@ public class EditList {
throw new UnsupportedOperationException();
}
};
}
};
}
private int findCombinedEnd(int i) {

View File

@ -512,11 +512,8 @@ public class IdentifiedUser extends CurrentUser {
remotePeer = Providers.of(remotePeerProvider.get());
} catch (OutOfScopeException | ProvisionException e) {
remotePeer =
new Provider<SocketAddress>() {
@Override
public SocketAddress get() {
throw e;
}
() -> {
throw e;
};
}
return new IdentifiedUser(

View File

@ -30,7 +30,6 @@ import com.google.gerrit.git.RefUpdateUtil;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.InternalAccountUpdate.Builder;
import com.google.gerrit.server.account.externalids.ExternalIdNotes;
import com.google.gerrit.server.account.externalids.ExternalIdNotes.ExternalIdNotesLoader;
import com.google.gerrit.server.account.externalids.ExternalIds;
@ -154,12 +153,9 @@ public class AccountsUpdate {
void update(AccountState accountState, InternalAccountUpdate.Builder update) throws IOException;
static AccountUpdater join(List<AccountUpdater> updaters) {
return new AccountUpdater() {
@Override
public void update(AccountState accountState, Builder update) throws IOException {
for (AccountUpdater updater : updaters) {
updater.update(accountState, update);
}
return (accountState, update) -> {
for (AccountUpdater updater : updaters) {
updater.update(accountState, update);
}
};
}

View File

@ -186,13 +186,7 @@ class Helper {
Subject subject = ctx.getSubject();
try {
return Subject.doAs(
subject,
new PrivilegedExceptionAction<DirContext>() {
@Override
public DirContext run() throws IOException, NamingException {
return createContext(env);
}
});
subject, (PrivilegedExceptionAction<DirContext>) () -> createContext(env));
} catch (PrivilegedActionException e) {
Throwables.throwIfInstanceOf(e.getException(), IOException.class);
Throwables.throwIfInstanceOf(e.getException(), NamingException.class);

View File

@ -42,7 +42,6 @@ class H2CacheDefProxy<K, V> implements PersistentCacheDef<K, V> {
return source.expireFromMemoryAfterAccess();
}
@SuppressWarnings("unchecked")
@Override
public Weigher<K, V> weigher() {
Weigher<K, V> weigher = source.weigher();
@ -52,13 +51,10 @@ class H2CacheDefProxy<K, V> implements PersistentCacheDef<K, V> {
// introduce weigher that performs calculations
// on value that is being stored not on ValueHolder
return (Weigher<K, V>)
new Weigher<K, ValueHolder<V>>() {
@Override
public int weigh(K key, ValueHolder<V> value) {
return weigher.weigh(key, value.value);
}
};
Weigher<K, ValueHolder<V>> holderWeigher = (k, v) -> weigher.weigh(k, v.value);
@SuppressWarnings("unchecked")
Weigher<K, V> ret = (Weigher<K, V>) holderWeigher;
return ret;
}
@Override

View File

@ -112,11 +112,6 @@ class DefaultMemoryCacheFactory implements MemoryCacheFactory {
}
private static <K, V> Weigher<K, V> unitWeight() {
return new Weigher<K, V>() {
@Override
public int weigh(K key, V value) {
return 1;
}
};
return (key, value) -> 1;
}
}

View File

@ -33,15 +33,7 @@ public class CacheResource extends ConfigResource {
}
public CacheResource(String pluginName, String cacheName, Cache<?, ?> cache) {
this(
pluginName,
cacheName,
new Provider<Cache<?, ?>>() {
@Override
public Cache<?, ?> get() {
return cache;
}
});
this(pluginName, cacheName, () -> cache);
}
public String getName() {

View File

@ -18,7 +18,6 @@ import com.vladsch.flexmark.ast.Heading;
import com.vladsch.flexmark.ast.Node;
import com.vladsch.flexmark.ext.anchorlink.AnchorLink;
import com.vladsch.flexmark.ext.anchorlink.internal.AnchorLinkNodeRenderer;
import com.vladsch.flexmark.html.CustomNodeRenderer;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.html.HtmlRenderer.HtmlRendererExtension;
import com.vladsch.flexmark.html.HtmlWriter;
@ -61,21 +60,8 @@ public class MarkdownFormatterHeader {
Arrays.asList(
new NodeRenderingHandler<>(
AnchorLink.class,
new CustomNodeRenderer<AnchorLink>() {
@Override
public void render(
AnchorLink node, NodeRendererContext context, HtmlWriter html) {
HeadingNodeRenderer.this.render(node, context);
}
}),
new NodeRenderingHandler<>(
Heading.class,
new CustomNodeRenderer<Heading>() {
@Override
public void render(Heading node, NodeRendererContext context, HtmlWriter html) {
HeadingNodeRenderer.this.render(node, context, html);
}
})));
(node, context, html) -> HeadingNodeRenderer.this.render(node, context)),
new NodeRenderingHandler<>(Heading.class, HeadingNodeRenderer.this::render)));
}
void render(final AnchorLink node, final NodeRendererContext context) {
@ -116,25 +102,15 @@ public class MarkdownFormatterHeader {
.withAttr()
.tagLine(
"h" + node.getLevel(),
new Runnable() {
@Override
public void run() {
html.srcPos(node.getText()).withAttr().tag("span");
context.renderChildren(node);
html.tag("/span");
}
() -> {
html.srcPos(node.getText()).withAttr().tag("span");
context.renderChildren(node);
html.tag("/span");
});
} else {
html.srcPos(node.getText())
.withAttr()
.tagLine(
"h" + node.getLevel(),
new Runnable() {
@Override
public void run() {
context.renderChildren(node);
}
});
.tagLine("h" + node.getLevel(), () -> context.renderChildren(node));
}
} else {
context.delegateRender();

View File

@ -50,7 +50,6 @@ import com.google.gerrit.server.data.AccountAttribute;
import com.google.gerrit.server.data.ApprovalAttribute;
import com.google.gerrit.server.data.ChangeAttribute;
import com.google.gerrit.server.data.PatchSetAttribute;
import com.google.gerrit.server.data.RefUpdateAttribute;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.plugincontext.PluginItemContext;
@ -151,42 +150,32 @@ public class StreamEventsApiListener
private Supplier<ChangeAttribute> changeAttributeSupplier(Change change, ChangeNotes notes) {
return Suppliers.memoize(
new Supplier<ChangeAttribute>() {
@Override
public ChangeAttribute get() {
try {
return eventFactory.asChangeAttribute(change, notes);
} catch (OrmException e) {
throw new RuntimeException(e);
}
() -> {
try {
return eventFactory.asChangeAttribute(change, notes);
} catch (OrmException e) {
throw new RuntimeException(e);
}
});
}
private Supplier<AccountAttribute> accountAttributeSupplier(AccountInfo account) {
return Suppliers.memoize(
new Supplier<AccountAttribute>() {
@Override
public AccountAttribute get() {
return account != null
() ->
account != null
? eventFactory.asAccountAttribute(new Account.Id(account._accountId))
: null;
}
});
: null);
}
private Supplier<PatchSetAttribute> patchSetAttributeSupplier(
final Change change, PatchSet patchSet) {
return Suppliers.memoize(
new Supplier<PatchSetAttribute>() {
@Override
public PatchSetAttribute get() {
try (Repository repo = repoManager.openRepository(change.getProject());
RevWalk revWalk = new RevWalk(repo)) {
return eventFactory.asPatchSetAttribute(revWalk, change, patchSet);
} catch (IOException e) {
throw new RuntimeException(e);
}
() -> {
try (Repository repo = repoManager.openRepository(change.getProject());
RevWalk revWalk = new RevWalk(repo)) {
return eventFactory.asPatchSetAttribute(revWalk, change, patchSet);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
@ -226,21 +215,18 @@ public class StreamEventsApiListener
final Map<String, ApprovalInfo> oldApprovals) {
final Map<String, Short> approvals = convertApprovalsMap(newApprovals);
return Suppliers.memoize(
new Supplier<ApprovalAttribute[]>() {
@Override
public ApprovalAttribute[] get() {
LabelTypes labelTypes = projectCache.get(change.getProject()).getLabelTypes();
if (approvals.size() > 0) {
ApprovalAttribute[] r = new ApprovalAttribute[approvals.size()];
int i = 0;
for (Map.Entry<String, Short> approval : approvals.entrySet()) {
r[i++] =
getApprovalAttribute(labelTypes, approval, convertApprovalsMap(oldApprovals));
}
return r;
() -> {
LabelTypes labelTypes = projectCache.get(change.getProject()).getLabelTypes();
if (approvals.size() > 0) {
ApprovalAttribute[] r = new ApprovalAttribute[approvals.size()];
int i = 0;
for (Entry<String, Short> approval : approvals.entrySet()) {
r[i++] =
getApprovalAttribute(labelTypes, approval, convertApprovalsMap(oldApprovals));
}
return null;
return r;
}
return null;
});
}
@ -378,15 +364,11 @@ public class StreamEventsApiListener
final Branch.NameKey refName = new Branch.NameKey(ev.getProjectName(), ev.getRefName());
event.refUpdate =
Suppliers.memoize(
new Supplier<RefUpdateAttribute>() {
@Override
public RefUpdateAttribute get() {
return eventFactory.asRefUpdateAttribute(
() ->
eventFactory.asRefUpdateAttribute(
ObjectId.fromString(ev.getOldObjectId()),
ObjectId.fromString(ev.getNewObjectId()),
refName);
}
});
refName));
dispatcher.run(d -> d.postEvent(refName, event));
}

View File

@ -106,14 +106,11 @@ public class GroupCollector {
Project.NameKey project) {
return new GroupCollector(
transformRefs(changeRefsById),
new Lookup() {
@Override
public List<String> lookup(PatchSet.Id psId) throws OrmException {
// TODO(dborowitz): Reuse open repository from caller.
ChangeNotes notes = notesFactory.createChecked(project, psId.getParentKey());
PatchSet ps = psUtil.get(notes, psId);
return ps != null ? ps.getGroups() : null;
}
psId -> {
// TODO(dborowitz): Reuse open repository from caller.
ChangeNotes notes = notesFactory.createChecked(project, psId.getParentKey());
PatchSet ps = psUtil.get(notes, psId);
return ps != null ? ps.getGroups() : null;
});
}
@ -135,12 +132,9 @@ public class GroupCollector {
ListMultimap<PatchSet.Id, String> groupLookup) {
this(
patchSetsBySha,
new Lookup() {
@Override
public List<String> lookup(PatchSet.Id psId) {
List<String> groups = groupLookup.get(psId);
return !groups.isEmpty() ? groups : null;
}
psId -> {
List<String> groups = groupLookup.get(psId);
return !groups.isEmpty() ? groups : null;
});
}

View File

@ -17,7 +17,6 @@ package com.google.gerrit.server.git;
import static java.util.stream.Collectors.toList;
import com.google.common.base.CaseFormat;
import com.google.common.base.Supplier;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.lifecycle.LifecycleModule;
@ -86,12 +85,8 @@ public class WorkQueue {
}
private static final UncaughtExceptionHandler LOG_UNCAUGHT_EXCEPTION =
new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
(t, e) ->
logger.atSevere().withCause(e).log("WorkQueue thread %s threw exception", t.getName());
}
};
private final ScheduledExecutorService defaultQueue;
private final IdGenerator idGenerator;
@ -360,68 +355,38 @@ public class WorkQueue {
new Description("Maximum allowed number of threads in the pool")
.setGauge()
.setUnit("threads"),
new Supplier<Long>() {
@Override
public Long get() {
return (long) getMaximumPoolSize();
}
});
() -> (long) getMaximumPoolSize());
metrics.newCallbackMetric(
getMetricName(queueName, "pool_size"),
Long.class,
new Description("Current number of threads in the pool").setGauge().setUnit("threads"),
new Supplier<Long>() {
@Override
public Long get() {
return (long) getPoolSize();
}
});
() -> (long) getPoolSize());
metrics.newCallbackMetric(
getMetricName(queueName, "active_threads"),
Long.class,
new Description("Number number of threads that are actively executing tasks")
.setGauge()
.setUnit("threads"),
new Supplier<Long>() {
@Override
public Long get() {
return (long) getActiveCount();
}
});
() -> (long) getActiveCount());
metrics.newCallbackMetric(
getMetricName(queueName, "scheduled_tasks"),
Integer.class,
new Description("Number of scheduled tasks in the queue").setGauge().setUnit("tasks"),
new Supplier<Integer>() {
@Override
public Integer get() {
return getQueue().size();
}
});
() -> getQueue().size());
metrics.newCallbackMetric(
getMetricName(queueName, "total_scheduled_tasks_count"),
Long.class,
new Description("Total number of tasks that have been scheduled for execution")
.setCumulative()
.setUnit("tasks"),
new Supplier<Long>() {
@Override
public Long get() {
return getTaskCount();
}
});
this::getTaskCount);
metrics.newCallbackMetric(
getMetricName(queueName, "total_completed_tasks_count"),
Long.class,
new Description("Total number of tasks that have completed execution")
.setCumulative()
.setUnit("tasks"),
new Supplier<Long>() {
@Override
public Long get() {
return getCompletedTaskCount();
}
});
this::getCompletedTaskCount);
}
private String getMetricName(String queueName, String metricName) {

View File

@ -39,16 +39,13 @@ public final class IndexUtils {
ImmutableMap.of("_", " ", ".", " ");
public static final Function<Exception, IOException> MAPPER =
new Function<Exception, IOException>() {
@Override
public IOException apply(Exception in) {
if (in instanceof IOException) {
return (IOException) in;
} else if (in instanceof ExecutionException && in.getCause() instanceof IOException) {
return (IOException) in.getCause();
} else {
return new IOException(in);
}
in -> {
if (in instanceof IOException) {
return (IOException) in;
} else if (in instanceof ExecutionException && in.getCause() instanceof IOException) {
return (IOException) in.getCause();
} else {
return new IOException(in);
}
};

View File

@ -25,7 +25,6 @@ import com.google.gerrit.extensions.events.ChangeIndexedListener;
import com.google.gerrit.index.Index;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.index.IndexExecutor;
import com.google.gerrit.server.index.IndexUtils;
@ -309,11 +308,8 @@ public class ChangeIndexer {
public final T call() throws Exception {
try {
RequestContext newCtx =
new RequestContext() {
@Override
public CurrentUser getUser() {
throw new OutOfScopeException("No user during ChangeIndexer");
}
() -> {
throw new OutOfScopeException("No user during ChangeIndexer");
};
RequestContext oldCtx = context.setContext(newCtx);
try {

View File

@ -33,12 +33,7 @@ public final class HostPlatform {
private static boolean compute(String platform) {
final String osDotName =
AccessController.doPrivileged(
new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty("os.name");
}
});
(PrivilegedAction<String>) () -> System.getProperty("os.name"));
return osDotName != null && osDotName.toLowerCase().contains(platform);
}

View File

@ -331,13 +331,6 @@ public class JarScanner implements PluginContentScanner, AutoCloseable {
if (attributes == null) {
return Collections.emptyMap();
}
return Maps.transformEntries(
attributes,
new Maps.EntryTransformer<Object, Object, String>() {
@Override
public String transformEntry(Object key, Object value) {
return (String) value;
}
});
return Maps.transformEntries(attributes, (key, value) -> (String) value);
}
}

View File

@ -290,12 +290,7 @@ public class PluginLoader implements LifecycleListener {
private void removeStalePluginFiles() {
DirectoryStream.Filter<Path> filter =
new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
return entry.getFileName().toString().startsWith("plugin_");
}
};
entry -> entry.getFileName().toString().startsWith("plugin_");
try (DirectoryStream<Path> files = Files.newDirectoryStream(tempDir, filter)) {
for (Path file : files) {
logger.atInfo().log("Removing stale plugin file: %s", file.toFile().getName());

View File

@ -160,12 +160,9 @@ public class PluginMetricMaker extends MetricMaker implements LifecycleListener
public RegistrationHandle newTrigger(Set<CallbackMetric<?>> metrics, Runnable trigger) {
final RegistrationHandle handle = root.newTrigger(metrics, trigger);
cleanup.add(handle);
return new RegistrationHandle() {
@Override
public void remove() {
handle.remove();
cleanup.remove(handle);
}
return () -> {
handle.remove();
cleanup.remove(handle);
};
}

View File

@ -34,17 +34,14 @@ public class PluginUtil {
return ImmutableList.of();
}
DirectoryStream.Filter<Path> filter =
new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
String n = entry.getFileName().toString();
boolean accept =
!n.startsWith(".last_") && !n.startsWith(".next_") && Files.isRegularFile(entry);
if (!Strings.isNullOrEmpty(suffix)) {
accept &= n.endsWith(suffix);
}
return accept;
entry -> {
String n = entry.getFileName().toString();
boolean accept =
!n.startsWith(".last_") && !n.startsWith(".next_") && Files.isRegularFile(entry);
if (!Strings.isNullOrEmpty(suffix)) {
accept &= n.endsWith(suffix);
}
return accept;
};
try (DirectoryStream<Path> files = Files.newDirectoryStream(pluginsDir, filter)) {
return Ordering.natural().sortedCopy(files);

View File

@ -64,7 +64,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@ -422,12 +421,7 @@ public class ProjectState {
* Starts from this project and progresses up the hierarchy to All-Projects.
*/
public Iterable<ProjectState> tree() {
return new Iterable<ProjectState>() {
@Override
public Iterator<ProjectState> iterator() {
return new ProjectHierarchyIterator(projectCache, allProjectsName, ProjectState.this);
}
};
return () -> new ProjectHierarchyIterator(projectCache, allProjectsName, ProjectState.this);
}
/**

View File

@ -86,15 +86,12 @@ public class StarredChanges
@Override
public RestView<AccountResource> list() throws ResourceNotFoundException {
return new RestReadView<AccountResource>() {
@Override
public Object apply(AccountResource self)
throws BadRequestException, AuthException, OrmException, PermissionBackendException {
QueryChanges query = changes.list();
query.addQuery("starredby:" + self.getUser().getAccountId().get());
return query.apply(TopLevelResource.INSTANCE);
}
};
return (RestReadView<AccountResource>)
self -> {
QueryChanges query = changes.list();
query.addQuery("starredby:" + self.getUser().getAccountId().get());
return query.apply(TopLevelResource.INSTANCE);
};
}
@Singleton

View File

@ -19,7 +19,6 @@ import com.google.gerrit.extensions.common.SuggestedReviewerInfo;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.change.ChangeResource;
import com.google.gerrit.server.config.GerritServerConfig;
@ -81,16 +80,13 @@ public class SuggestChangeReviewers extends SuggestReviewers
private VisibilityControl getVisibility(ChangeResource rsrc) {
return new VisibilityControl() {
@Override
public boolean isVisibleTo(Account.Id account) {
// Use the destination reference, not the change, as private changes deny anyone who is not
// already a reviewer.
return permissionBackend
.absentUser(account)
.ref(rsrc.getChange().getDest())
.testOrFalse(RefPermission.READ);
}
return account -> {
// Use the destination reference, not the change, as private changes deny anyone who is not
// already a reviewer.
return permissionBackend
.absentUser(account)
.ref(rsrc.getChange().getDest())
.testOrFalse(RefPermission.READ);
};
}
}

View File

@ -18,11 +18,9 @@ import static java.util.Objects.requireNonNull;
import com.google.common.base.Throwables;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.RequestCleanup;
import com.google.gerrit.server.git.ProjectRunnable;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.servlet.ServletScopes;
import java.util.concurrent.Callable;
@ -167,14 +165,7 @@ public abstract class RequestScopePropagator {
protected <T> Callable<T> context(RequestContext context, Callable<T> callable) {
return () -> {
RequestContext old =
local.setContext(
new RequestContext() {
@Override
public CurrentUser getUser() {
return context.getUser();
}
});
RequestContext old = local.setContext(context::getUser);
try {
return callable.call();
} finally {
@ -186,16 +177,7 @@ public abstract class RequestScopePropagator {
protected <T> Callable<T> cleanup(Callable<T> callable) {
return () -> {
RequestCleanup cleanup =
scope
.scope(
Key.get(RequestCleanup.class),
new Provider<RequestCleanup>() {
@Override
public RequestCleanup get() {
return new RequestCleanup();
}
})
.get();
scope.scope(Key.get(RequestCleanup.class), RequestCleanup::new).get();
try {
return callable.call();
} finally {

View File

@ -91,16 +91,13 @@ class CommandFactoryProvider implements Provider<CommandFactory>, LifecycleListe
@Override
public CommandFactory get() {
return new CommandFactory() {
@Override
public Command createCommand(String requestCommand) {
String c = requestCommand;
SshCreateCommandInterceptor interceptor = createCommandInterceptor.get();
if (interceptor != null) {
c = interceptor.intercept(c);
}
return new Trampoline(c);
return requestCommand -> {
String c = requestCommand;
SshCreateCommandInterceptor interceptor = createCommandInterceptor.get();
if (interceptor != null) {
c = interceptor.intercept(c);
}
return new Trampoline(c);
};
}

View File

@ -50,24 +50,14 @@ public class DispatchCommandProvider implements Provider<DispatchCommand> {
if (m.putIfAbsent(name.value(), commandProvider) != null) {
throw new IllegalArgumentException(name.value() + " exists");
}
return new RegistrationHandle() {
@Override
public void remove() {
m.remove(name.value(), commandProvider);
}
};
return () -> m.remove(name.value(), commandProvider);
}
public RegistrationHandle replace(CommandName name, Provider<Command> cmd) {
final ConcurrentMap<String, CommandProvider> m = getMap();
final CommandProvider commandProvider = new CommandProvider(cmd, null);
m.put(name.value(), commandProvider);
return new RegistrationHandle() {
@Override
public void remove() {
m.remove(name.value(), commandProvider);
}
};
return () -> m.remove(name.value(), commandProvider);
}
ConcurrentMap<String, CommandProvider> getMap() {

View File

@ -34,18 +34,15 @@ public abstract class SshCommand extends BaseCommand {
@Override
public void start(Environment env) throws IOException {
startThread(
new CommandRunnable() {
@Override
public void run() throws Exception {
parseCommandLine();
stdout = toPrintWriter(out);
stderr = toPrintWriter(err);
try (TraceContext traceContext = enableTracing()) {
SshCommand.this.run();
} finally {
stdout.flush();
stderr.flush();
}
() -> {
parseCommandLine();
stdout = toPrintWriter(out);
stderr = toPrintWriter(err);
try (TraceContext traceContext = enableTracing()) {
SshCommand.this.run();
} finally {
stdout.flush();
stderr.flush();
}
},
AccessPath.SSH_COMMAND);

View File

@ -69,10 +69,7 @@ import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.cipher.Cipher;
import org.apache.sshd.common.compression.BuiltinCompressions;
import org.apache.sshd.common.compression.Compression;
import org.apache.sshd.common.file.FileSystemFactory;
import org.apache.sshd.common.forward.DefaultForwarderFactory;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.AbstractIoServiceFactory;
import org.apache.sshd.common.io.IoAcceptor;
import org.apache.sshd.common.io.IoServiceFactory;
@ -271,14 +268,11 @@ public class SshDaemon extends SshServer implements SshInfo, LifecycleListener {
// Log a session close without authentication as a failure.
//
s.addCloseFutureListener(
new SshFutureListener<CloseFuture>() {
@Override
public void operationComplete(CloseFuture future) {
connected.decrementAndGet();
if (sd.isAuthenticationError()) {
authFailures.increment();
sshLog.onAuthFail(sd);
}
future -> {
connected.decrementAndGet();
if (sd.isAuthenticationError()) {
authFailures.increment();
sshLog.onAuthFail(sd);
}
});
return s;
@ -718,10 +712,8 @@ public class SshDaemon extends SshServer implements SshInfo, LifecycleListener {
private void initFileSystemFactory() {
setFileSystemFactory(
new FileSystemFactory() {
@Override
public FileSystem createFileSystem(Session session) throws IOException {
return new FileSystem() {
session ->
new FileSystem() {
@Override
public void close() throws IOException {}
@ -779,8 +771,6 @@ public class SshDaemon extends SshServer implements SshInfo, LifecycleListener {
public Set<String> supportedFileAttributeViews() {
return null;
}
};
}
});
});
}
}

View File

@ -30,8 +30,6 @@ import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import org.apache.commons.codec.binary.Base64;
import org.apache.sshd.common.SshException;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
import org.apache.sshd.server.session.ServerSession;
@ -136,16 +134,13 @@ public class SshUtil {
}
session.addCloseFutureListener(
new SshFutureListener<CloseFuture>() {
@Override
public void operationComplete(CloseFuture future) {
final Context ctx = sshScope.newContext(sd, null);
final Context old = sshScope.set(ctx);
try {
sshLog.onLogout();
} finally {
sshScope.set(old);
}
future -> {
final Context ctx1 = sshScope.newContext(sd, null);
final Context old1 = sshScope.set(ctx1);
try {
sshLog.onLogout();
} finally {
sshScope.set(old1);
}
});
}

View File

@ -17,7 +17,6 @@ package com.google.gerrit.testing;
import org.eclipse.jgit.lib.Config;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.model.Statement;
@ -29,15 +28,11 @@ public class GerritServerTests extends GerritBaseTests {
@Rule
public TestRule testRunner =
new TestRule() {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
(base, description) ->
new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
}
};
}
};
}

View File

@ -16,12 +16,10 @@ package com.google.gerrit.testing;
import com.google.gerrit.lifecycle.LifecycleManager;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.AccountManager;
import com.google.gerrit.server.account.AuthRequest;
import com.google.gerrit.server.schema.SchemaCreator;
import com.google.gerrit.server.util.RequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.inject.Guice;
import com.google.inject.Inject;
@ -85,13 +83,7 @@ public final class InMemoryTestEnvironment implements MethodRule {
public void setApiUser(Account.Id id) {
IdentifiedUser user = userFactory.create(id);
requestContext.setContext(
new RequestContext() {
@Override
public CurrentUser getUser() {
return user;
}
});
requestContext.setContext(() -> user);
}
private void setUp(Object target) throws Exception {

View File

@ -2698,16 +2698,9 @@ public class ChangeIT extends AbstractDaemonTest {
RegistrationHandle handle =
changeMessageModifiers.add(
"gerrit",
new ChangeMessageModifier() {
@Override
public String onSubmit(
String newCommitMessage,
RevCommit original,
RevCommit mergeTip,
Branch.NameKey destination) {
assertThat(original.getName()).isNotEqualTo(mergeTip.getName());
return newCommitMessage + "Custom: " + destination.get();
}
(newCommitMessage, original, mergeTip, destination) -> {
assertThat(original.getName()).isNotEqualTo(mergeTip.getName());
return newCommitMessage + "Custom: " + destination.get();
});
ChangeInfo actual;
try {

View File

@ -1173,14 +1173,7 @@ public class RevisionIT extends AbstractDaemonTest {
public void commit() throws Exception {
WebLinkInfo expectedWebLinkInfo = new WebLinkInfo("foo", "imageUrl", "url");
RegistrationHandle handle =
patchSetLinks.add(
"gerrit",
new PatchSetWebLink() {
@Override
public WebLinkInfo getPatchSetWebLink(String projectName, String commit) {
return expectedWebLinkInfo;
}
});
patchSetLinks.add("gerrit", (projectName, commit) -> expectedWebLinkInfo);
try {
PushOneCommit.Result r = createChange();

View File

@ -980,12 +980,7 @@ public class ExternalIdIT extends AbstractDaemonTest {
private AutoCloseable createFailOnLoadContext() {
externalIdReader.setFailOnLoad(true);
return new AutoCloseable() {
@Override
public void close() {
externalIdReader.setFailOnLoad(false);
}
};
return () -> externalIdReader.setFailOnLoad(false);
}
@FunctionalInterface

View File

@ -737,18 +737,15 @@ public abstract class AbstractSubmit extends AbstractDaemonTest {
public void submitWithValidation() throws Exception {
AtomicBoolean called = new AtomicBoolean(false);
this.addOnSubmitValidationListener(
new OnSubmitValidationListener() {
@Override
public void preBranchUpdate(Arguments args) throws ValidationException {
called.set(true);
HashSet<String> refs = Sets.newHashSet(args.getCommands().keySet());
assertThat(refs).contains("refs/heads/master");
refs.remove("refs/heads/master");
if (!refs.isEmpty()) {
// Some submit strategies need to insert new patchset.
assertThat(refs).hasSize(1);
assertThat(refs.iterator().next()).startsWith(RefNames.REFS_CHANGES);
}
args -> {
called.set(true);
HashSet<String> refs = Sets.newHashSet(args.getCommands().keySet());
assertThat(refs).contains("refs/heads/master");
refs.remove("refs/heads/master");
if (!refs.isEmpty()) {
// Some submit strategies need to insert new patchset.
assertThat(refs).hasSize(1);
assertThat(refs.iterator().next()).startsWith(RefNames.REFS_CHANGES);
}
});
@ -791,24 +788,21 @@ public abstract class AbstractSubmit extends AbstractDaemonTest {
// succeed.
List<String> projectsCalled = new ArrayList<>(4);
this.addOnSubmitValidationListener(
new OnSubmitValidationListener() {
@Override
public void preBranchUpdate(Arguments args) throws ValidationException {
String master = "refs/heads/master";
assertThat(args.getCommands()).containsKey(master);
ReceiveCommand cmd = args.getCommands().get(master);
ObjectId newMasterId = cmd.getNewId();
try (Repository repo = repoManager.openRepository(args.getProject())) {
assertThat(repo.exactRef(master).getObjectId()).isEqualTo(cmd.getOldId());
assertThat(args.getRef(master)).hasValue(newMasterId);
args.getRevWalk().parseBody(args.getRevWalk().parseCommit(newMasterId));
} catch (IOException e) {
throw new AssertionError("failed checking new ref value", e);
}
projectsCalled.add(args.getProject().get());
if (projectsCalled.size() == 2) {
throw new ValidationException("time to fail");
}
args -> {
String master = "refs/heads/master";
assertThat(args.getCommands()).containsKey(master);
ReceiveCommand cmd = args.getCommands().get(master);
ObjectId newMasterId = cmd.getNewId();
try (Repository repo = repoManager.openRepository(args.getProject())) {
assertThat(repo.exactRef(master).getObjectId()).isEqualTo(cmd.getOldId());
assertThat(args.getRef(master)).hasValue(newMasterId);
args.getRevWalk().parseBody(args.getRevWalk().parseCommit(newMasterId));
} catch (IOException e) {
throw new AssertionError("failed checking new ref value", e);
}
projectsCalled.add(args.getProject().get());
if (projectsCalled.size() == 2) {
throw new ValidationException("time to fail");
}
});
submitWithConflict(change4.getChangeId(), "time to fail");

View File

@ -30,7 +30,6 @@ import com.google.gerrit.extensions.client.SubmitType;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.extensions.registration.RegistrationHandle;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.server.git.ChangeMessageModifier;
import com.google.gerrit.server.submit.CommitMergeStatus;
import com.google.inject.Inject;
@ -91,16 +90,8 @@ public class SubmitByCherryPickIT extends AbstractSubmit {
RegistrationHandle handle =
changeMessageModifiers.add(
"gerrit",
new ChangeMessageModifier() {
@Override
public String onSubmit(
String newCommitMessage,
RevCommit original,
RevCommit mergeTip,
Branch.NameKey destination) {
return newCommitMessage + "Custom: " + destination.get();
}
});
(newCommitMessage, original, mergeTip, destination) ->
newCommitMessage + "Custom: " + destination.get());
try {
submit(change.getChangeId());
} finally {

View File

@ -25,7 +25,6 @@ import com.google.gerrit.extensions.client.SubmitType;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.extensions.registration.RegistrationHandle;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.server.git.ChangeMessageModifier;
import com.google.inject.Inject;
import java.util.List;
@ -88,19 +87,12 @@ public class SubmitByRebaseAlwaysIT extends AbstractSubmitByRebase {
RegistrationHandle handle =
changeMessageModifiers.add(
"gerrit",
new ChangeMessageModifier() {
@Override
public String onSubmit(
String newCommitMessage,
RevCommit original,
RevCommit mergeTip,
Branch.NameKey destination) {
List<String> custom = mergeTip.getFooterLines("Custom");
if (!custom.isEmpty()) {
newCommitMessage += "Custom-Parent: " + custom.get(0) + "\n";
}
return newCommitMessage + "Custom: " + destination.get();
(newCommitMessage, original, mergeTip, destination) -> {
List<String> custom = mergeTip.getFooterLines("Custom");
if (!custom.isEmpty()) {
newCommitMessage += "Custom-Parent: " + custom.get(0) + "\n";
}
return newCommitMessage + "Custom: " + destination.get();
});
try {
// change1 is a fast-forward, but should be rebased in cherry pick style

View File

@ -90,14 +90,8 @@ public class AccessIT extends AbstractDaemonTest {
RegistrationHandle handle =
fileHistoryWebLinkDynamicSet.add(
"gerrit",
new FileHistoryWebLink() {
@Override
public WebLinkInfo getFileHistoryWebLink(
String projectName, String revision, String fileName) {
return new WebLinkInfo(
"name", "imageURL", "http://view/" + projectName + "/" + fileName);
}
});
(projectName, revision, fileName) ->
new WebLinkInfo("name", "imageURL", "http://view/" + projectName + "/" + fileName));
try {
ProjectAccessInfo info = pApi().access();
assertThat(info.configWebLinks).hasSize(1);
@ -113,14 +107,8 @@ public class AccessIT extends AbstractDaemonTest {
RegistrationHandle handle =
fileHistoryWebLinkDynamicSet.add(
"gerrit",
new FileHistoryWebLink() {
@Override
public WebLinkInfo getFileHistoryWebLink(
String projectName, String revision, String fileName) {
return new WebLinkInfo(
"name", "imageURL", "http://view/" + projectName + "/" + fileName);
}
});
(projectName, revision, fileName) ->
new WebLinkInfo("name", "imageURL", "http://view/" + projectName + "/" + fileName));
try (Repository repo = repoManager.openRepository(newProjectName)) {
RefUpdate u = repo.updateRef(RefNames.REFS_CONFIG);
u.setForceUpdate(true);

View File

@ -74,15 +74,7 @@ public class CommentAddedEventIT extends AbstractDaemonTest {
u.save();
}
eventListenerRegistration =
source.add(
"gerrit",
new CommentAddedListener() {
@Override
public void onCommentAdded(Event event) {
lastCommentAddedEvent = event;
}
});
eventListenerRegistration = source.add("gerrit", event -> lastCommentAddedEvent = event);
}
@After

View File

@ -80,15 +80,7 @@ public class CustomLabelIT extends AbstractDaemonTest {
u.save();
}
eventListenerRegistration =
source.add(
"gerrit",
new CommentAddedListener() {
@Override
public void onCommentAdded(Event event) {
lastCommentAddedEvent = event;
}
});
eventListenerRegistration = source.add("gerrit", event -> lastCommentAddedEvent = event);
}
@After

View File

@ -33,7 +33,6 @@ import com.google.gerrit.extensions.common.GpgKeyInfo.Status;
import com.google.gerrit.gpg.testing.TestKey;
import com.google.gerrit.lifecycle.LifecycleManager;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.ServerInitiated;
import com.google.gerrit.server.account.AccountManager;
@ -41,7 +40,6 @@ import com.google.gerrit.server.account.AccountsUpdate;
import com.google.gerrit.server.account.AuthRequest;
import com.google.gerrit.server.account.externalids.ExternalId;
import com.google.gerrit.server.schema.SchemaCreator;
import com.google.gerrit.server.util.RequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.gerrit.testing.GerritBaseTests;
import com.google.gerrit.testing.InMemoryModule;
@ -111,13 +109,7 @@ public class GerritPublicKeyCheckerTest extends GerritBaseTests {
.update("Set Preferred Email", userId, u -> u.setPreferredEmail("user@example.com"));
user = reloadUser();
requestContext.setContext(
new RequestContext() {
@Override
public CurrentUser getUser() {
return user;
}
});
requestContext.setContext(() -> user);
storeRepo = new InMemoryRepository(new DfsRepositoryDescription("repo"));
store = new PublicKeyStore(storeRepo);

View File

@ -22,7 +22,6 @@ import static org.junit.Assert.assertNotNull;
import com.google.gerrit.pgm.init.api.ConsoleUI;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.testing.GerritBaseTests;
import com.google.inject.Provider;
import java.nio.file.Paths;
import java.util.Collections;
import org.junit.Test;
@ -38,14 +37,7 @@ public class LibrariesTest extends GerritBaseTests {
Libraries lib =
new Libraries(
new Provider<LibraryDownloader>() {
@Override
public LibraryDownloader get() {
return new LibraryDownloader(ui, site, remover);
}
},
Collections.emptyList(),
false);
() -> new LibraryDownloader(ui, site, remover), Collections.emptyList(), false);
assertNotNull(lib.mysqlDriver);

View File

@ -39,7 +39,6 @@ import com.google.gerrit.server.plugincontext.PluginContext.PluginMetrics;
import com.google.gerrit.server.plugincontext.PluginSetContext;
import com.google.gerrit.testing.GerritBaseTests;
import java.util.Set;
import org.easymock.IAnswer;
import org.eclipse.jgit.lib.Config;
import org.junit.Before;
import org.junit.Test;
@ -113,16 +112,13 @@ public class UniversalGroupBackendTest extends GerritBaseTests {
expect(backend.handles(not(eq(handled)))).andStubReturn(false);
expect(backend.membershipsOf(anyObject(IdentifiedUser.class)))
.andStubAnswer(
new IAnswer<GroupMembership>() {
@Override
public GroupMembership answer() throws Throwable {
Object[] args = getCurrentArguments();
GroupMembership membership = createMock(GroupMembership.class);
expect(membership.contains(eq(handled))).andStubReturn(args[0] == member);
expect(membership.contains(not(eq(notHandled)))).andStubReturn(false);
replay(membership);
return membership;
}
() -> {
Object[] args = getCurrentArguments();
GroupMembership membership = createMock(GroupMembership.class);
expect(membership.contains(eq(handled))).andStubReturn(args[0] == member);
expect(membership.contains(not(eq(notHandled)))).andStubReturn(false);
replay(membership);
return membership;
});
replay(member, notMember, backend);

View File

@ -32,7 +32,6 @@ import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.LabelId;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.AccountManager;
import com.google.gerrit.server.account.AuthRequest;
@ -44,7 +43,6 @@ import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectConfig;
import com.google.gerrit.server.schema.SchemaCreator;
import com.google.gerrit.server.util.RequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.gerrit.server.util.time.TimeUtil;
import com.google.gerrit.testing.GerritBaseTests;
@ -91,13 +89,7 @@ public class LabelNormalizerTest extends GerritBaseTests {
userId = accountManager.authenticate(AuthRequest.forUser("user")).getAccountId();
user = userFactory.create(userId);
requestContext.setContext(
new RequestContext() {
@Override
public CurrentUser getUser() {
return user;
}
});
requestContext.setContext(() -> user);
configureProject();
setUpChange();

View File

@ -59,12 +59,6 @@ public class EventDeserializerTest extends GerritBaseTests {
}
private <T> Supplier<T> createSupplier(T value) {
return Suppliers.memoize(
new Supplier<T>() {
@Override
public T get() {
return value;
}
});
return Suppliers.memoize(() -> value);
}
}

View File

@ -63,7 +63,6 @@ import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.project.RefPattern;
import com.google.gerrit.server.project.testing.Util;
import com.google.gerrit.server.schema.SchemaCreator;
import com.google.gerrit.server.util.RequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.gerrit.testing.GerritBaseTests;
import com.google.gerrit.testing.InMemoryModule;
@ -300,13 +299,7 @@ public class RefControlTest extends GerritBaseTests {
add(local);
local.getProject().setParentName(parentKey);
requestContext.setContext(
new RequestContext() {
@Override
public CurrentUser getUser() {
return null;
}
});
requestContext.setContext(() -> null);
changeControlFactory = injector.getInstance(ChangeControl.Factory.class);
}

View File

@ -169,22 +169,11 @@ public abstract class AbstractQueryAccountsTest extends GerritServerTests {
protected RequestContext newRequestContext(Account.Id requestUserId) {
final CurrentUser requestUser = userFactory.create(requestUserId);
return new RequestContext() {
@Override
public CurrentUser getUser() {
return requestUser;
}
};
return () -> requestUser;
}
protected void setAnonymous() {
requestContext.setContext(
new RequestContext() {
@Override
public CurrentUser getUser() {
return anonymousUser.get();
}
});
requestContext.setContext(anonymousUser::get);
}
@After

View File

@ -229,12 +229,7 @@ public abstract class AbstractQueryChangesTest extends GerritServerTests {
protected RequestContext newRequestContext(Account.Id requestUserId) {
final CurrentUser requestUser = userFactory.create(requestUserId);
return new RequestContext() {
@Override
public CurrentUser getUser() {
return requestUser;
}
};
return () -> requestUser;
}
protected void resetUser() {

View File

@ -139,22 +139,11 @@ public abstract class AbstractQueryGroupsTest extends GerritServerTests {
protected RequestContext newRequestContext(Account.Id requestUserId) {
final CurrentUser requestUser = userFactory.create(requestUserId);
return new RequestContext() {
@Override
public CurrentUser getUser() {
return requestUser;
}
};
return () -> requestUser;
}
protected void setAnonymous() {
requestContext.setContext(
new RequestContext() {
@Override
public CurrentUser getUser() {
return anonymousUser.get();
}
});
requestContext.setContext(anonymousUser::get);
}
@After

View File

@ -129,22 +129,11 @@ public abstract class AbstractQueryProjectsTest extends GerritServerTests {
protected RequestContext newRequestContext(Account.Id requestUserId) {
final CurrentUser requestUser = userFactory.create(requestUserId);
return new RequestContext() {
@Override
public CurrentUser getUser() {
return requestUser;
}
};
return () -> requestUser;
}
protected void setAnonymous() {
requestContext.setContext(
new RequestContext() {
@Override
public CurrentUser getUser() {
return anonymousUser.get();
}
});
requestContext.setContext(anonymousUser::get);
}
@After

@ -1 +1 @@
Subproject commit 25ac76fe18537c33f9f27c5463a081449c13ba67
Subproject commit 9d0ad9ae5667b7da5bb3e7e8066d2dbff446d70b

@ -1 +1 @@
Subproject commit 8eb376d306bf907fb6317641a53e43e5257c7dc5
Subproject commit 4fad0c870d80daf274d6aa542a2be554cf4a1044

@ -1 +1 @@
Subproject commit d584a963102850c5291d91d1430f4d96bd7f84aa
Subproject commit 48703a1cf5dce6af87f700ccda2c6f5949a6fa1c