Convert some Functions/Predicates to streams & lambdas

The conversion is somewhat conservative; there are many places where
we use things like Lists.transform and FluentIterable where we could
in theory switch entirely to streams, but the win is not obvious.
Converting Functions to lambdas is pretty much always a win, though.

Change-Id: I771b13bddb768426c8bb2dbf81207664994ee21d
This commit is contained in:
Dave Borowitz
2016-09-20 10:11:30 -04:00
parent e128d6f413
commit b5a07489f3
35 changed files with 194 additions and 471 deletions

View File

@@ -161,17 +161,10 @@ public class Field<T> {
private static <T> Function<T, String> initFormatter(Class<T> keyType) {
if (keyType == String.class) {
return (Function<T, String>) Functions.<String> identity();
} else if (keyType == Integer.class || keyType == Boolean.class) {
return (Function<T, String>) Functions.toStringFunction();
} else if (Enum.class.isAssignableFrom(keyType)) {
return new Function<T, String>() {
@Override
public String apply(T in) {
return ((Enum<?>) in).name();
}
};
return in -> ((Enum<?>) in).name();
}
throw new IllegalStateException("unsupported type " + keyType.getName());
}

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.metrics.dropwizard;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gerrit.metrics.Description;
@@ -124,14 +123,7 @@ abstract class BucketedCallback<V> implements BucketedMetric {
@Override
public Map<Object, Metric> getCells() {
return Maps.transformValues(
cells,
new Function<ValueGauge, Metric> () {
@Override
public Metric apply(ValueGauge in) {
return in;
}
});
return Maps.transformValues(cells, in -> (Metric) in);
}
final class ValueGauge implements Gauge<V> {

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.metrics.dropwizard;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gerrit.metrics.Description;
@@ -98,13 +97,6 @@ abstract class BucketedCounter implements BucketedMetric {
@Override
public Map<Object, Metric> getCells() {
return Maps.transformValues(
cells,
new Function<CounterImpl, Metric> () {
@Override
public Metric apply(CounterImpl in) {
return in.metric;
}
});
return Maps.transformValues(cells, c -> c.metric);
}
}

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.metrics.dropwizard;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gerrit.metrics.Description;
@@ -96,13 +95,6 @@ abstract class BucketedHistogram implements BucketedMetric {
@Override
public Map<Object, Metric> getCells() {
return Maps.transformValues(
cells,
new Function<HistogramImpl, Metric> () {
@Override
public Metric apply(HistogramImpl in) {
return in.metric;
}
});
return Maps.transformValues(cells, h -> h.metric);
}
}

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.metrics.dropwizard;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.gerrit.metrics.Description;
@@ -96,13 +95,6 @@ abstract class BucketedTimer implements BucketedMetric {
@Override
public Map<Object, Metric> getCells() {
return Maps.transformValues(
cells,
new Function<TimerImpl, Metric> () {
@Override
public Metric apply(TimerImpl in) {
return in.metric;
}
});
return Maps.transformValues(cells, t -> t.metric);
}
}

View File

@@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.gerrit.metrics.dropwizard.MetricResource.METRIC_KIND;
import static com.google.gerrit.server.config.ConfigResource.CONFIG_KIND;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@@ -304,14 +303,8 @@ public class DropWizardMetricMaker extends MetricMaker {
@Override
public synchronized RegistrationHandle newTrigger(
Set<CallbackMetric<?>> metrics, Runnable trigger) {
final ImmutableSet<CallbackMetricGlue> all = FluentIterable.from(metrics)
.transform(
new Function<CallbackMetric<?>, CallbackMetricGlue>() {
@Override
public CallbackMetricGlue apply(CallbackMetric<?> input) {
return (CallbackMetricGlue) input;
}
})
ImmutableSet<CallbackMetricGlue> all = FluentIterable.from(metrics)
.transform(m -> (CallbackMetricGlue) m)
.toSet();
trigger = new CallbackGroup(trigger, all);

View File

@@ -16,9 +16,9 @@ package com.google.gerrit.server;
import static com.google.gerrit.server.notedb.ReviewerStateInternal.CC;
import static com.google.gerrit.server.notedb.ReviewerStateInternal.REVIEWER;
import static java.util.Comparator.comparing;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
@@ -52,7 +52,6 @@ import com.google.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -81,14 +80,7 @@ public class ApprovalsUtil {
LoggerFactory.getLogger(ApprovalsUtil.class);
private static final Ordering<PatchSetApproval> SORT_APPROVALS =
Ordering.natural()
.onResultOf(
new Function<PatchSetApproval, Timestamp>() {
@Override
public Timestamp apply(PatchSetApproval a) {
return a.getGranted();
}
});
Ordering.from(comparing(PatchSetApproval::getGranted));
public static List<PatchSetApproval> sortApprovals(
Iterable<PatchSetApproval> approvals) {

View File

@@ -14,8 +14,8 @@
package com.google.gerrit.server.account;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import static java.util.stream.Collectors.toSet;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountExternalId;
import com.google.gerrit.reviewdb.server.ReviewDb;
@@ -191,14 +191,9 @@ public class AccountResolver {
// At this point we have no clue. Just perform a whole bunch of suggestions
// and pray we come up with a reasonable result list.
return FluentIterable
.from(accountQueryProvider.get().byDefault(nameOrEmail))
.transform(new Function<AccountState, Account.Id>() {
@Override
public Account.Id apply(AccountState accountState) {
return accountState.getAccount().getId();
}
}).toSet();
return accountQueryProvider.get().byDefault(nameOrEmail).stream()
.map(a -> a.getAccount().getId())
.collect(toSet());
}
List<Account> m = db.accounts().byFullName(nameOrEmail).toList();

View File

@@ -36,12 +36,7 @@ import java.util.Set;
public class AccountState {
public static final Function<AccountState, Account.Id> ACCOUNT_ID_FUNCTION =
new Function<AccountState, Account.Id>() {
@Override
public Account.Id apply(AccountState in) {
return in.getAccount().getId();
}
};
a -> a.getAccount().getId();
private final Account account;
private final Set<AccountGroup.UUID> internalGroups;

View File

@@ -14,15 +14,14 @@
package com.google.gerrit.server.account;
import com.google.common.base.Function;
import static com.google.common.base.Predicates.not;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.FluentIterable;
import com.google.gerrit.common.data.GlobalCapability;
import com.google.gerrit.common.data.PermissionRange;
import com.google.gerrit.common.data.PermissionRule;
import com.google.gerrit.common.data.PermissionRule.Action;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.PeerDaemonUser;
import com.google.gerrit.server.git.QueueProvider;
@@ -32,6 +31,7 @@ import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -98,7 +98,7 @@ public class CapabilityControl {
if (canEmailReviewers == null) {
canEmailReviewers =
matchAny(capabilities.emailReviewers, ALLOWED_RULE)
|| !matchAny(capabilities.emailReviewers, Predicates.not(ALLOWED_RULE));
|| !matchAny(capabilities.emailReviewers, not(ALLOWED_RULE));
}
return canEmailReviewers;
@@ -279,23 +279,16 @@ public class CapabilityControl {
return mine;
}
private static final Predicate<PermissionRule> ALLOWED_RULE = new Predicate<PermissionRule>() {
@Override
public boolean apply(PermissionRule rule) {
return rule.getAction() == Action.ALLOW;
}
};
private static final Predicate<PermissionRule> ALLOWED_RULE =
r -> r.getAction() == Action.ALLOW;
private boolean matchAny(Iterable<PermissionRule> rules, Predicate<PermissionRule> predicate) {
Iterable<AccountGroup.UUID> ids = Iterables.transform(
Iterables.filter(rules, predicate),
new Function<PermissionRule, AccountGroup.UUID>() {
@Override
public AccountGroup.UUID apply(PermissionRule rule) {
return rule.getGroup().getUUID();
}
});
return user.getEffectiveGroups().containsAnyOf(ids);
private boolean matchAny(Collection<PermissionRule> rules,
Predicate<PermissionRule> predicate) {
return user.getEffectiveGroups()
.containsAnyOf(
FluentIterable.from(rules)
.filter(predicate)
.transform(r -> r.getGroup().getUUID()));
}
private static boolean match(GroupMembership groups,

View File

@@ -14,8 +14,8 @@
package com.google.gerrit.server.account;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import static java.util.stream.Collectors.toList;
import com.google.gerrit.extensions.client.ProjectWatchInfo;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.Response;
@@ -105,13 +105,10 @@ public class DeleteWatchedProjects
private void deleteFromGit(Account.Id accountId, List<ProjectWatchInfo> input)
throws IOException, ConfigInvalidException {
watchConfig.deleteProjectWatches(accountId, Lists.transform(input,
new Function<ProjectWatchInfo, ProjectWatchKey>() {
@Override
public ProjectWatchKey apply(ProjectWatchInfo info) {
return ProjectWatchKey.create(new Project.NameKey(info.project),
info.filter);
}
}));
watchConfig.deleteProjectWatches(
accountId,
input.stream().map(w -> ProjectWatchKey.create(
new Project.NameKey(w.project), w.filter))
.collect(toList()));
}
}

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.server.account;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.gerrit.extensions.common.SshKeyInfo;
@@ -60,13 +59,9 @@ public class GetSshKeys implements RestReadView<AccountResource> {
public List<SshKeyInfo> apply(IdentifiedUser user)
throws RepositoryNotFoundException, IOException, ConfigInvalidException {
return Lists.transform(authorizedKeys.getKeys(user.getAccountId()),
new Function<AccountSshKey, SshKeyInfo>() {
@Override
public SshKeyInfo apply(AccountSshKey key) {
return newSshKeyInfo(key);
}
});
return Lists.transform(
authorizedKeys.getKeys(user.getAccountId()),
GetSshKeys::newSshKeyInfo);
}
public static SshKeyInfo newSshKeyInfo(AccountSshKey sshKey) {

View File

@@ -14,10 +14,8 @@
package com.google.gerrit.server.account;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import static java.util.stream.Collectors.toList;
import com.google.gerrit.common.data.GroupDescription;
import com.google.gerrit.common.data.GroupDescriptions;
import com.google.gerrit.common.data.GroupReference;
@@ -30,18 +28,11 @@ import com.google.inject.Singleton;
import org.eclipse.jgit.lib.ObjectId;
import java.util.Collection;
import java.util.stream.StreamSupport;
/** Implementation of GroupBackend for the internal group system. */
@Singleton
public class InternalGroupBackend implements GroupBackend {
private static final Function<AccountGroup, GroupReference> ACT_GROUP_TO_GROUP_REF =
new Function<AccountGroup, GroupReference>() {
@Override
public GroupReference apply(AccountGroup group) {
return GroupReference.forGroup(group);
}
};
private final GroupControl.Factory groupControlFactory;
private final GroupCache groupCache;
private final IncludingGroupMembership.Factory groupMembershipFactory;
@@ -77,16 +68,13 @@ public class InternalGroupBackend implements GroupBackend {
@Override
public Collection<GroupReference> suggest(final String name,
final ProjectControl project) {
Iterable<AccountGroup> filtered = Iterables.filter(groupCache.all(),
new Predicate<AccountGroup>() {
@Override
public boolean apply(AccountGroup group) {
return StreamSupport.stream(groupCache.all().spliterator(), false)
.filter(group ->
// startsWithIgnoreCase && isVisible
return group.getName().regionMatches(true, 0, name, 0, name.length())
&& groupControlFactory.controlFor(group).isVisible();
}
});
return Lists.newArrayList(Iterables.transform(filtered, ACT_GROUP_TO_GROUP_REF));
group.getName().regionMatches(true, 0, name, 0, name.length())
&& groupControlFactory.controlFor(group).isVisible())
.map(GroupReference::forGroup)
.collect(toList());
}
@Override

View File

@@ -15,8 +15,8 @@
package com.google.gerrit.server.account;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Comparator.comparing;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
@@ -278,13 +278,7 @@ public class VersionedAuthorizedKeys extends VersionedMetaData {
* @param newKeys the new public SSH keys
*/
public void setKeys(Collection<AccountSshKey> newKeys) {
Ordering<AccountSshKey> o =
Ordering.natural().onResultOf(new Function<AccountSshKey, Integer>() {
@Override
public Integer apply(AccountSshKey sshKey) {
return sshKey.getKey().get();
}
});
Ordering<AccountSshKey> o = Ordering.from(comparing(k -> k.getKey().get()));
keys = new ArrayList<>(Collections.nCopies(o.max(newKeys).getKey().get(),
Optional.<AccountSshKey> absent()));
for (AccountSshKey key : newKeys) {

View File

@@ -14,11 +14,11 @@
package com.google.gerrit.server.config;
import static java.util.stream.Collectors.toList;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gerrit.common.data.ContributorAgreement;
import com.google.gerrit.extensions.common.AuthInfo;
@@ -225,14 +225,8 @@ public class GetServerInfo implements RestReadView<ConfigResource> {
getDownloadSchemeInfo(scheme, downloadCommands, cloneCommands));
}
}
info.archives = Lists.newArrayList(Iterables.transform(
archiveFormats.getAllowed(),
new Function<ArchiveFormat, String>() {
@Override
public String apply(ArchiveFormat in) {
return in.getShortName();
}
}));
info.archives = archiveFormats.getAllowed().stream()
.map(ArchiveFormat::getShortName).collect(toList());
return info;
}

View File

@@ -14,8 +14,8 @@
package com.google.gerrit.server.config;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import static java.util.stream.Collectors.toList;
import com.google.gerrit.extensions.annotations.ExtensionPoint;
import com.google.gerrit.extensions.api.projects.ConfigValue;
import com.google.gerrit.extensions.api.projects.ProjectConfigEntryType;
@@ -137,14 +137,9 @@ public class ProjectConfigEntry {
T defaultValue, Class<T> permittedValues, boolean inheritable,
String description) {
this(displayName, defaultValue.name(), ProjectConfigEntryType.LIST,
Lists.transform(
Arrays.asList(permittedValues.getEnumConstants()),
new Function<Enum<?>, String>() {
@Override
public String apply(Enum<?> e) {
return e.name();
}
}), inheritable, description);
Arrays.stream(permittedValues.getEnumConstants())
.map(Enum::name).collect(toList()),
inheritable, description);
}
public ProjectConfigEntry(String displayName, String defaultValue,

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.server.extensions.events;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.gerrit.extensions.api.changes.NotifyHandling;
import com.google.gerrit.extensions.common.AccountInfo;
@@ -72,18 +71,10 @@ public class ReviewerAdded {
return;
}
List<AccountInfo> transformed = Lists.transform(reviewers,
new Function<Account.Id, AccountInfo>() {
@Override
public AccountInfo apply(Account.Id account) {
return util.accountInfo(account);
}
});
try {
fire(util.changeInfo(change),
util.revisionInfo(change.getProject(), patchSet),
transformed,
Lists.transform(reviewers, util::accountInfo),
util.accountInfo(adder),
when);
} catch (PatchListNotAvailableException | GpgException | IOException

View File

@@ -14,11 +14,8 @@
package com.google.gerrit.server.extensions.webui;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.gerrit.common.Nullable;
import com.google.common.collect.FluentIterable;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.RestCollection;
@@ -33,16 +30,13 @@ import com.google.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
public class UiActions {
private static final Logger log = LoggerFactory.getLogger(UiActions.class);
public static Predicate<UiAction.Description> enabled() {
return new Predicate<UiAction.Description>() {
@Override
public boolean apply(UiAction.Description input) {
return input.isEnabled();
}
};
return UiAction.Description::isEnabled;
}
public static <R extends RestResource> Iterable<UiAction.Description> from(
@@ -56,58 +50,52 @@ public class UiActions {
DynamicMap<RestView<R>> views,
final R resource,
final Provider<CurrentUser> userProvider) {
return Iterables.filter(
Iterables.transform(
views,
new Function<DynamicMap.Entry<RestView<R>>, UiAction.Description> () {
@Override
@Nullable
public UiAction.Description apply(DynamicMap.Entry<RestView<R>> e) {
int d = e.getExportName().indexOf('.');
if (d < 0) {
return null;
}
return FluentIterable.from(views)
.transform((DynamicMap.Entry<RestView<R>> e) -> {
int d = e.getExportName().indexOf('.');
if (d < 0) {
return null;
}
RestView<R> view;
try {
view = e.getProvider().get();
} catch (RuntimeException err) {
log.error(String.format(
"error creating view %s.%s",
e.getPluginName(), e.getExportName()), err);
return null;
}
RestView<R> view;
try {
view = e.getProvider().get();
} catch (RuntimeException err) {
log.error(String.format(
"error creating view %s.%s",
e.getPluginName(), e.getExportName()), err);
return null;
}
if (!(view instanceof UiAction)) {
return null;
}
if (!(view instanceof UiAction)) {
return null;
}
try {
CapabilityUtils.checkRequiresCapability(userProvider,
e.getPluginName(), view.getClass());
} catch (AuthException exc) {
return null;
}
try {
CapabilityUtils.checkRequiresCapability(userProvider,
e.getPluginName(), view.getClass());
} catch (AuthException exc) {
return null;
}
UiAction.Description dsc =
((UiAction<R>) view).getDescription(resource);
if (dsc == null || !dsc.isVisible()) {
return null;
}
UiAction.Description dsc =
((UiAction<R>) view).getDescription(resource);
if (dsc == null || !dsc.isVisible()) {
return null;
}
String name = e.getExportName().substring(d + 1);
PrivateInternals_UiActionDescription.setMethod(
dsc,
e.getExportName().substring(0, d));
PrivateInternals_UiActionDescription.setId(
dsc,
"gerrit".equals(e.getPluginName())
? name
: e.getPluginName() + '~' + name);
return dsc;
}
}),
Predicates.notNull());
String name = e.getExportName().substring(d + 1);
PrivateInternals_UiActionDescription.setMethod(
dsc,
e.getExportName().substring(0, d));
PrivateInternals_UiActionDescription.setId(
dsc,
"gerrit".equals(e.getPluginName())
? name
: e.getPluginName() + '~' + name);
return dsc;
})
.filter(Objects::nonNull);
}
private UiActions() {

View File

@@ -345,54 +345,36 @@ public class ChangeBundle {
private Map<PatchSetApproval.Key, PatchSetApproval>
filterPatchSetApprovals() {
return limitToValidPatchSets(patchSetApprovals,
new Function<PatchSetApproval.Key, PatchSet.Id>() {
@Override
public PatchSet.Id apply(PatchSetApproval.Key in) {
return in.getParentKey();
}
});
return limitToValidPatchSets(
patchSetApprovals, PatchSetApproval.Key::getParentKey);
}
private Map<PatchLineComment.Key, PatchLineComment>
filterPatchLineComments() {
return limitToValidPatchSets(patchLineComments,
new Function<PatchLineComment.Key, PatchSet.Id>() {
@Override
public PatchSet.Id apply(PatchLineComment.Key in) {
return in.getParentKey().getParentKey();
}
});
return limitToValidPatchSets(
patchLineComments,
k -> k.getParentKey().getParentKey());
}
private <K, V> Map<K, V> limitToValidPatchSets(Map<K, V> in,
final Function<K, PatchSet.Id> func) {
Function<K, PatchSet.Id> func) {
return Maps.filterKeys(
in, Predicates.compose(validPatchSetPredicate(), func));
}
private Predicate<PatchSet.Id> validPatchSetPredicate() {
final Predicate<PatchSet.Id> upToCurrent = upToCurrentPredicate();
return new Predicate<PatchSet.Id>() {
@Override
public boolean apply(PatchSet.Id in) {
return upToCurrent.apply(in) && patchSets.containsKey(in);
}
};
Predicate<PatchSet.Id> upToCurrent = upToCurrentPredicate();
return p -> upToCurrent.apply(p) && patchSets.containsKey(p);
}
private Collection<ChangeMessage> filterChangeMessages() {
final Predicate<PatchSet.Id> validPatchSet = validPatchSetPredicate();
return Collections2.filter(changeMessages,
new Predicate<ChangeMessage>() {
@Override
public boolean apply(ChangeMessage in) {
PatchSet.Id psId = in.getPatchSetId();
if (psId == null) {
return true;
}
return validPatchSet.apply(psId);
return Collections2.filter(changeMessages, m -> {
PatchSet.Id psId = m.getPatchSetId();
if (psId == null) {
return true;
}
return validPatchSet.apply(psId);
});
}

View File

@@ -19,9 +19,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.gerrit.reviewdb.client.RefNames.changeMetaRef;
import static com.google.gerrit.server.notedb.NoteDbTable.CHANGES;
import static java.util.Comparator.comparing;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
@@ -70,7 +70,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
@@ -84,22 +83,10 @@ public class ChangeNotes extends AbstractChangeNotes<ChangeNotes> {
private static final Logger log = LoggerFactory.getLogger(ChangeNotes.class);
static final Ordering<PatchSetApproval> PSA_BY_TIME =
Ordering.natural().onResultOf(
new Function<PatchSetApproval, Timestamp>() {
@Override
public Timestamp apply(PatchSetApproval input) {
return input.getGranted();
}
});
Ordering.from(comparing(PatchSetApproval::getGranted));
public static final Ordering<ChangeMessage> MESSAGE_BY_TIME =
Ordering.natural().onResultOf(
new Function<ChangeMessage, Timestamp>() {
@Override
public Timestamp apply(ChangeMessage input) {
return input.getWrittenOn();
}
});
Ordering.from(comparing(ChangeMessage::getWrittenOn));
public static ConfigInvalidException parseException(Change.Id changeId,
String fmt, Object... args) {

View File

@@ -30,11 +30,10 @@ import static com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_TAG;
import static com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_TOPIC;
import static com.google.gerrit.server.notedb.NoteDbTable.CHANGES;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.joining;
import com.google.auto.value.AutoValue;
import com.google.common.base.Enums;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.ArrayListMultimap;
@@ -883,13 +882,8 @@ class ChangeNotesParser {
missing.add(FOOTER_SUBJECT);
}
if (!missing.isEmpty()) {
throw parseException("Missing footers: " + Joiner.on(", ")
.join(Lists.transform(missing, new Function<FooterKey, String>() {
@Override
public String apply(FooterKey input) {
return input.getName();
}
})));
throw parseException("Missing footers: "
+ missing.stream().map(FooterKey::getName).collect(joining(", ")));
}
}

View File

@@ -17,10 +17,9 @@ package com.google.gerrit.server.notedb;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.gerrit.server.PatchLineCommentsUtil.PLC_ORDER;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.toList;
import com.google.common.base.Function;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.gerrit.reviewdb.client.PatchLineComment;
@@ -134,13 +133,10 @@ class RevisionNoteBuilder {
}
RevisionNoteData data = new RevisionNoteData();
data.comments = FluentIterable.from(PLC_ORDER.sortedCopy(comments.values()))
.transform(new Function<PatchLineComment, RevisionNoteData.Comment>() {
@Override
public RevisionNoteData.Comment apply(PatchLineComment plc) {
return new RevisionNoteData.Comment(plc, noteUtil.getServerId());
}
}).toList();
data.comments = comments.values().stream()
.sorted(PLC_ORDER)
.map(plc -> new RevisionNoteData.Comment(plc, noteUtil.getServerId()))
.collect(toList());
data.pushCert = pushCert;
try (OutputStreamWriter osw = new OutputStreamWriter(out)) {

View File

@@ -14,9 +14,9 @@
package com.google.gerrit.server.notedb;
import com.google.common.base.Function;
import static java.util.stream.Collectors.toList;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.Patch;
@@ -134,15 +134,15 @@ class RevisionNoteData {
List<Comment> comments;
ImmutableList<PatchLineComment> exportComments(
final PatchLineComment.Status status) {
PatchLineComment.Status status) {
return ImmutableList.copyOf(
Lists.transform(comments, new Function<Comment, PatchLineComment>() {
@Override
public PatchLineComment apply(Comment c) {
PatchLineComment plc = c.export();
plc.setStatus(status);
return plc;
}
}));
comments.stream()
.map(
c -> {
PatchLineComment plc = c.export();
plc.setStatus(status);
return plc;
})
.collect(toList()));
}
}

View File

@@ -16,12 +16,12 @@
package com.google.gerrit.server.patch;
import static com.google.common.base.Preconditions.checkArgument;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.toSet;
import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace;
import com.google.gerrit.reviewdb.client.Patch;
import com.google.gerrit.reviewdb.client.Project;
@@ -70,6 +70,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;
public class PatchListLoader implements Callable<PatchList> {
static final Logger log = LoggerFactory.getLogger(PatchListLoader.class);
@@ -179,16 +180,11 @@ public class PatchListLoader implements Callable<PatchList> {
key.getNewId(), key.getWhitespace());
PatchListKey oldKey = PatchListKey.againstDefaultBase(
key.getOldId(), key.getWhitespace());
paths = FluentIterable
.from(patchListCache.get(newKey, project).getPatches())
.append(patchListCache.get(oldKey, project).getPatches())
.transform(new Function<PatchListEntry, String>() {
@Override
public String apply(PatchListEntry entry) {
return entry.getNewName();
}
})
.toSet();
paths = Stream.concat(
patchListCache.get(newKey, project).getPatches().stream(),
patchListCache.get(oldKey, project).getPatches().stream())
.map(PatchListEntry::getNewName)
.collect(toSet());
}
int cnt = diffEntries.size();

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.server.project;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.gerrit.common.errors.PermissionDeniedException;
import com.google.gerrit.extensions.restapi.AuthException;
@@ -91,14 +90,7 @@ public class BanCommit implements RestModifyView<ProjectResource, Input> {
if (commits == null || commits.isEmpty()) {
return null;
}
return Lists.transform(commits,
new Function<ObjectId, String>() {
@Override
public String apply(ObjectId id) {
return id.getName();
}
});
return Lists.transform(commits, ObjectId::getName);
}
public static class BanResultInfo {

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.server.project;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.gerrit.extensions.common.GitPerson;
import com.google.gerrit.extensions.restapi.AuthException;
@@ -102,12 +101,7 @@ public class GetReflog implements RestReadView<BranchResource> {
}
}
}
return Lists.transform(entries, new Function<ReflogEntry, ReflogEntryInfo>() {
@Override
public ReflogEntryInfo apply(ReflogEntry e) {
return new ReflogEntryInfo(e);
}
});
return Lists.transform(entries, ReflogEntryInfo::new);
}
}

View File

@@ -17,7 +17,6 @@ package com.google.gerrit.server.project;
import static com.google.gerrit.common.data.PermissionRule.Action.ALLOW;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
@@ -72,6 +71,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
/** Cached information on a project. */
public class ProjectState {
@@ -378,75 +378,35 @@ public class ProjectState {
}
public boolean isUseContributorAgreements() {
return getInheritableBoolean(new Function<Project, InheritableBoolean>() {
@Override
public InheritableBoolean apply(Project input) {
return input.getUseContributorAgreements();
}
});
return getInheritableBoolean(Project::getUseContributorAgreements);
}
public boolean isUseContentMerge() {
return getInheritableBoolean(new Function<Project, InheritableBoolean>() {
@Override
public InheritableBoolean apply(Project input) {
return input.getUseContentMerge();
}
});
return getInheritableBoolean(Project::getUseContentMerge);
}
public boolean isUseSignedOffBy() {
return getInheritableBoolean(new Function<Project, InheritableBoolean>() {
@Override
public InheritableBoolean apply(Project input) {
return input.getUseSignedOffBy();
}
});
return getInheritableBoolean(Project::getUseSignedOffBy);
}
public boolean isRequireChangeID() {
return getInheritableBoolean(new Function<Project, InheritableBoolean>() {
@Override
public InheritableBoolean apply(Project input) {
return input.getRequireChangeID();
}
});
return getInheritableBoolean(Project::getRequireChangeID);
}
public boolean isCreateNewChangeForAllNotInTarget() {
return getInheritableBoolean(new Function<Project, InheritableBoolean>() {
@Override
public InheritableBoolean apply(Project input) {
return input.getCreateNewChangeForAllNotInTarget();
}
});
return getInheritableBoolean(Project::getCreateNewChangeForAllNotInTarget);
}
public boolean isEnableSignedPush() {
return getInheritableBoolean(new Function<Project, InheritableBoolean>() {
@Override
public InheritableBoolean apply(Project input) {
return input.getEnableSignedPush();
}
});
return getInheritableBoolean(Project::getEnableSignedPush);
}
public boolean isRequireSignedPush() {
return getInheritableBoolean(new Function<Project, InheritableBoolean>() {
@Override
public InheritableBoolean apply(Project input) {
return input.getRequireSignedPush();
}
});
return getInheritableBoolean(Project::getRequireSignedPush);
}
public boolean isRejectImplicitMerges() {
return getInheritableBoolean(new Function<Project, InheritableBoolean>() {
@Override
public InheritableBoolean apply(Project input) {
return input.getRejectImplicitMerges();
}
});
return getInheritableBoolean(Project::getRejectImplicitMerges);
}
public LabelTypes getLabelTypes() {
@@ -551,7 +511,8 @@ public class ProjectState {
return Files.exists(p) ? new String(Files.readAllBytes(p), UTF_8) : null;
}
private boolean getInheritableBoolean(Function<Project, InheritableBoolean> func) {
private boolean getInheritableBoolean(
Function<Project, InheritableBoolean> func) {
for (ProjectState s : tree()) {
switch (func.apply(s.getProject())) {
case TRUE:

View File

@@ -16,7 +16,6 @@ package com.google.gerrit.server.query;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
@@ -157,12 +156,7 @@ public class AndSource<T> extends AndPredicate<T>
private Iterable<T> buffer(ResultSet<T> scanner) {
return FluentIterable.from(Iterables.partition(scanner, 50))
.transformAndConcat(new Function<List<T>, List<T>>() {
@Override
public List<T> apply(List<T> buffer) {
return transformBuffer(buffer);
}
});
.transformAndConcat(this::transformBuffer);
}
protected List<T> transformBuffer(List<T> buffer) throws OrmRuntimeException {

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.server.query.account;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
@@ -124,13 +123,9 @@ public class AccountQueryBuilder extends QueryBuilder<AccountState> {
public Predicate<AccountState> defaultQuery(String query) {
return Predicate.and(
Lists.transform(Splitter.on(' ').omitEmptyStrings().splitToList(query),
new Function<String, Predicate<AccountState>>() {
@Override
public Predicate<AccountState> apply(String s) {
return defaultField(s);
}
}));
Lists.transform(
Splitter.on(' ').omitEmptyStrings().splitToList(query),
this::defaultField));
}
@Override

View File

@@ -16,9 +16,9 @@ package com.google.gerrit.server.query.change;
import static com.google.gerrit.reviewdb.client.Change.CHANGE_ID_PATTERN;
import static com.google.gerrit.server.query.change.ChangeData.asChanges;
import static java.util.stream.Collectors.toSet;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
@@ -26,7 +26,6 @@ import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.common.errors.NotSignedInException;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGroup;
@@ -632,14 +631,9 @@ public class ChangeQueryBuilder extends QueryBuilder<ChangeData> {
// expand a group predicate into multiple user predicates
if (group != null) {
Set<Account.Id> allMembers =
new HashSet<>(Lists.transform(
args.listMembers.get().setRecursive(true).apply(group),
new Function<AccountInfo, Account.Id>() {
@Override
public Account.Id apply(AccountInfo accountInfo) {
return new Account.Id(accountInfo._accountId);
}
}));
args.listMembers.get().setRecursive(true).apply(group).stream()
.map(a -> new Account.Id(a._accountId))
.collect(toSet());
int maxLimit = args.indexConfig.maxLimit();
if (allMembers.size() > maxLimit) {
// limit the number of query terms otherwise Gerrit will barf

View File

@@ -22,7 +22,6 @@ import static com.google.gerrit.server.query.Predicate.or;
import static com.google.gerrit.server.query.change.ChangeStatusPredicate.open;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
@@ -191,20 +190,14 @@ public class InternalChangeQuery extends InternalQuery<ChangeData> {
}
}
return Lists.transform(notesFactory.create(db, branch.getParentKey(),
changeIds, new com.google.common.base.Predicate<ChangeNotes>() {
@Override
public boolean apply(ChangeNotes notes) {
Change c = notes.getChange();
List<ChangeNotes> notes = notesFactory.create(
db, branch.getParentKey(), changeIds,
cn -> {
Change c = cn.getChange();
return c.getDest().equals(branch)
&& c.getStatus() != Change.Status.MERGED;
}
}), new Function<ChangeNotes, ChangeData>() {
@Override
public ChangeData apply(ChangeNotes notes) {
return changeDataFactory.create(db, notes);
}
});
return Lists.transform(notes, n -> changeDataFactory.create(db, n));
}
private Iterable<ChangeData> byCommitsOnBranchNotMergedFromIndex(

View File

@@ -15,9 +15,8 @@
package com.google.gerrit.server.schema;
import static com.google.gerrit.server.git.ProjectConfig.ACCESS;
import static java.util.stream.Collectors.toList;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.gerrit.common.data.PermissionRule;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.git.MetaDataUpdate;
@@ -67,18 +66,16 @@ public class ProjectConfigSchemaUpdate extends VersionedMetaData {
Set<String> names = config.getNames(ACCESS, subsection);
if (names.contains(name)) {
List<String> values =
Arrays.asList(config.getStringList(ACCESS, subsection, name));
values = Lists.transform(values, new Function<String, String>() {
@Override
public String apply(String ruleString) {
PermissionRule rule = PermissionRule.fromString(ruleString, false);
if (rule.getForce()) {
rule.setForce(false);
updated = true;
}
return rule.asString(false);
}
});
Arrays.stream(config.getStringList(ACCESS, subsection, name))
.map(r -> {
PermissionRule rule = PermissionRule.fromString(r, false);
if (rule.getForce()) {
rule.setForce(false);
updated = true;
}
return rule.asString(false);
})
.collect(toList());
config.setStringList(ACCESS, subsection, name, values);
}
}

View File

@@ -14,7 +14,8 @@
package com.google.gerrit.server.schema;
import com.google.common.base.Function;
import static java.util.Comparator.comparing;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
@@ -124,13 +125,7 @@ public class Schema_124 extends SchemaVersion {
private Collection<AccountSshKey> fixInvalidSequenceNumbers(
Collection<AccountSshKey> keys) {
Ordering<AccountSshKey> o =
Ordering.natural().onResultOf(new Function<AccountSshKey, Integer>() {
@Override
public Integer apply(AccountSshKey sshKey) {
return sshKey.getKey().get();
}
});
Ordering<AccountSshKey> o = Ordering.from(comparing(k -> k.getKey().get()));
List<AccountSshKey> fixedKeys = new ArrayList<>(keys);
AccountSshKey minKey = o.min(keys);
while (minKey.getKey().get() <= 0) {

View File

@@ -24,7 +24,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
@@ -34,7 +33,6 @@ import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.common.data.SubmitRecord;
import com.google.gerrit.reviewdb.client.Account;
@@ -47,6 +45,7 @@ import com.google.gerrit.reviewdb.client.PatchLineComment.Status;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.reviewdb.client.RevId;
import com.google.gerrit.reviewdb.server.ReviewDbUtil;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.ReviewerSet;
import com.google.gerrit.server.config.GerritServerId;
@@ -381,13 +380,9 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
update.commit();
ChangeNotes notes = newNotes(c);
List<PatchSetApproval> approvals = Ordering.natural().onResultOf(
new Function<PatchSetApproval, Integer>() {
@Override
public Integer apply(PatchSetApproval in) {
return in.getAccountId().get();
}
}).sortedCopy(notes.getApprovals().get(c.currentPatchSetId()));
List<PatchSetApproval> approvals = ReviewDbUtil.intKeyOrdering()
.onResultOf(PatchSetApproval::getAccountId)
.sortedCopy(notes.getApprovals().get(c.currentPatchSetId()));
assertThat(approvals).hasSize(2);
assertThat(approvals.get(0).getAccountId())

View File

@@ -17,7 +17,6 @@ package com.google.gerrit.server.query.account;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.extensions.api.GerritApi;
@@ -476,22 +475,10 @@ public abstract class AbstractQueryAccountsTest extends GerritServerTests {
}
protected static Iterable<Integer> ids(AccountInfo... accounts) {
return FluentIterable.from(Arrays.asList(accounts)).transform(
new Function<AccountInfo, Integer>() {
@Override
public Integer apply(AccountInfo in) {
return in._accountId;
}
});
return FluentIterable.of(accounts).transform(a -> a._accountId);
}
protected static Iterable<Integer> ids(Iterable<AccountInfo> accounts) {
return FluentIterable.from(accounts).transform(
new Function<AccountInfo, Integer>() {
@Override
public Integer apply(AccountInfo in) {
return in._accountId;
}
});
return FluentIterable.from(accounts).transform(a -> a._accountId);
}
}