Use some Java 8 features

These suggestions were produced by a refactoring tool that we have;
the particular decisions it made were based on heuristics over which I
have no control. Some suggestions were edited for brevity, and to omit
references to unreleased Guava features.

Change-Id: I9deac0afd6eda8fdc5a369816a4ee2bbe16924ba
This commit is contained in:
Dave Borowitz 2016-09-20 07:44:23 -04:00
parent 4c93a559b6
commit e45363dcbd
14 changed files with 109 additions and 220 deletions

View File

@ -504,8 +504,7 @@ public class CommentsIT extends AbstractDaemonTest {
assertThat(ps2List.get(2).message).isEqualTo("join lines");
assertThat(ps2List.get(3).message).isEqualTo("typo: content");
ImmutableList<Message> messages =
email.getMessages(r2.getChangeId(), "comment");
List<Message> messages = email.getMessages(r2.getChangeId(), "comment");
assertThat(messages).hasSize(1);
String url = canonicalWebUrl.get();
int c = r1.getChange().getId().get();

View File

@ -119,19 +119,8 @@ class H2CacheFactory implements PersistentCacheFactory, LifecycleListener {
public void start() {
if (executor != null) {
for (final H2CacheImpl<?, ?> cache : caches) {
executor.execute(new Runnable() {
@Override
public void run() {
cache.start();
}
});
cleanup.schedule(new Runnable() {
@Override
public void run() {
cache.prune(cleanup);
}
}, 30, TimeUnit.SECONDS);
executor.execute(cache::start);
cleanup.schedule(() -> cache.prune(cleanup), 30, TimeUnit.SECONDS);
}
}
}

View File

@ -144,24 +144,14 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
final ValueHolder<V> h = new ValueHolder<>(val);
h.created = TimeUtil.nowMs();
mem.put(key, h);
executor.execute(new Runnable() {
@Override
public void run() {
store.put(key, h);
}
});
executor.execute(() -> store.put(key, h));
}
@SuppressWarnings("unchecked")
@Override
public void invalidate(final Object key) {
if (keyType.getRawType().isInstance(key) && store.mightContain((K) key)) {
executor.execute(new Runnable() {
@Override
public void run() {
store.invalidate((K) key);
}
});
executor.execute(() -> store.invalidate((K) key));
}
mem.invalidate(key);
}
@ -212,12 +202,7 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
cal.add(Calendar.DAY_OF_MONTH, 1);
long delay = cal.getTimeInMillis() - TimeUtil.nowMs();
service.schedule(new Runnable() {
@Override
public void run() {
prune(service);
}
}, delay, TimeUnit.MILLISECONDS);
service.schedule(() -> prune(service), delay, TimeUnit.MILLISECONDS);
}
static class ValueHolder<V> {
@ -252,12 +237,7 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
final ValueHolder<V> h = new ValueHolder<>(loader.load(key));
h.created = TimeUtil.nowMs();
executor.execute(new Runnable() {
@Override
public void run() {
store.put(key, h);
}
});
executor.execute(() -> store.put(key, h));
return h;
}
}
@ -282,12 +262,7 @@ public class H2CacheImpl<K, V> extends AbstractLoadingCache<K, V> implements
final ValueHolder<V> h = new ValueHolder<>(loader.call());
h.created = TimeUtil.nowMs();
executor.execute(new Runnable() {
@Override
public void run() {
store.put(key, h);
}
});
executor.execute(() -> store.put(key, h));
return h;
}
}

View File

@ -19,10 +19,8 @@ import static com.google.gerrit.reviewdb.client.AccountExternalId.SCHEME_GPGKEY;
import com.google.common.base.CharMatcher;
import com.google.common.base.MoreObjects;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.io.BaseEncoding;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.reviewdb.client.AccountExternalId;
@ -274,9 +272,7 @@ public class GerritPublicKeyChecker extends PublicKeyChecker {
private static String missingUserIds(Set<String> allowedUserIds) {
StringBuilder sb = new StringBuilder("Key must contain a valid"
+ " certification for one of the following identities:\n");
Iterator<String> sorted = FluentIterable.from(allowedUserIds)
.toSortedList(Ordering.natural())
.iterator();
Iterator<String> sorted = allowedUserIds.stream().sorted().iterator();
while (sorted.hasNext()) {
sb.append(" ").append(sorted.next());
if (sorted.hasNext()) {

View File

@ -19,7 +19,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.io.BaseEncoding;
@ -211,14 +210,8 @@ public class GpgKeys implements
@VisibleForTesting
public static FluentIterable<AccountExternalId> getGpgExtIds(ReviewDb db,
Account.Id accountId) throws OrmException {
return FluentIterable
.from(db.accountExternalIds().byAccount(accountId))
.filter(new Predicate<AccountExternalId>() {
@Override
public boolean apply(AccountExternalId in) {
return in.isScheme(SCHEME_GPGKEY);
}
});
return FluentIterable.from(db.accountExternalIds().byAccount(accountId))
.filter(in -> in.isScheme(SCHEME_GPGKEY));
}
private Iterable<AccountExternalId> getGpgExtIds(AccountResource rsrc)

View File

@ -18,7 +18,6 @@ import static com.google.gerrit.gpg.PublicKeyStore.keyIdToString;
import static com.google.gerrit.gpg.PublicKeyStore.keyToString;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@ -161,13 +160,8 @@ public class PostGpgKeys implements RestModifyView<AccountResource, Input> {
if (!newExtIds.isEmpty()) {
db.get().accountExternalIds().insert(newExtIds);
}
db.get().accountExternalIds().deleteKeys(Iterables.transform(toRemove,
new Function<Fingerprint, AccountExternalId.Key>() {
@Override
public AccountExternalId.Key apply(Fingerprint fp) {
return toExtIdKey(fp.get());
}
}));
db.get().accountExternalIds().deleteKeys(
Iterables.transform(toRemove, fp -> toExtIdKey(fp.get())));
accountCache.evict(rsrc.getUser().getAccountId());
return toJson(newKeys, toRemove, store, rsrc.getUser());
}

View File

@ -609,45 +609,39 @@ class GitwebServlet extends HttpServlet {
final OutputStream dst) throws IOException {
final int contentLength = req.getContentLength();
final InputStream src = req.getInputStream();
new Thread(new Runnable() {
@Override
public void run() {
new Thread(() -> {
try {
try {
try {
final byte[] buf = new byte[bufferSize];
int remaining = contentLength;
while (0 < remaining) {
final int max = Math.max(buf.length, remaining);
final int n = src.read(buf, 0, max);
if (n < 0) {
throw new EOFException("Expected " + remaining + " more bytes");
}
dst.write(buf, 0, n);
remaining -= n;
final byte[] buf = new byte[bufferSize];
int remaining = contentLength;
while (0 < remaining) {
final int max = Math.max(buf.length, remaining);
final int n = src.read(buf, 0, max);
if (n < 0) {
throw new EOFException("Expected " + remaining + " more bytes");
}
} finally {
dst.close();
dst.write(buf, 0, n);
remaining -= n;
}
} catch (IOException e) {
log.debug("Unexpected error copying input to CGI", e);
} finally {
dst.close();
}
} catch (IOException e) {
log.debug("Unexpected error copying input to CGI", e);
}
}, "Gitweb-InputFeeder").start();
}
private void copyStderrToLog(final InputStream in) {
new Thread(new Runnable() {
@Override
public void run() {
try (BufferedReader br =
new BufferedReader(new InputStreamReader(in, ISO_8859_1.name()))) {
String line;
while ((line = br.readLine()) != null) {
log.error("CGI: " + line);
}
} catch (IOException e) {
log.debug("Unexpected error copying stderr from CGI", e);
new Thread(() -> {
try (BufferedReader br =
new BufferedReader(new InputStreamReader(in, ISO_8859_1.name()))) {
String line;
while ((line = br.readLine()) != null) {
log.error("CGI: " + line);
}
} catch (IOException e) {
log.debug("Unexpected error copying stderr from CGI", e);
}
}, "Gitweb-ErrorLogger").start();
}

View File

@ -18,14 +18,13 @@ import static com.google.gerrit.common.FileUtil.lastModified;
import static com.google.gerrit.server.plugins.PluginEntry.ATTR_CHARACTER_ENCODING;
import static com.google.gerrit.server.plugins.PluginEntry.ATTR_CONTENT_TYPE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.toList;
import com.google.common.base.CharMatcher;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.ByteStreams;
@ -74,6 +73,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Predicate;
import java.util.jar.Attributes;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -378,34 +378,30 @@ class HttpPluginServlet extends HttpServlet
List<PluginEntry> docs = new ArrayList<>();
PluginEntry about = null;
Predicate<PluginEntry> filter = new Predicate<PluginEntry>() {
@Override
public boolean apply(PluginEntry entry) {
String name = entry.getName();
Optional<Long> size = entry.getSize();
if (name.startsWith(prefix)
&& (name.endsWith(".md") || name.endsWith(".html"))
&& size.isPresent()) {
if (size.get() <= 0 || size.get() > SMALL_RESOURCE) {
log.warn(String.format(
"Plugin %s: %s omitted from document index. "
+ "Size %d out of range (0,%d).",
pluginName,
name.substring(prefix.length()),
size.get(),
SMALL_RESOURCE));
return false;
Predicate<PluginEntry> filter =
entry -> {
String name = entry.getName();
Optional<Long> size = entry.getSize();
if (name.startsWith(prefix)
&& (name.endsWith(".md") || name.endsWith(".html"))
&& size.isPresent()) {
if (size.get() <= 0 || size.get() > SMALL_RESOURCE) {
log.warn(String.format(
"Plugin %s: %s omitted from document index. "
+ "Size %d out of range (0,%d).",
pluginName,
name.substring(prefix.length()),
size.get(),
SMALL_RESOURCE));
return false;
}
return true;
}
return true;
}
return false;
}
};
return false;
};
List<PluginEntry> entries = FluentIterable
.from(Collections.list(scanner.entries()))
.filter(filter)
.toList();
List<PluginEntry> entries = Collections.list(scanner.entries()).stream()
.filter(filter).collect(toList());
for (PluginEntry entry: entries) {
String name = entry.getName().substring(prefix.length());
if (name.startsWith("cmd-")) {

View File

@ -294,17 +294,14 @@ public abstract class ResourceServlet extends HttpServlet {
}
private Callable<Resource> newLoader(final Path p) {
return new Callable<Resource>() {
@Override
public Resource call() throws IOException {
try {
return new Resource(
getLastModifiedTime(p),
contentType(p.toString()),
Files.readAllBytes(p));
} catch (NoSuchFileException e) {
return Resource.NOT_FOUND;
}
return () -> {
try {
return new Resource(
getLastModifiedTime(p),
contentType(p.toString()),
Files.readAllBytes(p));
} catch (NoSuchFileException e) {
return Resource.NOT_FOUND;
}
};
}

View File

@ -26,6 +26,7 @@ import static com.google.common.net.HttpHeaders.VARY;
import static java.math.RoundingMode.CEILING;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
import static javax.servlet.http.HttpServletResponse.SC_ACCEPTED;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_CONFLICT;
@ -41,9 +42,7 @@ import static javax.servlet.http.HttpServletResponse.SC_OK;
import static javax.servlet.http.HttpServletResponse.SC_PRECONDITION_FAILED;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
@ -145,6 +144,7 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.StreamSupport;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
@ -497,11 +497,13 @@ public class RestApiServlet extends HttpServlet {
String headers = req.getHeader(ACCESS_CONTROL_REQUEST_HEADERS);
if (headers != null) {
res.addHeader(VARY, ACCESS_CONTROL_REQUEST_HEADERS);
String badHeader = Iterables.getFirst(
Iterables.filter(
Splitter.on(',').trimResults().split(headers),
Predicates.not(Predicates.in(ALLOWED_CORS_REQUEST_HEADERS))),
null);
String badHeader =
StreamSupport.stream(
Splitter.on(',').trimResults().split(headers).spliterator(),
false)
.filter(h -> !ALLOWED_CORS_REQUEST_HEADERS.contains(h))
.findFirst()
.orElse(null);
if (badHeader != null) {
throw new BadRequestException(badHeader + " not allowed in CORS");
}
@ -1034,16 +1036,12 @@ public class RestApiServlet extends HttpServlet {
} else if (r.isEmpty()) {
throw new ResourceNotFoundException(projection);
} else {
throw new AmbiguousViewException(String.format(
"Projection %s is ambiguous: %s",
name,
Joiner.on(", ").join(
Iterables.transform(r.keySet(), new Function<String, String>() {
@Override
public String apply(String in) {
return in + "~" + projection;
}
}))));
throw new AmbiguousViewException(
String.format(
"Projection %s is ambiguous: %s",
name,
r.keySet().stream().map(in -> in + "~" + projection)
.collect(joining(", "))));
}
}

View File

@ -14,7 +14,6 @@
package com.google.gerrit.httpd.rpc.project;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Maps;
import com.google.gerrit.common.data.AccessSection;
@ -238,14 +237,7 @@ class ProjectAccessFactory extends Handler<ProjectAccess> {
}
}
}
return Maps.filterEntries(
infos,
new Predicate<Map.Entry<AccountGroup.UUID, GroupInfo>>() {
@Override
public boolean apply(Map.Entry<AccountGroup.UUID, GroupInfo> in) {
return in.getValue() != null;
}
});
return Maps.filterEntries(infos, in -> in.getValue() != null);
}
private ProjectControl open() throws NoSuchProjectException {

View File

@ -22,20 +22,7 @@ import com.google.gwtorm.client.IntKey;
/** Static utilities for ReviewDb types. */
public class ReviewDbUtil {
public static final Function<IntKey<?>, Integer> INT_KEY_FUNCTION =
new Function<IntKey<?>, Integer>() {
@Override
public Integer apply(IntKey<?> in) {
return in.get();
}
};
private static final Function<Change, Change.Id> CHANGE_ID_FUNCTION =
new Function<Change, Change.Id>() {
@Override
public Change.Id apply(Change in) {
return in.getId();
}
};
IntKey::get;
private static final Ordering<? extends IntKey<?>> INT_KEY_ORDERING =
Ordering.natural().nullsFirst().onResultOf(INT_KEY_FUNCTION).nullsFirst();
@ -46,7 +33,7 @@ public class ReviewDbUtil {
}
public static Function<Change, Change.Id> changeIdFunction() {
return CHANGE_ID_FUNCTION;
return Change::getId;
}
public static ReviewDb unwrapDb(ReviewDb db) {

View File

@ -23,7 +23,6 @@ import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
@ -1437,13 +1436,8 @@ public abstract class AbstractQueryChangesTest extends GerritServerTests {
for (int i = 1; i <= 11; i++) {
Iterable<ChangeData> cds = internalChangeQuery.byCommitsOnBranchNotMerged(
repo.getRepository(), db, dest, shas, i);
Iterable<Integer> ids = FluentIterable.from(cds).transform(
new Function<ChangeData, Integer>() {
@Override
public Integer apply(ChangeData in) {
return in.getId().get();
}
});
Iterable<Integer> ids = FluentIterable.from(cds)
.transform(in -> in.getId().get());
String name = "limit " + i;
assertThat(ids).named(name).hasSize(n);
assertThat(ids).named(name)
@ -1640,24 +1634,22 @@ public abstract class AbstractQueryChangesTest extends GerritServerTests {
StringBuilder b = new StringBuilder();
b.append("query '").append(query.getQuery())
.append("' with expected changes ");
b.append(format(Iterables.transform(Arrays.asList(expectedChanges),
new Function<Change, Integer>() {
@Override
public Integer apply(Change change) {
return change.getChangeId();
}
})));
b.append(format(
Arrays.stream(expectedChanges).map(Change::getChangeId).iterator()));
b.append(" and result ");
b.append(format(actualIds));
return b.toString();
}
private String format(Iterable<Integer> changeIds) throws RestApiException {
return format(changeIds.iterator());
}
private String format(Iterator<Integer> changeIds) throws RestApiException {
StringBuilder b = new StringBuilder();
b.append("[");
Iterator<Integer> it = changeIds.iterator();
while (it.hasNext()) {
int id = it.next();
while (changeIds.hasNext()) {
int id = changeIds.next();
ChangeInfo c = gApi.changes().id(id).get();
b.append("{").append(id).append(" (").append(c.changeId)
.append("), ").append("dest=").append(
@ -1666,7 +1658,7 @@ public abstract class AbstractQueryChangesTest extends GerritServerTests {
.append("status=").append(c.status).append(", ")
.append("lastUpdated=").append(c.updated.getTime())
.append("}");
if (it.hasNext()) {
if (changeIds.hasNext()) {
b.append(", ");
}
}
@ -1675,23 +1667,13 @@ public abstract class AbstractQueryChangesTest extends GerritServerTests {
}
protected static Iterable<Integer> ids(Change... changes) {
return FluentIterable.from(Arrays.asList(changes)).transform(
new Function<Change, Integer>() {
@Override
public Integer apply(Change in) {
return in.getId().get();
}
});
return FluentIterable.from(Arrays.asList(changes))
.transform(in -> in.getId().get());
}
protected static Iterable<Integer> ids(Iterable<ChangeInfo> changes) {
return FluentIterable.from(changes).transform(
new Function<ChangeInfo, Integer>() {
@Override
public Integer apply(ChangeInfo in) {
return in._number;
}
});
return FluentIterable.from(changes)
.transform(in -> in._number);
}
protected static long lastUpdatedMs(Change c) {

View File

@ -14,9 +14,9 @@
package com.google.gerrit.testutil;
import static java.util.stream.Collectors.toList;
import com.google.auto.value.AutoValue;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.gerrit.common.errors.EmailException;
@ -111,17 +111,14 @@ public class FakeEmailSender implements EmailSender {
}
}
public ImmutableList<Message> getMessages(String changeId, String type) {
public List<Message> getMessages(String changeId, String type) {
final String idFooter = "\nGerrit-Change-Id: " + changeId + "\n";
final String typeFooter = "\nGerrit-MessageType: " + type + "\n";
return FluentIterable.from(getMessages())
.filter(new Predicate<Message>() {
@Override
public boolean apply(Message in) {
return in.body().contains(idFooter)
&& in.body().contains(typeFooter);
}
}).toList();
return getMessages()
.stream()
.filter(in -> in.body().contains(idFooter)
&& in.body().contains(typeFooter))
.collect(toList());
}
private void waitForEmails() {