From 79e9d8d00b0b9be10a12d6bb37f387f6f8b356f2 Mon Sep 17 00:00:00 2001 From: bpcreech <35012922+bpcreech@users.noreply.github.com> Date: Tue, 6 Sep 2022 22:08:20 -0400 Subject: [PATCH] fix: Apply Google Java Code Clarity suggestions (#1044) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: Apply Google Java Code Clarity suggestions * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Ben Creech Co-authored-by: Owl Bot --- .../clirr-ignored-differences.xml | 12 + google-cloud-logging/pom.xml | 5 + .../com/google/cloud/logging/Context.java | 16 +- .../com/google/cloud/logging/Exclusion.java | 31 +- .../com/google/cloud/logging/HttpRequest.java | 15 +- .../google/cloud/logging/Instrumentation.java | 47 ++- .../com/google/cloud/logging/LogEntry.java | 37 +-- .../cloud/logging/LogEntryIterator.java | 4 +- .../cloud/logging/LogEntryServerStream.java | 13 +- .../com/google/cloud/logging/Logging.java | 214 ++++++-------- .../google/cloud/logging/LoggingConfig.java | 5 +- .../google/cloud/logging/LoggingHandler.java | 39 ++- .../com/google/cloud/logging/LoggingImpl.java | 80 +++--- .../google/cloud/logging/LoggingLevel.java | 1 + .../google/cloud/logging/LoggingOptions.java | 2 +- .../google/cloud/logging/MetadataLoader.java | 49 ++-- .../java/com/google/cloud/logging/Metric.java | 10 +- .../com/google/cloud/logging/MetricInfo.java | 4 +- .../cloud/logging/MonitoredResourceUtil.java | 10 +- .../com/google/cloud/logging/Payload.java | 7 +- .../com/google/cloud/logging/Severity.java | 5 +- .../java/com/google/cloud/logging/Sink.java | 10 +- .../com/google/cloud/logging/SinkInfo.java | 13 +- .../google/cloud/logging/SourceLocation.java | 7 +- .../com/google/cloud/logging/Structs.java | 38 +-- .../cloud/logging/TraceLoggingEnhancer.java | 2 +- .../cloud/logging/spi/v2/GrpcLoggingRpc.java | 6 +- .../logging/testing/RemoteLoggingHelper.java | 7 +- .../logging/AutoPopulateMetadataTests.java | 10 +- .../com/google/cloud/logging/ContextTest.java | 5 +- .../cloud/logging/InstrumentationTest.java | 10 +- .../cloud/logging/InvalidContextTest.java | 11 +- .../google/cloud/logging/LogEntryTest.java | 20 +- .../cloud/logging/LoggingHandlerTest.java | 21 +- .../google/cloud/logging/LoggingImplTest.java | 270 +++++++++--------- .../cloud/logging/LoggingLevelTest.java | 26 +- .../cloud/logging/LoggingOptionsTest.java | 7 +- .../com/google/cloud/logging/LoggingTest.java | 3 +- .../com/google/cloud/logging/MetricTest.java | 4 +- .../logging/MonitoredResourceUtilTest.java | 36 ++- .../com/google/cloud/logging/OptionTest.java | 15 +- .../com/google/cloud/logging/PayloadTest.java | 23 +- .../cloud/logging/SerializationTest.java | 4 +- .../google/cloud/logging/SinkInfoTest.java | 5 +- .../com/google/cloud/logging/SinkTest.java | 4 +- .../cloud/logging/SourceLocationTest.java | 4 +- .../com/google/cloud/logging/StructsTest.java | 31 +- .../cloud/logging/TailLogEntriesTest.java | 16 +- .../logging/v2/testing/LocalLoggingImpl.java | 11 +- 49 files changed, 586 insertions(+), 639 deletions(-) create mode 100644 google-cloud-logging/clirr-ignored-differences.xml diff --git a/google-cloud-logging/clirr-ignored-differences.xml b/google-cloud-logging/clirr-ignored-differences.xml new file mode 100644 index 000000000..aff67cbad --- /dev/null +++ b/google-cloud-logging/clirr-ignored-differences.xml @@ -0,0 +1,12 @@ + + + + 3003 + com/google/cloud/logging/Instrumentation + + + 7009 + com/google/cloud/logging/Instrumentation + Instrumentation() + + diff --git a/google-cloud-logging/pom.xml b/google-cloud-logging/pom.xml index ad8b9412d..1f90850e8 100644 --- a/google-cloud-logging/pom.xml +++ b/google-cloud-logging/pom.xml @@ -127,6 +127,11 @@ test-jar test + + com.google.guava + guava-testlib + test + com.google.api.grpc diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Context.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Context.java index 932777549..109edfafc 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Context.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Context.java @@ -17,8 +17,12 @@ package com.google.cloud.logging; import com.google.cloud.logging.HttpRequest.RequestMethod; +import com.google.common.base.Ascii; import com.google.common.base.MoreObjects; +import com.google.common.base.Splitter; +import com.google.common.collect.Iterables; import com.google.errorprone.annotations.CanIgnoreReturnValue; +import java.util.List; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -125,7 +129,7 @@ public Builder setSpanId(String spanId) { @CanIgnoreReturnValue public Builder loadCloudTraceContext(String cloudTrace) { if (cloudTrace != null) { - cloudTrace = cloudTrace.split(";")[0]; + cloudTrace = Iterables.get(Splitter.on(';').split(cloudTrace), 0); int split = cloudTrace.indexOf('/'); if (split >= 0) { String traceId = cloudTrace.substring(0, split); @@ -157,16 +161,16 @@ public Builder loadCloudTraceContext(String cloudTrace) { * the format version is not supported. */ @CanIgnoreReturnValue - public Builder loadW3CTraceParentContext(String traceParent) throws IllegalArgumentException { + public Builder loadW3CTraceParentContext(String traceParent) { if (traceParent != null) { - Matcher validator = W3C_TRACE_CONTEXT_FORMAT.matcher(traceParent.toLowerCase()); + Matcher validator = W3C_TRACE_CONTEXT_FORMAT.matcher(Ascii.toLowerCase(traceParent)); if (!validator.matches()) { throw new IllegalArgumentException( "Invalid format of the header value. The value does not match W3C Trace Context version \"00\""); } - String[] fields = traceParent.split("-"); - setTraceId(fields[1]); - setSpanId(fields[2]); + List fields = Splitter.on('-').splitToList(traceParent); + setTraceId(fields.get(1)); + setSpanId(fields.get(2)); // fields[3] contains flag(s) } return this; diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Exclusion.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Exclusion.java index a1f84f069..ffa1e50ea 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Exclusion.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Exclusion.java @@ -23,7 +23,6 @@ import com.google.logging.v2.LogExclusion; import com.google.protobuf.Timestamp; import java.util.Objects; -import org.jspecify.nullness.Nullable; /** * Specifies a set of log entries that are not to be stored in Logging. If your GCP resource @@ -35,27 +34,21 @@ public class Exclusion { static final Function FROM_PROTOBUF_FUNCTION = - new Function() { - @Override - public @Nullable Exclusion apply(LogExclusion exclusionPb) { - return exclusionPb != null ? Exclusion.fromProtobuf(exclusionPb) : null; - } + (LogExclusion exclusionPb) -> { + return exclusionPb != null ? Exclusion.fromProtobuf(exclusionPb) : null; }; static final Function TO_PROTOBUF_FUNCTION = - new Function() { - @Override - public @Nullable LogExclusion apply(Exclusion exclusion) { - return exclusion != null ? exclusion.toProtobuf() : null; - } + (Exclusion exclusion) -> { + return exclusion != null ? exclusion.toProtobuf() : null; }; - private String name; - private String description; - private String filter; - private boolean disabled; - private Timestamp createTime; - private Timestamp updateTime; + private final String name; + private final String description; + private final String filter; + private final boolean disabled; + private final Timestamp createTime; + private final Timestamp updateTime; /** A builder for {@code Exclusion} objects. */ public static class Builder { @@ -165,7 +158,7 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { + if (!(o instanceof Exclusion)) { return false; } Exclusion exclusion = (Exclusion) o; @@ -253,7 +246,7 @@ LogExclusion toProtobuf() { static Exclusion fromProtobuf(LogExclusion exclusionPb) { Exclusion.Builder builder = newBuilder(exclusionPb.getName(), exclusionPb.getFilter()); builder.setDisabled(exclusionPb.getDisabled()); - if (!exclusionPb.getDescription().equals("")) { + if (!exclusionPb.getDescription().isEmpty()) { builder.setDescription(exclusionPb.getDescription()); } if (exclusionPb.hasCreateTime()) { diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/HttpRequest.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/HttpRequest.java index 9ba29bb13..4bf78e641 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/HttpRequest.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/HttpRequest.java @@ -20,7 +20,6 @@ import com.google.cloud.StringEnumType; import com.google.cloud.StringEnumValue; import com.google.common.base.MoreObjects; -import com.google.common.base.Strings; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.Serializable; import java.util.Objects; @@ -71,7 +70,7 @@ public RequestMethod apply(String constant) { }; private static final StringEnumType type = - new StringEnumType(RequestMethod.class, CONSTRUCTOR); + new StringEnumType<>(RequestMethod.class, CONSTRUCTOR); public static final RequestMethod GET = type.createAndRegister("GET"); public static final RequestMethod HEAD = type.createAndRegister("HEAD"); @@ -527,10 +526,10 @@ public static Builder newBuilder() { static HttpRequest fromPb(com.google.logging.type.HttpRequest requestPb) { Builder builder = newBuilder(); - if (!Strings.isNullOrEmpty(requestPb.getRequestMethod())) { + if (!requestPb.getRequestMethod().isEmpty()) { builder.setRequestMethod(RequestMethod.valueOf(requestPb.getRequestMethod())); } - if (!Strings.isNullOrEmpty(requestPb.getRequestUrl())) { + if (!requestPb.getRequestUrl().isEmpty()) { builder.setRequestUrl(requestPb.getRequestUrl()); } if (requestPb.getRequestSize() != 0L) { @@ -542,16 +541,16 @@ static HttpRequest fromPb(com.google.logging.type.HttpRequest requestPb) { if (requestPb.getResponseSize() != 0L) { builder.setResponseSize(requestPb.getResponseSize()); } - if (!Strings.isNullOrEmpty(requestPb.getUserAgent())) { + if (!requestPb.getUserAgent().isEmpty()) { builder.setUserAgent(requestPb.getUserAgent()); } - if (!Strings.isNullOrEmpty(requestPb.getServerIp())) { + if (!requestPb.getServerIp().isEmpty()) { builder.setServerIp(requestPb.getServerIp()); } - if (!Strings.isNullOrEmpty(requestPb.getRemoteIp())) { + if (!requestPb.getRemoteIp().isEmpty()) { builder.setRemoteIp(requestPb.getRemoteIp()); } - if (!Strings.isNullOrEmpty(requestPb.getReferer())) { + if (!requestPb.getReferer().isEmpty()) { builder.setReferer(requestPb.getReferer()); } builder.setCacheLookup(requestPb.getCacheLookup()); diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Instrumentation.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Instrumentation.java index c827d2c93..f9f000c78 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Instrumentation.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Instrumentation.java @@ -21,18 +21,17 @@ import com.google.cloud.Tuple; import com.google.cloud.logging.Logging.WriteOption; import com.google.cloud.logging.Payload.JsonPayload; -import com.google.cloud.logging.Payload.Type; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.protobuf.ListValue; import com.google.protobuf.Struct; import com.google.protobuf.Value; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import org.jspecify.nullness.Nullable; -public class Instrumentation { +public final class Instrumentation { public static final String DIAGNOSTIC_INFO_KEY = "logging.googleapis.com/diagnostic"; public static final String INSTRUMENTATION_SOURCE_KEY = "instrumentation_source"; public static final String INSTRUMENTATION_NAME_KEY = "name"; @@ -43,14 +42,14 @@ public class Instrumentation { public static final int MAX_DIAGNOSTIC_VALUE_LENGTH = 14; public static final int MAX_DIAGNOSTIC_ENTIES = 3; private static boolean instrumentationAdded = false; - private static Object instrumentationLock = new Object(); + private static final Object instrumentationLock = new Object(); /** * Populates entries with instrumentation info which is added in separate log entry * - * @param logEntries {Iterable} The list of entries to be populated - * @return {Tuple>} containing a flag if instrumentation info was - * added or not and a modified list of log entries + * @param logEntries {@code Iterable} The list of entries to be populated + * @return {@code Tuple>} containing a flag if instrumentation info + * was added or not and a modified list of log entries */ public static Tuple> populateInstrumentationInfo( Iterable logEntries) { @@ -61,7 +60,7 @@ public static Tuple> populateInstrumentationInfo( for (LogEntry logEntry : logEntries) { // Check if LogEntry has a proper payload and also contains a diagnostic entry if (!isWritten - && logEntry.getPayload().getType() == Type.JSON + && logEntry.getPayload().getType() == Payload.Type.JSON && logEntry .getPayload() .getData() @@ -77,7 +76,7 @@ public static Tuple> populateInstrumentationInfo( .getListValue(); entries.add(createDiagnosticEntry(null, null, infoList)); isWritten = true; - } catch (Exception ex) { + } catch (RuntimeException ex) { System.err.println("ERROR: unexpected exception in populateInstrumentationInfo: " + ex); } } else { @@ -99,8 +98,8 @@ public static Tuple> populateInstrumentationInfo( */ public static WriteOption @Nullable [] addPartialSuccessOption(WriteOption[] options) { if (options == null) return options; - List writeOptions = new ArrayList(); - writeOptions.addAll(Arrays.asList(options)); + List writeOptions = new ArrayList<>(); + Collections.addAll(writeOptions, options); // Make sure we remove all partial success flags if any exist writeOptions.removeIf( option -> option.getOptionType() == WriteOption.OptionType.PARTIAL_SUCCESS); @@ -133,18 +132,16 @@ private static LogEntry createDiagnosticEntry( generateLibrariesList(libraryName, libraryVersion, existingLibraryList)) .build())) .build(); - LogEntry entry = - LogEntry.newBuilder( - JsonPayload.of( - Struct.newBuilder() - .putAllFields( - ImmutableMap.of( - DIAGNOSTIC_INFO_KEY, - Value.newBuilder().setStructValue(instrumentation).build())) - .build())) - .setLogName(INSTRUMENTATION_LOG_NAME) - .build(); - return entry; + return LogEntry.newBuilder( + JsonPayload.of( + Struct.newBuilder() + .putAllFields( + ImmutableMap.of( + DIAGNOSTIC_INFO_KEY, + Value.newBuilder().setStructValue(instrumentation).build())) + .build())) + .setLogName(INSTRUMENTATION_LOG_NAME) + .build(); } private static ListValue generateLibrariesList( @@ -171,7 +168,7 @@ private static ListValue generateLibrariesList( libraryList.addValues( Value.newBuilder().setStructValue(createInfoStruct(name, version)).build()); if (libraryList.getValuesCount() == MAX_DIAGNOSTIC_ENTIES) break; - } catch (Exception ex) { + } catch (RuntimeException ex) { } } } @@ -222,4 +219,6 @@ private static String truncateValue(String value) { if (Strings.isNullOrEmpty(value) || value.length() < MAX_DIAGNOSTIC_VALUE_LENGTH) return value; return value.substring(0, MAX_DIAGNOSTIC_VALUE_LENGTH) + "*"; } + + private Instrumentation() {} } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java index 169bfe4cd..45b8b9a30 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java @@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.cloud.MonitoredResource; -import com.google.cloud.logging.Payload.Type; import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableMap; @@ -55,11 +54,8 @@ public class LogEntry implements Serializable { private static final long serialVersionUID = -944788159728228219L; static final Function FROM_PB_FUNCTION = - new Function() { - @Override - public LogEntry apply(com.google.logging.v2.LogEntry pb) { - return fromPb(pb); - } + (com.google.logging.v2.LogEntry pb) -> { + return fromPb(pb); }; private final String logName; @@ -69,7 +65,7 @@ public LogEntry apply(com.google.logging.v2.LogEntry pb) { private final Severity severity; private final String insertId; private final HttpRequest httpRequest; - private final Map labels; + private final ImmutableMap labels; private final Operation operation; private final String trace; private final String spanId; @@ -148,7 +144,7 @@ public Builder setResource(MonitoredResource resource) { * omitted, the Logging service will use the time at which the log entry is received. * * @deprecated This method is no longer recommended to setup the entry timestamp. - *

Use {@link setTimeStamp(Instant)} instead. + *

Use {@link #setTimestamp(Instant)} instead. */ @CanIgnoreReturnValue @Deprecated @@ -444,13 +440,13 @@ public Operation getOperation() { */ public @Nullable String getTrace() { // For backwards compatibility return null when trace not set instead of "null". - return trace == null ? null : String.valueOf(trace); + return trace == null ? null : trace; } /** Returns the ID of the trace span associated with the log entry, if any. */ public @Nullable String getSpanId() { // For backwards compatibility return null when spanId not set instead of "null". - return spanId == null ? null : String.valueOf(spanId); + return spanId == null ? null : spanId; } /** @@ -716,7 +712,7 @@ public StructuredLogFormatter appendDict(Map value, boolean appe * the logging agents that run on Google Cloud resources. */ public String toStructuredJsonString() { - if (payload.getType() == Type.PROTO) { + if (payload.getType() == Payload.Type.PROTO) { throw new UnsupportedOperationException("LogEntry with protobuf payload cannot be converted"); } @@ -734,9 +730,9 @@ public String toStructuredJsonString() { .appendField("logging.googleapis.com/spanId", spanId) .appendField("logging.googleapis.com/trace", trace) .appendField("logging.googleapis.com/trace_sampled", traceSampled); - if (payload.getType() == Type.STRING) { + if (payload.getType() == Payload.Type.STRING) { formatter.appendField("message", payload.getData(), false); - } else if (payload.getType() == Type.JSON) { + } else if (payload.getType() == Payload.Type.JSON) { Payload.JsonPayload jsonPayload = (Payload.JsonPayload) payload; formatter.appendDict(jsonPayload.getDataAsMap(), false); } @@ -766,7 +762,7 @@ static LogEntry fromPb(com.google.logging.v2.LogEntry entryPb) { Builder builder = newBuilder(Payload.fromPb(entryPb)); builder.setLabels(entryPb.getLabelsMap()); builder.setSeverity(Severity.fromPb(entryPb.getSeverity())); - if (!entryPb.getLogName().equals("")) { + if (!entryPb.getLogName().isEmpty()) { LogName name = LogName.parse(entryPb.getLogName()); builder.setLogName(name.getLog()); LogDestinationName resource = LogDestinationName.fromLogName(name); @@ -783,7 +779,7 @@ static LogEntry fromPb(com.google.logging.v2.LogEntry entryPb) { if (entryPb.hasReceiveTimestamp()) { builder.setReceiveTimestamp(JavaTimeConversions.toJavaInstant(entryPb.getReceiveTimestamp())); } - if (!entryPb.getInsertId().equals("")) { + if (!entryPb.getInsertId().isEmpty()) { builder.setInsertId(entryPb.getInsertId()); } if (!entryPb @@ -794,10 +790,10 @@ static LogEntry fromPb(com.google.logging.v2.LogEntry entryPb) { if (!entryPb.getOperation().equals(LogEntryOperation.getDefaultInstance())) { builder.setOperation(Operation.fromPb(entryPb.getOperation())); } - if (!entryPb.getTrace().equals("")) { + if (!entryPb.getTrace().isEmpty()) { builder.setTrace(entryPb.getTrace()); } - if (!entryPb.getSpanId().equals("")) { + if (!entryPb.getSpanId().isEmpty()) { builder.setSpanId(entryPb.getSpanId()); } builder.setTraceSampled(entryPb.getTraceSampled()); @@ -808,11 +804,8 @@ static LogEntry fromPb(com.google.logging.v2.LogEntry entryPb) { } static Function toPbFunction(final String projectId) { - return new Function() { - @Override - public com.google.logging.v2.LogEntry apply(LogEntry entry) { - return entry.toPb(projectId); - } + return (LogEntry entry) -> { + return entry.toPb(projectId); }; } } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntryIterator.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntryIterator.java index 34887e49b..2bbd76be2 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntryIterator.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntryIterator.java @@ -18,8 +18,8 @@ import com.google.common.collect.Lists; import com.google.logging.v2.TailLogEntriesResponse; +import java.util.ArrayDeque; import java.util.Iterator; -import java.util.LinkedList; /** * The class implements {@see Iterator} interface over {@see LogEntry} by iterating through {@see @@ -30,7 +30,7 @@ public class LogEntryIterator implements Iterator { // TODO: consider converting this to use generics instead of // fixed TailLogEntriesResponse private final Iterator streamIterator; - private final LinkedList buffer = new LinkedList<>(); + private final ArrayDeque buffer = new ArrayDeque<>(); LogEntryIterator(Iterator streamIterator) { this.streamIterator = streamIterator; diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntryServerStream.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntryServerStream.java index 1bbf038f3..43821861f 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntryServerStream.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntryServerStream.java @@ -21,13 +21,14 @@ import com.google.logging.v2.TailLogEntriesRequest; import com.google.logging.v2.TailLogEntriesResponse; import java.util.Iterator; +import java.util.List; /** - * The class implements {@Iterable} interface over {@see LogEntry}. It wraps around {@BidiStream} - * bi-directional gRPC stream to support iterating through ingested responses. The class uses {@see - * LogEntryIterator} to iterate through the processed responses. The stream should be explicitly - * canceled by calling {@see LogEntryServerStream#cancel()} method. The class does not provide - * recovery or resuming functionality over the stream. + * The class implements {@link Iterable} interface over {@see LogEntry}. It wraps around {@link + * BidiStream} bi-directional gRPC stream to support iterating through ingested responses. The class + * uses {@see LogEntryIterator} to iterate through the processed responses. The stream should be + * explicitly canceled by calling {@see LogEntryServerStream#cancel()} method. The class does not + * provide recovery or resuming functionality over the stream. * *

To iterate run: * @@ -59,7 +60,7 @@ public BidiStream getInternalStre return serverStream; } - public java.util.List convert(TailLogEntriesResponse resp) { + public List convert(TailLogEntriesResponse resp) { return Lists.transform(resp.getEntriesList(), LogEntry.FROM_PB_FUNCTION); } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java index 832c61137..7c650978b 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java @@ -23,6 +23,7 @@ import com.google.cloud.MonitoredResource; import com.google.cloud.MonitoredResourceDescriptor; import com.google.cloud.Service; +import com.google.common.base.Ascii; import com.google.common.collect.ImmutableMap; import java.util.Map; @@ -46,18 +47,18 @@ T get(Map options) { } } - private ListOption(OptionType option, Object value) { + private ListOption(ListOption.OptionType option, Object value) { super(option, value); } /** Returns an option to specify the maximum number of resources returned per page. */ public static ListOption pageSize(int pageSize) { - return new ListOption(OptionType.PAGE_SIZE, pageSize); + return new ListOption(ListOption.OptionType.PAGE_SIZE, pageSize); } /** Returns an option to specify the page token from which to start listing resources. */ public static ListOption pageToken(String pageToken) { - return new ListOption(OptionType.PAGE_TOKEN, pageToken); + return new ListOption(ListOption.OptionType.PAGE_TOKEN, pageToken); } } @@ -80,7 +81,7 @@ T get(Map options) { } } - private WriteOption(OptionType option, Object value) { + private WriteOption(WriteOption.OptionType option, Object value) { super(option, value); } @@ -89,7 +90,7 @@ private WriteOption(OptionType option, Object value) { * log entries that do not specify their own log name. Example: {@code syslog}. */ public static WriteOption logName(String logName) { - return new WriteOption(OptionType.LOG_NAME, logName); + return new WriteOption(WriteOption.OptionType.LOG_NAME, logName); } /** @@ -97,7 +98,7 @@ public static WriteOption logName(String logName) { * LogEntry#getResource()}) for those log entries that do not specify their own resource. */ public static WriteOption resource(MonitoredResource resource) { - return new WriteOption(OptionType.RESOURCE, resource); + return new WriteOption(WriteOption.OptionType.RESOURCE, resource); } /** @@ -106,7 +107,7 @@ public static WriteOption resource(MonitoredResource resource) { * associated to the same key. */ public static WriteOption labels(Map labels) { - return new WriteOption(OptionType.LABELS, ImmutableMap.copyOf(labels)); + return new WriteOption(WriteOption.OptionType.LABELS, ImmutableMap.copyOf(labels)); } /** @@ -114,7 +115,7 @@ public static WriteOption labels(Map labels) { * for details) */ public static WriteOption destination(LogDestinationName destination) { - return new WriteOption(OptionType.LOG_DESTINATION, destination); + return new WriteOption(WriteOption.OptionType.LOG_DESTINATION, destination); } /** @@ -122,16 +123,16 @@ public static WriteOption destination(LogDestinationName destination) { * set. */ public static WriteOption autoPopulateMetadata(boolean autoPopulateMetadata) { - return new WriteOption(OptionType.AUTO_POPULATE_METADATA, autoPopulateMetadata); + return new WriteOption(WriteOption.OptionType.AUTO_POPULATE_METADATA, autoPopulateMetadata); } /** - * Returns an option to set partialSuccess flag. See {@link - * https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write#body.request_body.FIELDS.partial_success} - * for more details. + * Returns an option to set partialSuccess flag. See the + * API documentation for more details. */ public static WriteOption partialSuccess(boolean partialSuccess) { - return new WriteOption(OptionType.PARTIAL_SUCCESS, partialSuccess); + return new WriteOption(WriteOption.OptionType.PARTIAL_SUCCESS, partialSuccess); } } @@ -140,7 +141,7 @@ enum SortingField { TIMESTAMP; String selector() { - return name().toLowerCase(); + return Ascii.toLowerCase(name()); } } @@ -197,7 +198,8 @@ public static EntryListOption pageToken(String pageToken) { * (most-recent last) order with respect to the {@link LogEntry#getTimestamp()} value. */ public static EntryListOption sortOrder(SortingField field, SortingOrder order) { - return new EntryListOption(OptionType.ORDER_BY, field.selector() + ' ' + order.selector()); + return new EntryListOption( + EntryListOption.OptionType.ORDER_BY, field.selector() + ' ' + order.selector()); } /** @@ -207,22 +209,22 @@ public static EntryListOption sortOrder(SortingField field, SortingOrder order) * Filters */ public static EntryListOption filter(String filter) { - return new EntryListOption(OptionType.FILTER, filter); + return new EntryListOption(EntryListOption.OptionType.FILTER, filter); } /** Returns an option to specify an organization for the log entries to be listed. */ public static EntryListOption organization(String organization) { - return new EntryListOption(OptionType.ORGANIZATION, organization); + return new EntryListOption(EntryListOption.OptionType.ORGANIZATION, organization); } /** Returns an option to specify a billingAccount for the log entries to be listed. */ public static EntryListOption billingAccount(String billingAccount) { - return new EntryListOption(OptionType.BILLINGACCOUNT, billingAccount); + return new EntryListOption(EntryListOption.OptionType.BILLINGACCOUNT, billingAccount); } /** Returns an option to specify a folder for the log entries to be listed. */ public static EntryListOption folder(String folder) { - return new EntryListOption(OptionType.FOLDER, folder); + return new EntryListOption(EntryListOption.OptionType.FOLDER, folder); } } @@ -256,7 +258,7 @@ private TailOption(Option.OptionType option, Object value) { * Filters */ public static TailOption filter(String filter) { - return new TailOption(OptionType.FILTER, filter); + return new TailOption(TailOption.OptionType.FILTER, filter); } /** @@ -269,39 +271,34 @@ public static TailOption filter(String filter) { * format */ public static TailOption bufferWindow(String duration) { - return new TailOption(OptionType.BUFFERWINDOW, duration); + return new TailOption(TailOption.OptionType.BUFFERWINDOW, duration); } /** Returns an option to specify an organization for the log entries to be tailed. */ public static TailOption organization(String organization) { - return new TailOption(OptionType.ORGANIZATION, organization); + return new TailOption(TailOption.OptionType.ORGANIZATION, organization); } /** Returns an option to specify a billingAccount for the log entries to be tailed. */ public static TailOption billingAccount(String billingAccount) { - return new TailOption(OptionType.BILLINGACCOUNT, billingAccount); + return new TailOption(TailOption.OptionType.BILLINGACCOUNT, billingAccount); } /** Returns an option to specify a folder for the log entries to be tailed. */ public static TailOption folder(String folder) { - return new TailOption(OptionType.FOLDER, folder); + return new TailOption(TailOption.OptionType.FOLDER, folder); } /** Returns an option to specify a project for the log entries to be tailed. */ public static TailOption project(String project) { - return new TailOption(OptionType.PROJECT, project); + return new TailOption(TailOption.OptionType.PROJECT, project); } } - /* - * Sets synchronicity {@link Synchronicity} of logging writes, defaults to - * asynchronous. - */ + /** Sets synchronicity {@link Synchronicity} of logging writes, defaults to asynchronous. */ void setWriteSynchronicity(Synchronicity synchronicity); - /* - * Retrieves current set synchronicity {@link Synchronicity} of logging writes. - */ + /** Retrieves current set synchronicity {@link Synchronicity} of logging writes. */ Synchronicity getWriteSynchronicity(); /** @@ -479,19 +476,16 @@ public static TailOption project(String project) { * *

Example of asynchronously listing sinks, specifying the page size. * - *

-   * {
-   *   @code
-   *   ApiFuture> future = logging.listSinksAsync(ListOption.pageSize(100));
-   *   // ...
-   *   AsyncPage sinks = future.get();
-   *   Iterator sinkIterator = sinks.iterateAll().iterator();
-   *   while (sinkIterator.hasNext()) {
-   *     Sink sink = sinkIterator.next();
-   *     // do something with the sink
-   *   }
+   * 
{@code
+   * ApiFuture> future = logging.listSinksAsync(ListOption.pageSize(100));
+   * // ...
+   * AsyncPage sinks = future.get();
+   * Iterator sinkIterator = sinks.iterateAll().iterator();
+   * while (sinkIterator.hasNext()) {
+   *   Sink sink = sinkIterator.next();
+   *   // do something with the sink
    * }
-   * 
+ * }
*/ ApiFuture> listSinksAsync(ListOption... options); @@ -575,19 +569,16 @@ default Page listLogs(ListOption... options) { * *

Example of asynchronously listing log names, specifying the page size. * - *

-   * {
-   *   @code
-   *   ApiFuture> future = logging.listLogsAsync(ListOption.pageSize(100));
-   *   // ...
-   *   AsyncPage logNames = future.get();
-   *   Iterator logIterator = logNames.iterateAll().iterator();
-   *   while (logIterator.hasNext()) {
-   *     String logName = logIterator.next();
-   *     // do something with the log name
-   *   }
+   * 
{@code
+   * ApiFuture> future = logging.listLogsAsync(ListOption.pageSize(100));
+   * // ...
+   * AsyncPage logNames = future.get();
+   * Iterator logIterator = logNames.iterateAll().iterator();
+   * while (logIterator.hasNext()) {
+   *   String logName = logIterator.next();
+   *   // do something with the log name
    * }
-   * 
+ * }
*/ default ApiFuture> listLogsAsync(ListOption... options) { throw new UnsupportedOperationException( @@ -730,20 +721,17 @@ default ApiFuture deleteLogAsync(String log, LogDestinationName destina * *

Example of asynchronously listing monitored resource descriptors, specifying the page size. * - *

-   * {
-   *   @code
-   *   ApiFuture> future = logging
-   *       .listMonitoredResourceDescriptorsAsync(ListOption.pageSize(100));
-   *   // ...
-   *   AsyncPage descriptors = future.get();
-   *   Iterator descriptorIterator = descriptors.iterateAll().iterator();
-   *   while (descriptorIterator.hasNext()) {
-   *     MonitoredResourceDescriptor descriptor = descriptorIterator.next();
-   *     // do something with the descriptor
-   *   }
+   * 
{@code
+   * ApiFuture> future = logging
+   *     .listMonitoredResourceDescriptorsAsync(ListOption.pageSize(100));
+   * // ...
+   * AsyncPage descriptors = future.get();
+   * Iterator descriptorIterator = descriptors.iterateAll().iterator();
+   * while (descriptorIterator.hasNext()) {
+   *   MonitoredResourceDescriptor descriptor = descriptorIterator.next();
+   *   // do something with the descriptor
    * }
-   * 
+ * }
*/ ApiFuture> listMonitoredResourceDescriptorsAsync( ListOption... options); @@ -901,19 +889,16 @@ ApiFuture> listMonitoredResourceDescripto * *

Example of asynchronously listing metrics, specifying the page size. * - *

-   * {
-   *   @code
-   *   ApiFuture> future = logging.listMetricsAsync(ListOption.pageSize(100));
-   *   // ...
-   *   AsyncPage metrics = future.get();
-   *   Iterator metricIterator = metrics.iterateAll().iterator();
-   *   while (metricIterator.hasNext()) {
-   *     Metric metric = metricIterator.next();
-   *     // do something with the metric
-   *   }
+   * 
{@code
+   * ApiFuture> future = logging.listMetricsAsync(ListOption.pageSize(100));
+   * // ...
+   * AsyncPage metrics = future.get();
+   * Iterator metricIterator = metrics.iterateAll().iterator();
+   * while (metricIterator.hasNext()) {
+   *   Metric metric = metricIterator.next();
+   *   // do something with the metric
    * }
-   * 
+ * }
*/ ApiFuture> listMetricsAsync(ListOption... options); @@ -1168,19 +1153,16 @@ ApiFuture> listMonitoredResourceDescripto * *

Example of asynchronously listing exclusions, specifying the page size: * - *

-   * {
-   *   @code
-   *   ApiFuture> future = logging.listExclusionsAsync(ListOption.pageSize(100));
-   *   // ...
-   *   AsyncPage exclusions = future.get();
-   *   Iterator exclusionIterator = exclusions.iterateAll().iterator();
-   *   while (exclusionIterator.hasNext()) {
-   *     Exclusion exclusion = exclusionIterator.next();
-   *     // do something with the exclusion
-   *   }
+   * 
{@code
+   * ApiFuture> future = logging.listExclusionsAsync(ListOption.pageSize(100));
+   * // ...
+   * AsyncPage exclusions = future.get();
+   * Iterator exclusionIterator = exclusions.iterateAll().iterator();
+   * while (exclusionIterator.hasNext()) {
+   *   Exclusion exclusion = exclusionIterator.next();
+   *   // do something with the exclusion
    * }
-   * 
+ * }
*/ ApiFuture> listExclusionsAsync(ListOption... options); @@ -1202,19 +1184,16 @@ ApiFuture> listMonitoredResourceDescripto * *

Example of writing log entries and providing a default log name and monitored resource. * - *

-   * {
-   *   @code
-   *   String logName = "my_log_name";
-   *   List entries = new ArrayList<>();
-   *   entries.add(LogEntry.of(StringPayload.of("Entry payload")));
-   *   Map jsonMap = new HashMap<>();
-   *   jsonMap.put("key", "value");
-   *   entries.add(LogEntry.of(JsonPayload.of(jsonMap)));
-   *   logging.write(entries, WriteOption.logName(logName),
-   *       WriteOption.resource(MonitoredResource.newBuilder("global").build()));
-   * }
-   * 
+ *
{@code
+   * String logName = "my_log_name";
+   * List entries = new ArrayList<>();
+   * entries.add(LogEntry.of(StringPayload.of("Entry payload")));
+   * Map jsonMap = new HashMap<>();
+   * jsonMap.put("key", "value");
+   * entries.add(LogEntry.of(JsonPayload.of(jsonMap)));
+   * logging.write(entries, WriteOption.logName(logName),
+   *     WriteOption.resource(MonitoredResource.newBuilder("global").build()));
+   * }
*/ void write(Iterable logEntries, WriteOption... options); @@ -1256,20 +1235,17 @@ ApiFuture> listMonitoredResourceDescripto * *

Example of asynchronously listing log entries for a specific log. * - *

-   * {
-   *   @code
-   *   String filter = "logName=projects/my_project_id/logs/my_log_name";
-   *   ApiFuture> future = logging.listLogEntriesAsync(EntryListOption.filter(filter));
-   *   // ...
-   *   AsyncPage entries = future.get();
-   *   Iterator entryIterator = entries.iterateAll().iterator();
-   *   while (entryIterator.hasNext()) {
-   *     LogEntry entry = entryIterator.next();
-   *     // do something with the entry
-   *   }
+   * 
{@code
+   * String filter = "logName=projects/my_project_id/logs/my_log_name";
+   * ApiFuture> future = logging.listLogEntriesAsync(EntryListOption.filter(filter));
+   * // ...
+   * AsyncPage entries = future.get();
+   * Iterator entryIterator = entries.iterateAll().iterator();
+   * while (entryIterator.hasNext()) {
+   *   LogEntry entry = entryIterator.next();
+   *   // do something with the entry
    * }
-   * 
+ * }
* * @throws LoggingException upon failure */ diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingConfig.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingConfig.java index 93e0c338f..702ef1a5a 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingConfig.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingConfig.java @@ -19,6 +19,7 @@ import static com.google.common.base.MoreObjects.firstNonNull; import com.google.cloud.MonitoredResource; +import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; @@ -68,7 +69,7 @@ Synchronicity getSynchronicity() { String synchronicityStr = getProperty(SYNCHRONICITY_TAG); try { return Synchronicity.valueOf(synchronicityStr); - } catch (Exception ex) { + } catch (RuntimeException ex) { // If we cannot create the Synchronicity we fall back to default value } return Synchronicity.ASYNC; @@ -96,7 +97,7 @@ List getEnhancers() { try { List enhancers = new ArrayList<>(); if (list != null) { - String[] items = list.split(","); + Iterable items = Splitter.on(',').split(list); for (String e_name : items) { Class clazz = ClassLoader.getSystemClassLoader() diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java index c92e2bd49..768209b46 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java @@ -17,6 +17,7 @@ package com.google.cloud.logging; import static com.google.common.base.MoreObjects.firstNonNull; +import static java.util.Arrays.stream; import com.google.cloud.MonitoredResource; import com.google.cloud.logging.Logging.WriteOption; @@ -25,9 +26,6 @@ import com.google.common.collect.Iterables; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.logging.ErrorManager; @@ -156,7 +154,7 @@ public class LoggingHandler extends Handler { private volatile Boolean autoPopulateMetadata; private volatile Boolean redirectToStdout; - private WriteOption[] defaultWriteOptions; + private final WriteOption[] defaultWriteOptions; /** Creates an handler that publishes messages to Cloud Logging. */ public LoggingHandler() { @@ -250,7 +248,7 @@ public LoggingHandler( MonitoredResource resource = firstNonNull( monitoredResource, config.getMonitoredResource(loggingOptions.getProjectId())); - List writeOptions = new ArrayList(); + List writeOptions = new ArrayList<>(); writeOptions.add(WriteOption.logName(logName)); if (resource != null) { writeOptions.add(WriteOption.resource(resource)); @@ -271,12 +269,10 @@ public LoggingHandler( logging.setFlushSeverity(severityFor(flushLevel)); logging.setWriteSynchronicity(config.getSynchronicity()); - this.enhancers = new LinkedList<>(); + this.enhancers = new ArrayList<>(); List enhancersParam = - firstNonNull( - enhancers, - firstNonNull(config.getEnhancers(), Collections.emptyList())); + firstNonNull(enhancers, firstNonNull(config.getEnhancers(), ImmutableList.of())); this.enhancers.addAll(enhancersParam); @@ -284,7 +280,7 @@ public LoggingHandler( // attribute) List loggingEnhancers = MonitoredResourceUtil.getResourceEnhancers(); this.enhancers.addAll(loggingEnhancers); - } catch (Exception ex) { + } catch (RuntimeException ex) { reportError(null, ex, ErrorManager.OPEN_FAILURE); throw ex; } @@ -307,7 +303,7 @@ public void publish(LogRecord record) { LogEntry logEntry; try { logEntry = logEntryFor(record).build(); - } catch (Exception ex) { + } catch (RuntimeException ex) { getErrorManager().error(null, ex, ErrorManager.FORMAT_FAILURE); return; } @@ -327,7 +323,7 @@ public void publish(LogRecord record) { } else { logging.write(logEntries, defaultWriteOptions); } - } catch (Exception ex) { + } catch (RuntimeException ex) { getErrorManager().error(null, ex, ErrorManager.WRITE_FAILURE); } } @@ -335,7 +331,7 @@ public void publish(LogRecord record) { private @Nullable MonitoredResource getMonitoredResource() { Optional resourceOption = - Arrays.stream(defaultWriteOptions) + stream(defaultWriteOptions) .filter(o -> o.getOptionType() == WriteOption.OptionType.RESOURCE) .findFirst(); if (resourceOption.isPresent()) { @@ -344,7 +340,7 @@ public void publish(LogRecord record) { return null; } - protected LogEntry.Builder logEntryFor(LogRecord record) throws Exception { + protected LogEntry.Builder logEntryFor(LogRecord record) { String payload = getFormatter().format(record); Level level = record.getLevel(); LogEntry.Builder builder = @@ -368,14 +364,14 @@ protected LogEntry.Builder logEntryFor(LogRecord record) throws Exception { public void flush() { try { logging.flush(); - } catch (Exception ex) { + } catch (RuntimeException ex) { getErrorManager().error(null, ex, ErrorManager.FLUSH_FAILURE); } } /** Closes the handler and the associated {@link Logging} object. */ @Override - public synchronized void close() throws SecurityException { + public synchronized void close() { if (logging != null) { try { logging.close(); @@ -454,18 +450,15 @@ private static Severity severityFor(Level level) { switch (level.intValue()) { // FINEST - case 300: - return Severity.DEBUG; // FINER - case 400: - return Severity.DEBUG; // FINE + case 300: + case 400: case 500: return Severity.DEBUG; // CONFIG - case 700: - return Severity.INFO; // INFO + case 700: case 800: return Severity.INFO; // WARNING @@ -480,6 +473,6 @@ private static Severity severityFor(Level level) { } private static boolean isTrueOrNull(Boolean b) { - return b == null || b == Boolean.TRUE; + return b == null || b.equals(Boolean.TRUE); } } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java index 48b93146c..56f52bee0 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java @@ -43,8 +43,10 @@ import com.google.cloud.Tuple; import com.google.cloud.logging.spi.v2.LoggingRpc; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Ascii; import com.google.common.base.Function; import com.google.common.base.Throwables; +import com.google.common.base.VerifyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; @@ -87,7 +89,9 @@ import com.google.logging.v2.WriteLogEntriesResponse; import com.google.protobuf.Empty; import com.google.protobuf.util.Durations; +import java.text.ParseException; import java.util.*; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -104,13 +108,10 @@ class LoggingImpl extends BaseService implements Logging { private volatile Severity flushSeverity = null; private boolean closed; - private static final Function EMPTY_TO_BOOLEAN_FUNCTION = - new Function() { - @Override - public Boolean apply(Empty input) { - return input != null; - } - }; + private static Boolean emptyToBooleanFunction(Empty input) { + return input != null; + } + private static final Function WRITE_RESPONSE_TO_VOID_FUNCTION = new Function() { @Override @@ -128,18 +129,22 @@ public Void apply(WriteLogEntriesResponse input) { rpc = options.getLoggingRpcV2(); } + @Override public void setWriteSynchronicity(Synchronicity writeSynchronicity) { this.writeSynchronicity = writeSynchronicity; } + @Override public void setFlushSeverity(Severity flushSeverity) { this.flushSeverity = flushSeverity; } + @Override public Synchronicity getWriteSynchronicity() { return writeSynchronicity; } + @Override public Severity getFlushSeverity() { return flushSeverity; } @@ -149,7 +154,7 @@ private static V get(ApiFuture future) { return Uninterruptibles.getUninterruptibly(future); } catch (ExecutionException ex) { Throwables.throwIfUnchecked(ex.getCause()); - throw new RuntimeException(ex); + throw new VerifyException(ex); } } @@ -355,7 +360,7 @@ public AsyncPage apply(ListSinksResponse listSinksResponse) { listSinksResponse.getSinksList(), Sink.fromPbFunction(serviceOptions.getService())); String cursor = - listSinksResponse.getNextPageToken().equals("") + listSinksResponse.getNextPageToken().isEmpty() ? null : listSinksResponse.getNextPageToken(); return new AsyncPageImpl<>( @@ -386,7 +391,7 @@ public ApiFuture deleteSinkAsync(String sink) { .setSinkName( LogSinkName.ofProjectSinkName(getOptions().getProjectId(), sink).toString()) .build(); - return transform(rpc.delete(request), EMPTY_TO_BOOLEAN_FUNCTION); + return transform(rpc.delete(request), LoggingImpl::emptyToBooleanFunction); } /** @@ -427,7 +432,7 @@ public AsyncPage apply(ListLogsResponse listLogsResponse) { ? ImmutableList.of() : listLogsResponse.getLogNamesList(); String cursor = - listLogsResponse.getNextPageToken().equals("") + listLogsResponse.getNextPageToken().isEmpty() ? null : listLogsResponse.getNextPageToken(); return new AsyncPageImpl<>( @@ -446,6 +451,7 @@ public ApiFuture> listLogsAsync(ListOption... options) { return listLogsAsync(getOptions(), optionMap(options)); } + @Override public boolean deleteLog(String log) { return get(deleteLogAsync(log, null)); } @@ -455,6 +461,7 @@ public boolean deleteLog(String log, LogDestinationName destination) { return get(deleteLogAsync(log, destination)); } + @Override public ApiFuture deleteLogAsync(String log) { return deleteLogAsync(log, null); } @@ -468,7 +475,7 @@ public ApiFuture deleteLogAsync(String log, LogDestinationName destinat } LogName name = getLogName(projectId, log, destination); DeleteLogRequest request = DeleteLogRequest.newBuilder().setLogName(name.toString()).build(); - return transform(rpc.delete(request), EMPTY_TO_BOOLEAN_FUNCTION); + return transform(rpc.delete(request), LoggingImpl::emptyToBooleanFunction); } private static ListMonitoredResourceDescriptorsRequest listMonitoredResourceDescriptorsRequest( @@ -505,19 +512,13 @@ public AsyncPage apply( ? ImmutableList.of() : Lists.transform( listDescriptorsResponse.getResourceDescriptorsList(), - new Function< - com.google.api.MonitoredResourceDescriptor, - MonitoredResourceDescriptor>() { - @Override - public MonitoredResourceDescriptor apply( - com.google.api.MonitoredResourceDescriptor - monitoredResourceDescriptor) { - return MonitoredResourceDescriptor.FROM_PB_FUNCTION.apply( - monitoredResourceDescriptor); - } + (com.google.api.MonitoredResourceDescriptor + monitoredResourceDescriptor) -> { + return MonitoredResourceDescriptor.FROM_PB_FUNCTION.apply( + monitoredResourceDescriptor); }); String cursor = - listDescriptorsResponse.getNextPageToken().equals("") + listDescriptorsResponse.getNextPageToken().isEmpty() ? null : listDescriptorsResponse.getNextPageToken(); return new AsyncPageImpl<>( @@ -528,10 +529,12 @@ public MonitoredResourceDescriptor apply( }); } + @Override public Page listMonitoredResourceDescriptors(ListOption... options) { return get(listMonitoredResourceDescriptorsAsync(options)); } + @Override public ApiFuture> listMonitoredResourceDescriptorsAsync( ListOption... options) { return listMonitoredResourceDescriptorsAsync(getOptions(), optionMap(options)); @@ -613,7 +616,7 @@ public AsyncPage apply(ListLogMetricsResponse listMetricsResponse) { listMetricsResponse.getMetricsList(), Metric.fromPbFunction(serviceOptions.getService())); String cursor = - listMetricsResponse.getNextPageToken().equals("") + listMetricsResponse.getNextPageToken().isEmpty() ? null : listMetricsResponse.getNextPageToken(); return new AsyncPageImpl<>( @@ -643,7 +646,7 @@ public ApiFuture deleteMetricAsync(String metric) { DeleteLogMetricRequest.newBuilder() .setMetricName(LogMetricName.of(getOptions().getProjectId(), metric).toString()) .build(); - return transform(rpc.delete(request), EMPTY_TO_BOOLEAN_FUNCTION); + return transform(rpc.delete(request), LoggingImpl::emptyToBooleanFunction); } @Override @@ -702,7 +705,7 @@ public ApiFuture deleteExclusionAsync(String exclusion) { DeleteExclusionRequest.newBuilder() .setName(LogExclusionName.of(getOptions().getProjectId(), exclusion).toString()) .build(); - return transform(rpc.delete(request), EMPTY_TO_BOOLEAN_FUNCTION); + return transform(rpc.delete(request), LoggingImpl::emptyToBooleanFunction); } @Override @@ -746,7 +749,7 @@ public AsyncPage apply(ListExclusionsResponse listExclusionsResponse) listExclusionsResponse.getExclusionsList(), Exclusion.FROM_PROTOBUF_FUNCTION); String cursor = - listExclusionsResponse.getNextPageToken().equals("") + listExclusionsResponse.getNextPageToken().isEmpty() ? null : listExclusionsResponse.getNextPageToken(); return new AsyncPageImpl<>( @@ -795,12 +798,13 @@ private static WriteLogEntriesRequest writeLogEntriesRequest( return destination.toLogName(logName); } + @Override public Iterable populateMetadata( Iterable logEntries, MonitoredResource customResource, String... exclusionClassPaths) { checkNotNull(logEntries); - final Boolean needDebugInfo = + final boolean needDebugInfo = Iterables.any( logEntries, log -> log.getSeverity() == Severity.DEBUG && log.getSourceLocation() == null); @@ -812,7 +816,7 @@ public Iterable populateMetadata( customResource == null ? MonitoredResourceUtil.getResource(getOptions().getProjectId(), null) : customResource; - final Context context = (new ContextHandler()).getCurrentContext(); + final Context context = new ContextHandler().getCurrentContext(); final ArrayList populatedLogEntries = Lists.newArrayList(); // populate empty metadata fields of log entries before calling write API @@ -843,6 +847,7 @@ public Iterable populateMetadata( return populatedLogEntries; } + @Override public void write(Iterable logEntries, WriteOption... options) { if (inWriteCall.get() != null) { return; @@ -852,14 +857,15 @@ public void write(Iterable logEntries, WriteOption... options) { try { final Map writeOptions = optionMap(options); final Boolean loggingOptionsPopulateFlag = getOptions().getAutoPopulateMetadata(); - final Boolean writeOptionPopulateFlga = + final Boolean writeOptionPopulateFlag = WriteOption.OptionType.AUTO_POPULATE_METADATA.get(writeOptions); Tuple> pair = Instrumentation.populateInstrumentationInfo(logEntries); logEntries = pair.y(); - if (writeOptionPopulateFlga == Boolean.TRUE - || (writeOptionPopulateFlga == null && loggingOptionsPopulateFlag == Boolean.TRUE)) { + if (Objects.equals(writeOptionPopulateFlag, Boolean.TRUE) + || (writeOptionPopulateFlag == null + && Objects.equals(loggingOptionsPopulateFlag, Boolean.TRUE))) { final MonitoredResource sharedResourceMetadata = RESOURCE.get(writeOptions); logEntries = populateMetadata(logEntries, sharedResourceMetadata, this.getClass().getName()); @@ -881,6 +887,7 @@ public void write(Iterable logEntries, WriteOption... options) { } } + @Override public void flush() { // BUG(1795): We should force batcher to issue RPC call for buffered messages, // so the code below doesn't wait uselessly. @@ -889,7 +896,7 @@ public void flush() { try { ApiFutures.allAsList(writesToFlush).get(FLUSH_WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { - throw new RuntimeException(e); + throw new VerifyException(e); } } @@ -927,7 +934,6 @@ private void writeLogEntries(Iterable logEntries, WriteOption... write break; case ASYNC: - default: final ApiFuture writeFuture = writeAsync(logEntries, writeOptions); final Object pendingKey = new Object(); pendingWrites.put(pendingKey, writeFuture); @@ -997,7 +1003,7 @@ static ListLogEntriesRequest listLogEntriesRequest( // time filter // of 24 hours back to be inline with gcloud behavior for the same API if (filter != null) { - if (!filter.toLowerCase().contains("timestamp")) { + if (!Ascii.toLowerCase(filter).contains("timestamp")) { filter = String.format( "%s AND %s", filter, defaultTimestampFilterCreator.createDefaultTimestampFilter()); @@ -1029,7 +1035,7 @@ public AsyncPage apply(ListLogEntriesResponse listLogEntriesResponse) : Lists.transform( listLogEntriesResponse.getEntriesList(), LogEntry.FROM_PB_FUNCTION); String cursor = - listLogEntriesResponse.getNextPageToken().equals("") + listLogEntriesResponse.getNextPageToken().isEmpty() ? null : listLogEntriesResponse.getNextPageToken(); return new AsyncPageImpl<>( @@ -1078,7 +1084,7 @@ static TailLogEntriesRequest buildTailLogEntriesRequest( if (bufferWindow != null) { try { builder.setBufferWindow(Durations.parse(bufferWindow)); - } catch (java.text.ParseException err) { + } catch (ParseException err) { System.err.println("ERROR: invalid duration format: " + bufferWindow); } } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java index b1c8c4f8a..f32a59b20 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java @@ -38,6 +38,7 @@ * {@link java.util.logging.Level#WARNING}. {@code DEBUG} instead is lower than {@link * java.util.logging.Level#FINEST} but higher than {@link java.util.logging.Level#ALL}. */ +@SuppressWarnings("ShouldNotSubclass") public final class LoggingLevel extends Level { private static final long serialVersionUID = -6455416241709366337L; diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java index 65750f1c4..00d61cb0f 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java @@ -35,7 +35,7 @@ public class LoggingOptions extends ServiceOptions { private static final String API_SHORT_NAME = "Logging"; private static final String LOGGING_SCOPE = "https://www.googleapis.com/auth/logging.admin"; - private static final Set SCOPES = ImmutableSet.of(LOGGING_SCOPE); + private static final ImmutableSet SCOPES = ImmutableSet.of(LOGGING_SCOPE); private static final String DEFAULT_HOST = LoggingSettings.getDefaultEndpoint(); private static final long serialVersionUID = 5753499510627426717L; diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/MetadataLoader.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/MetadataLoader.java index 207283205..7e2e74f1d 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/MetadataLoader.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/MetadataLoader.java @@ -16,10 +16,11 @@ package com.google.cloud.logging; +import static java.nio.charset.StandardCharsets.UTF_8; + import com.google.cloud.logging.MonitoredResourceUtil.Label; import com.google.common.collect.ImmutableMap; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.function.Supplier; @@ -29,36 +30,36 @@ public final class MetadataLoader { public static final String ENV_FLEXIBLE = "flex"; public static final String ENV_STANDARD = "standard"; - private ResourceTypeEnvironmentGetter getter; + private final ResourceTypeEnvironmentGetter getter; private final ImmutableMap> labelResolvers = ImmutableMap.>builder() - .put(Label.ClusterName, () -> getClusterName()) - .put(Label.ConfigurationName, () -> getConfigName()) - .put(Label.ContainerName, () -> getContainerName()) - .put(Label.Env, () -> getEnv()) - .put(Label.FunctionName, () -> getFunctionName()) - .put(Label.InstanceId, () -> getInstanceId()) - .put(Label.InstanceName, () -> getInstanceName()) - .put(Label.CloudRunLocation, () -> getCloudRunLocation()) - .put(Label.GKELocation, () -> getGKELocation()) - .put(Label.ModuleId, () -> getModuleId()) - .put(Label.NamespaceName, () -> getNamespaceName()) - .put(Label.PodName, () -> getPodName()) - .put(Label.ProjectId, () -> getProjectId()) - .put(Label.Region, () -> getRegion()) - .put(Label.RevisionName, () -> getRevisionName()) - .put(Label.ServiceName, () -> getServiceName()) - .put(Label.VersionId, () -> getVersionId()) - .put(Label.Zone, () -> getZone()) - .build(); + .put(Label.ClusterName, this::getClusterName) + .put(Label.ConfigurationName, this::getConfigName) + .put(Label.ContainerName, this::getContainerName) + .put(Label.Env, this::getEnv) + .put(Label.FunctionName, this::getFunctionName) + .put(Label.InstanceId, this::getInstanceId) + .put(Label.InstanceName, this::getInstanceName) + .put(Label.CloudRunLocation, this::getCloudRunLocation) + .put(Label.GKELocation, this::getGKELocation) + .put(Label.ModuleId, this::getModuleId) + .put(Label.NamespaceName, this::getNamespaceName) + .put(Label.PodName, this::getPodName) + .put(Label.ProjectId, this::getProjectId) + .put(Label.Region, this::getRegion) + .put(Label.RevisionName, this::getRevisionName) + .put(Label.ServiceName, this::getServiceName) + .put(Label.VersionId, this::getVersionId) + .put(Label.Zone, this::getZone) + .buildOrThrow(); public MetadataLoader(ResourceTypeEnvironmentGetter getter) { this.getter = getter; } /** - * Loads metadata value for the {@link label} argument. + * Loads metadata value for the {@code label} argument. * * @param label A resource metadata label of type {@see MonitoredResourceUtil.Label} * @return A string with metadata value or {@code null} if the label is not supported. @@ -96,7 +97,7 @@ private String getContainerName() { */ private String getEnv() { String value = getter.getAttribute("instance/attributes/startup-script"); - if (value == "/var/lib/flex/startup_script.sh") { + if ("/var/lib/flex/startup_script.sh".equals(value)) { return ENV_FLEXIBLE; } return ENV_STANDARD; @@ -147,7 +148,7 @@ private String getNamespaceName() { new String( Files.readAllBytes( Paths.get("/var/run/secrets/kubernetes.io/serviceaccount/namespace")), - StandardCharsets.UTF_8); + UTF_8); } catch (IOException e) { // if SA token is not shared the info about namespace is unavailable // allow users to define the namespace name explicitly diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java index 2ab6ee130..adec4dce5 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.util.Objects; -import org.jspecify.nullness.Nullable; /** * Cloud Logging metrics describe logs-based metric. The value of the metric is the number of log @@ -104,7 +103,7 @@ public final boolean equals(Object obj) { if (obj == this) { return true; } - if (obj == null || !obj.getClass().equals(Metric.class)) { + if (!(obj instanceof Metric)) { return false; } Metric other = (Metric) obj; @@ -254,11 +253,8 @@ static Metric fromPb(Logging logging, LogMetric metricPb) { } static Function fromPbFunction(final Logging logging) { - return new Function() { - @Override - public @Nullable Metric apply(LogMetric metricPb) { - return metricPb != null ? fromPb(logging, metricPb) : null; - } + return (LogMetric metricPb) -> { + return metricPb != null ? fromPb(logging, metricPb) : null; }; } } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/MetricInfo.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/MetricInfo.java index 6d7835c27..5ae92df84 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/MetricInfo.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/MetricInfo.java @@ -167,7 +167,7 @@ public boolean equals(Object obj) { if (obj == this) { return true; } - if (obj == null || !(obj.getClass().equals(MetricInfo.class))) { + if (!(obj instanceof MetricInfo)) { return false; } return baseEquals((MetricInfo) obj); @@ -205,7 +205,7 @@ LogMetric toPb() { static MetricInfo fromPb(LogMetric metricPb) { Builder builder = newBuilder(metricPb.getName(), metricPb.getFilter()); - if (!metricPb.getDescription().equals("")) { + if (!metricPb.getDescription().isEmpty()) { builder.setDescription(metricPb.getDescription()); } return builder.build(); diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/MonitoredResourceUtil.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/MonitoredResourceUtil.java index 1efcd9e5b..263d915c2 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/MonitoredResourceUtil.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/MonitoredResourceUtil.java @@ -17,11 +17,10 @@ package com.google.cloud.logging; import com.google.cloud.MonitoredResource; -import com.google.cloud.logging.LogEntry.Builder; import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -209,10 +208,9 @@ private static List createEnhancers(Resource resourceType) { List enhancers = new ArrayList<>(2); if (resourceType == Resource.AppEngine) { enhancers.add(new TraceLoggingEnhancer(APPENGINE_LABEL_PREFIX)); - if (metadataLoader.getValue(Label.Env) == MetadataLoader.ENV_FLEXIBLE) { + if (MetadataLoader.ENV_FLEXIBLE.equals(metadataLoader.getValue(Label.Env))) { enhancers.add( - new LabelLoggingEnhancer( - APPENGINE_LABEL_PREFIX, Collections.singletonList(Label.InstanceName))); + new LabelLoggingEnhancer(APPENGINE_LABEL_PREFIX, ImmutableList.of(Label.InstanceName))); } } return enhancers; @@ -244,7 +242,7 @@ private static class LabelLoggingEnhancer implements LoggingEnhancer { } @Override - public void enhanceLogEntry(Builder logEntry) { + public void enhanceLogEntry(LogEntry.Builder logEntry) { for (Map.Entry label : labels.entrySet()) { logEntry.addLabel(label.getKey(), label.getValue()); } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Payload.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Payload.java index bd0d9b276..a80262f75 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Payload.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Payload.java @@ -179,7 +179,7 @@ public final boolean equals(Object obj) { if (obj == this) { return true; } - if (obj == null || !(obj instanceof Payload)) { + if (!(obj instanceof Payload)) { return false; } Payload other = (Payload) obj; @@ -209,9 +209,8 @@ static > T fromPb(com.google.logging.v2.LogEntry entryPb) { return (T) ProtoPayload.fromPb(entryPb); case PAYLOAD_NOT_SET: return null; - default: - // should never occur - throw new IllegalArgumentException("Unrecognized log entry payload"); } + // should never occur + throw new IllegalArgumentException("Unrecognized log entry payload"); } } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Severity.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Severity.java index 10640d44d..ed3967b58 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Severity.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Severity.java @@ -83,8 +83,9 @@ static Severity fromPb(LogSeverity severityPb) { return ALERT; case EMERGENCY: return EMERGENCY; - default: - throw new IllegalArgumentException(severityPb + " is not a valid severity"); + case UNRECOGNIZED: + break; } + throw new IllegalArgumentException(severityPb + " is not a valid severity"); } } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java index 2cdbabca1..2c5ed5241 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.util.Objects; -import org.jspecify.nullness.Nullable; /** * Cloud Logging sinks can be used to control the export of your logs. Each sink specifies the @@ -117,7 +116,7 @@ public final boolean equals(Object obj) { if (obj == this) { return true; } - if (obj == null || !obj.getClass().equals(Sink.class)) { + if (!(obj instanceof Sink)) { return false; } Sink other = (Sink) obj; @@ -267,11 +266,8 @@ static Sink fromPb(Logging logging, LogSink sinkPb) { } static Function fromPbFunction(final Logging logging) { - return new Function() { - @Override - public @Nullable Sink apply(LogSink sinkPb) { - return sinkPb != null ? fromPb(logging, sinkPb) : null; - } + return (LogSink sinkPb) -> { + return sinkPb != null ? fromPb(logging, sinkPb) : null; }; } } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/SinkInfo.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/SinkInfo.java index 0a8958509..b2a9bb97d 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/SinkInfo.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/SinkInfo.java @@ -440,7 +440,7 @@ final boolean baseEquals(Destination other) { } final int baseHashCode() { - return Objects.hash(type); + return Objects.hashCode(type); } abstract String toPb(String projectId); @@ -468,7 +468,7 @@ public enum VersionFormat { V1(LogSink.VersionFormat.V1), V2(LogSink.VersionFormat.V2); - private LogSink.VersionFormat versionPb; + private final LogSink.VersionFormat versionPb; VersionFormat(LogSink.VersionFormat versionPb) { this.versionPb = versionPb; @@ -486,9 +486,10 @@ LogSink.VersionFormat toPb() { return VersionFormat.V2; case VERSION_FORMAT_UNSPECIFIED: return null; - default: - throw new IllegalArgumentException(versionPb + " is not a valid version"); + case UNRECOGNIZED: + break; } + throw new IllegalArgumentException(versionPb + " is not a valid version"); } } @@ -665,7 +666,7 @@ public boolean equals(Object obj) { if (obj == this) { return true; } - if (obj == null || !(obj.getClass().equals(SinkInfo.class))) { + if (!(obj instanceof SinkInfo)) { return false; } return baseEquals((SinkInfo) obj); @@ -706,7 +707,7 @@ static SinkInfo fromPb(LogSink sinkPb) { Builder builder = newBuilder(sinkPb.getName(), Destination.fromPb(sinkPb.getDestination())) .setVersionFormat(VersionFormat.fromPb(LogSink.VersionFormat.V2)); - if (!sinkPb.getFilter().equals("")) { + if (!sinkPb.getFilter().isEmpty()) { builder.setFilter(sinkPb.getFilter()); } return builder.build(); diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/SourceLocation.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/SourceLocation.java index 2e7dc1094..966ea63ef 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/SourceLocation.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/SourceLocation.java @@ -16,12 +16,13 @@ package com.google.cloud.logging; +import static java.util.Arrays.stream; + import com.google.api.client.util.Strings; import com.google.common.base.MoreObjects; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.logging.v2.LogEntrySourceLocation; import java.io.Serializable; -import java.util.Arrays; import java.util.Objects; import org.jspecify.nullness.Nullable; @@ -174,7 +175,7 @@ static SourceLocation fromPb(LogEntrySourceLocation sourceLocationPb) { * number information. */ static @Nullable SourceLocation fromCurrentContext(String... exclusionClassPaths) { - StackTraceElement[] stackTrace = (new Exception()).getStackTrace(); + StackTraceElement[] stackTrace = new Exception().getStackTrace(); for (int level = 1; level < stackTrace.length; level++) { StackTraceElement ste = stackTrace[level]; @@ -182,7 +183,7 @@ static SourceLocation fromPb(LogEntrySourceLocation sourceLocationPb) { if (exclusionClassPaths != null) { if (Strings.isNullOrEmpty(className) - || Arrays.stream(exclusionClassPaths) + || stream(exclusionClassPaths) .anyMatch(prefix -> prefix != null && className.startsWith(prefix))) { continue; } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Structs.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Structs.java index 9d223c13a..884e6ff08 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Structs.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Structs.java @@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.api.client.util.Types; -import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; @@ -41,21 +40,6 @@ */ final class Structs { - private static final Function VALUE_TO_OBJECT = - new Function() { - @Override - public Object apply(Value value) { - return valueToObject(value); - } - }; - private static final Function OBJECT_TO_VALUE = - new Function() { - @Override - public Value apply(Object obj) { - return objectToValue(obj); - } - }; - private Structs() {} /** @@ -72,15 +56,10 @@ private StructMap(Struct struct) { private static final class StructSet extends AbstractSet> { - private static final Function, Map.Entry> - VALUE_TO_OBJECT = - new Function, Map.Entry>() { - @Override - public Map.Entry apply(Map.Entry entry) { - return new AbstractMap.SimpleEntry<>( - entry.getKey(), valueToObject(entry.getValue())); - } - }; + private static Entry valueToObject(Entry entry) { + return new AbstractMap.SimpleEntry<>( + entry.getKey(), Structs.valueToObject(entry.getValue())); + } private final Struct struct; @@ -90,7 +69,8 @@ private StructSet(Struct struct) { @Override public Iterator> iterator() { - return Iterators.transform(struct.getFieldsMap().entrySet().iterator(), VALUE_TO_OBJECT); + return Iterators.transform( + struct.getFieldsMap().entrySet().iterator(), StructSet::valueToObject); } @Override @@ -117,7 +97,7 @@ static Map asMap(Struct struct) { * are serialized as strings. */ static Struct newStruct(Map map) { - Map valueMap = Maps.transformValues(checkNotNull(map), OBJECT_TO_VALUE); + Map valueMap = Maps.transformValues(checkNotNull(map), Structs::objectToValue); return Struct.newBuilder().putAllFields(valueMap).build(); } @@ -134,7 +114,7 @@ static Struct newStruct(Map map) { case STRUCT_VALUE: return new StructMap(value.getStructValue()); case LIST_VALUE: - return Lists.transform(value.getListValue().getValuesList(), VALUE_TO_OBJECT); + return Lists.transform(value.getListValue().getValuesList(), Structs::valueToObject); default: throw new IllegalArgumentException(String.format("Unsupported protobuf value %s", value)); } @@ -157,7 +137,7 @@ private static Value objectToValue(final Object obj) { } else if (obj instanceof Iterable || objClass.isArray()) { builder.setListValue( ListValue.newBuilder() - .addAllValues(Iterables.transform(Types.iterableOf(obj), OBJECT_TO_VALUE))); + .addAllValues(Iterables.transform(Types.iterableOf(obj), Structs::objectToValue))); } else if (objClass.isEnum()) { builder.setStringValue(((Enum) obj).name()); } else if (obj instanceof Map) { diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/TraceLoggingEnhancer.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/TraceLoggingEnhancer.java index f1593eb8a..8b7b4aea7 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/TraceLoggingEnhancer.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/TraceLoggingEnhancer.java @@ -48,7 +48,7 @@ public static String getCurrentTraceId() { } @Override - public void enhanceLogEntry(com.google.cloud.logging.LogEntry.Builder builder) { + public void enhanceLogEntry(LogEntry.Builder builder) { String traceId = getCurrentTraceId(); if (traceId != null) { builder.setTrace(traceId); diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/GrpcLoggingRpc.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/GrpcLoggingRpc.java index 05812d670..ffd6b99d0 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/GrpcLoggingRpc.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/GrpcLoggingRpc.java @@ -32,7 +32,6 @@ import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.TransportChannel; import com.google.api.gax.rpc.UnaryCallSettings; -import com.google.api.gax.rpc.UnaryCallSettings.Builder; import com.google.cloud.NoCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.grpc.GrpcTransportOptions; @@ -45,6 +44,7 @@ import com.google.cloud.logging.v2.LoggingSettings; import com.google.cloud.logging.v2.MetricsClient; import com.google.cloud.logging.v2.MetricsSettings; +import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.MoreExecutors; import com.google.logging.v2.CreateExclusionRequest; import com.google.logging.v2.CreateLogMetricRequest; @@ -148,7 +148,7 @@ public GrpcLoggingRpc(final LoggingOptions options) throws IOException { clientContext = ClientContext.create(settingsBuilder.build()); } ApiFunction, Void> retrySettingsSetter = - new ApiFunction, Void>() { + new ApiFunction, Void>() { @Override public Void apply(UnaryCallSettings.Builder builder) { builder.setRetrySettings(options.getRetrySettings()); @@ -193,7 +193,7 @@ private static ApiFuture translate(ApiFuture from, StatusCode.Code... if (returnNullOn.length > 0) { returnNullOnSet = EnumSet.of(returnNullOn[0], returnNullOn); } else { - returnNullOnSet = Collections.emptySet(); + returnNullOnSet = ImmutableSet.of(); } return ApiFutures.catching( from, diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java index b337811b0..db05fdb1c 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java @@ -58,8 +58,7 @@ public LoggingOptions getOptions() { * @throws com.google.cloud.logging.testing.RemoteLoggingHelper.LoggingHelperException if {@code * keyStream} is not a valid JSON key stream */ - public static RemoteLoggingHelper create(String projectId, InputStream keyStream) - throws LoggingHelperException { + public static RemoteLoggingHelper create(String projectId, InputStream keyStream) { try { GrpcTransportOptions transportOptions = LoggingOptions.getDefaultGrpcTransportOptions(); LoggingOptions storageOptions = @@ -82,7 +81,7 @@ public static RemoteLoggingHelper create(String projectId, InputStream keyStream * Creates a {@code RemoteLoggingHelper} object using default project id and authentication * credentials. */ - public static RemoteLoggingHelper create() throws LoggingHelperException { + public static RemoteLoggingHelper create() { GrpcTransportOptions transportOptions = LoggingOptions.getDefaultGrpcTransportOptions(); LoggingOptions loggingOptions = LoggingOptions.newBuilder() @@ -97,7 +96,7 @@ public static RemoteLoggingHelper create() throws LoggingHelperException { * name. */ public static String formatForTest(String name) { - return name + "-" + UUID.randomUUID().toString(); + return name + "-" + UUID.randomUUID(); } private static RetrySettings retrySettings() { diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/AutoPopulateMetadataTests.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/AutoPopulateMetadataTests.java index ea53c7914..f415f8c4c 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/AutoPopulateMetadataTests.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/AutoPopulateMetadataTests.java @@ -63,7 +63,7 @@ public class AutoPopulateMetadataTests { .setDestination(LogDestinationName.project(LOGGING_PROJECT_ID)) .build(); private static final WriteLogEntriesResponse EMPTY_WRITE_RESPONSE = - WriteLogEntriesResponse.newBuilder().build(); + WriteLogEntriesResponse.getDefaultInstance(); private static final HttpRequest HTTP_REQUEST = HttpRequest.newBuilder() .setRequestMethod(RequestMethod.GET) @@ -78,7 +78,7 @@ public class AutoPopulateMetadataTests { private LoggingRpcFactory mockedRpcFactory; private LoggingRpc mockedRpc; private Logging logging; - private Capture rpcWriteArgument = newCapture(); + private final Capture rpcWriteArgument = newCapture(); private ResourceTypeEnvironmentGetter mockedEnvGetter; @Before @@ -108,13 +108,13 @@ public void setup() { @After public void teardown() { - (new ContextHandler()).removeCurrentContext(); + new ContextHandler().removeCurrentContext(); } private void mockCurrentContext(HttpRequest request, String traceId, String spanId) { Context mockedContext = Context.newBuilder().setRequest(request).setTraceId(traceId).setSpanId(spanId).build(); - (new ContextHandler()).setCurrentContext(mockedContext); + new ContextHandler().setCurrentContext(mockedContext); } @Test @@ -169,7 +169,7 @@ public void testSourceLocationPopulation() { assertEquals(expected.getFile(), actual.getSourceLocation().getFile()); assertEquals(expected.getClass(), actual.getSourceLocation().getClass()); assertEquals(expected.getFunction(), actual.getSourceLocation().getFunction()); - assertEquals(new Long(expected.getLine() + 1), actual.getSourceLocation().getLine()); + assertEquals(Long.valueOf(expected.getLine() + 1), actual.getSourceLocation().getLine()); } @Test diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/ContextTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/ContextTest.java index ae44b7cbc..512c99aa8 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/ContextTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/ContextTest.java @@ -20,7 +20,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; @@ -92,8 +91,8 @@ public void testCompareContexts() { assertNotEquals(TEST_CONTEXT, context1); assertFalse(TEST_CONTEXT.hashCode() == context1.hashCode()); - assertTrue(TEST_CONTEXT.equals(context2)); - assertTrue(TEST_CONTEXT.hashCode() == context2.hashCode()); + assertEquals(context2, TEST_CONTEXT); + assertEquals(context2.hashCode(), TEST_CONTEXT.hashCode()); } @Test diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/InstrumentationTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/InstrumentationTest.java index 6b942d7bd..e1e00bc0a 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/InstrumentationTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/InstrumentationTest.java @@ -16,11 +16,12 @@ package com.google.cloud.logging; +import static org.junit.Assert.assertSame; + import com.google.api.client.util.Lists; import com.google.cloud.Tuple; import com.google.cloud.logging.Payload.JsonPayload; import com.google.cloud.logging.Payload.StringPayload; -import com.google.cloud.logging.Payload.Type; import com.google.common.collect.ImmutableList; import com.google.protobuf.ListValue; import com.google.protobuf.Value; @@ -28,7 +29,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Test; @@ -62,7 +62,7 @@ public void testNoInstrumentationGenerated() { ArrayList entries = Lists.newArrayList(pair.y()); Assert.assertFalse(pair.x()); Assert.assertEquals(1, entries.size()); - Assert.assertTrue(entries.get(0).getPayload().getType() == Type.STRING); + assertSame(Payload.Type.STRING, entries.get(0).getPayload().getType()); } @Test @@ -102,7 +102,7 @@ public static JsonPayload generateInstrumentationPayload( Map info = new HashMap<>(); info.put(Instrumentation.INSTRUMENTATION_NAME_KEY, libraryName); info.put(Instrumentation.INSTRUMENTATION_VERSION_KEY, libraryVersion); - List list = ImmutableList.of(info); + ImmutableList list = ImmutableList.of(info); instrumentation_data.put(Instrumentation.INSTRUMENTATION_SOURCE_KEY, list); json_data.put(Instrumentation.DIAGNOSTIC_INFO_KEY, instrumentation_data); return JsonPayload.of(json_data); @@ -117,7 +117,7 @@ private static void verifyEntries( ArrayList entries = Lists.newArrayList(pair.y()); Assert.assertTrue(pair.x()); Assert.assertEquals(expected, entries.size()); - Assert.assertTrue(entries.get(index).getPayload().getType() == Type.JSON); + assertSame(Payload.Type.JSON, entries.get(index).getPayload().getType()); ListValue infoList = entries .get(index) diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/InvalidContextTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/InvalidContextTest.java index 4ae5cd063..538766d47 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/InvalidContextTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/InvalidContextTest.java @@ -16,8 +16,10 @@ package com.google.cloud.logging; +import static org.junit.Assert.assertThrows; + import java.util.Arrays; -import java.util.Collection; +import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -26,7 +28,7 @@ @RunWith(Parameterized.class) public class InvalidContextTest { @Parameters - public static Collection data() { + public static List data() { final String[] INVALID_W3C_TRACE_CONTEXTS = { "", "abc/efg", @@ -49,9 +51,10 @@ public InvalidContextTest(String traceContext) { this.traceContext = traceContext; } - @Test(expected = IllegalArgumentException.class) + @Test public void testAssertionInvalidContext() { Context.Builder builder = Context.newBuilder(); - builder.loadW3CTraceParentContext(traceContext); + assertThrows( + IllegalArgumentException.class, () -> builder.loadW3CTraceParentContext(traceContext)); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LogEntryTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LogEntryTest.java index 43d5e3f20..2379fc189 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LogEntryTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LogEntryTest.java @@ -19,17 +19,18 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import com.google.cloud.MonitoredResource; import com.google.cloud.logging.Payload.JsonPayload; import com.google.cloud.logging.Payload.ProtoPayload; import com.google.cloud.logging.Payload.StringPayload; import com.google.common.collect.ImmutableMap; +import com.google.common.testing.EqualsTester; import com.google.gson.JsonParser; import com.google.protobuf.Any; import com.google.protobuf.Empty; import java.time.Instant; -import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -53,7 +54,7 @@ public class LogEntryTest { .setRequestMethod(HttpRequest.RequestMethod.GET) .setStatus(404) .build(); - private static final Map LABELS = + private static final ImmutableMap LABELS = ImmutableMap.of("key1", "value1", "key2", "value2"); private static final Operation OPERATION = Operation.of("id", "producer"); private static final String TRACE = "trace"; @@ -341,17 +342,18 @@ public void testToAndFromPb() { compareLogEntry(logEntry, LogEntry.fromPb(logEntry.toPb(PROJECT)), true); } - @Test(expected = AssertionError.class) + @Test public void testToAndFromPbWithExpectedFailure() { LogEntry logEntry = LogEntry.newBuilder(STRING_PAYLOAD).setLogName(LOG_NAME).setResource(RESOURCE).build(); - compareLogEntry(logEntry, LogEntry.fromPb(logEntry.toPb(PROJECT)), true); + assertThrows( + AssertionError.class, + () -> compareLogEntry(logEntry, LogEntry.fromPb(logEntry.toPb(PROJECT)), true)); } - private void compareLogEntry(LogEntry expected, LogEntry value, Boolean extraValidations) { + private void compareLogEntry(LogEntry expected, LogEntry value, boolean extraValidations) { if (extraValidations) { - assertEquals(expected.hashCode(), value.hashCode()); - assertEquals(expected, value); + new EqualsTester().addEqualityGroup(expected, value).testEquals(); } assertEquals(expected.getLogName(), value.getLogName()); assertEquals(expected.getResource(), value.getResource()); @@ -388,8 +390,8 @@ public void testStructureLogPresentations() { } } - @Test(expected = UnsupportedOperationException.class) + @Test public void testStructureLogPresentationWithProtobufPayload() { - PROTO_ENTRY.toStructuredJsonString(); + assertThrows(UnsupportedOperationException.class, () -> PROTO_ENTRY.toStructuredJsonString()); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java index 69c87eff1..c1e3f3d48 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java @@ -22,19 +22,17 @@ import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.google.api.client.util.Strings; import com.google.cloud.MonitoredResource; -import com.google.cloud.logging.LogEntry.Builder; import com.google.cloud.logging.Logging.WriteOption; import com.google.cloud.logging.Payload.StringPayload; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import java.util.Collections; import java.util.logging.ErrorManager; import java.util.logging.Filter; import java.util.logging.Formatter; @@ -233,7 +231,7 @@ public void testDefaultHandlerCreation() { String oldProject = System.getProperty(PROJECT_ENV_NAME); System.setProperty(PROJECT_ENV_NAME, PROJECT); replay(options, logging); - assertNotNull(new LoggingHandler()); + LoggingHandler unused = new LoggingHandler(); if (oldProject != null) { System.setProperty(PROJECT_ENV_NAME, oldProject); } else { @@ -365,13 +363,12 @@ public void testEnhancedLogEntry() { LoggingEnhancer enhancer = new LoggingEnhancer() { @Override - public void enhanceLogEntry(Builder builder) { + public void enhanceLogEntry(LogEntry.Builder builder) { builder.addLabel("enhanced", "true"); } }; Handler handler = - new LoggingHandler( - LOG_NAME, options, DEFAULT_RESOURCE, Collections.singletonList(enhancer)); + new LoggingHandler(LOG_NAME, options, DEFAULT_RESOURCE, ImmutableList.of(enhancer)); handler.setLevel(Level.ALL); handler.setFormatter(new TestFormatter()); handler.publish(newLogRecord(Level.FINEST, MESSAGE)); @@ -389,13 +386,12 @@ public void testEnhancedLogEntryPrintToStdout() { LoggingEnhancer enhancer = new LoggingEnhancer() { @Override - public void enhanceLogEntry(Builder builder) { + public void enhanceLogEntry(LogEntry.Builder builder) { builder.addLabel("enhanced", "true"); } }; LoggingHandler handler = - new LoggingHandler( - LOG_NAME, options, DEFAULT_RESOURCE, Collections.singletonList(enhancer)); + new LoggingHandler(LOG_NAME, options, DEFAULT_RESOURCE, ImmutableList.of(enhancer)); handler.setLevel(Level.ALL); handler.setFormatter(new TestFormatter()); handler.setRedirectToStdout(true); @@ -413,8 +409,7 @@ public void testTraceEnhancedLogEntry() { LoggingEnhancer enhancer = new TraceLoggingEnhancer(); TraceLoggingEnhancer.setCurrentTraceId("projects/projectId/traces/traceId"); Handler handler = - new LoggingHandler( - LOG_NAME, options, DEFAULT_RESOURCE, Collections.singletonList(enhancer)); + new LoggingHandler(LOG_NAME, options, DEFAULT_RESOURCE, ImmutableList.of(enhancer)); handler.setLevel(Level.ALL); handler.setFormatter(new TestFormatter()); handler.publish(newLogRecord(Level.FINEST, MESSAGE)); @@ -617,7 +612,7 @@ public void testRedirectToStdoutEnabled() { handler.setRedirectToStdout(true); handler.publish(newLogRecord(Level.INFO, MESSAGE)); - assertTrue(null, !Strings.isNullOrEmpty(bout.toString())); + assertFalse(null, Strings.isNullOrEmpty(bout.toString())); System.setOut(null); } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java index 052d8ebb8..1bea68495 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java @@ -42,7 +42,6 @@ import com.google.cloud.logging.SinkInfo.Destination; import com.google.cloud.logging.spi.LoggingRpcFactory; import com.google.cloud.logging.spi.v2.LoggingRpc; -import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; @@ -80,7 +79,6 @@ import com.google.protobuf.Empty; import com.google.protobuf.Timestamp; import java.util.List; -import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import org.easymock.EasyMock; @@ -166,30 +164,19 @@ public class LoggingImplTest { .build(); private static final LogEntry LOG_ENTRY_EMPTY = LogEntry.newBuilder(StringPayload.of("entry-empty")).build(); - private static final Function SINK_TO_PB_FUNCTION = - new Function() { - @Override - public LogSink apply(SinkInfo sinkInfo) { - return sinkInfo.toPb(PROJECT); - } - }; - private static final Function METRIC_TO_PB_FUNCTION = - new Function() { - @Override - public LogMetric apply(MetricInfo metricInfo) { - return metricInfo.toPb(); - } - }; - private static final Function< - MonitoredResourceDescriptor, com.google.api.MonitoredResourceDescriptor> - DESCRIPTOR_TO_PB_FUNCTION = - new Function() { - @Override - public com.google.api.MonitoredResourceDescriptor apply( - MonitoredResourceDescriptor descriptor) { - return descriptor.toPb(); - } - }; + + private static LogSink sinkToPbFunction(SinkInfo sinkInfo) { + return sinkInfo.toPb(PROJECT); + } + + private static LogMetric metricToPbFunction(MetricInfo metricInfo) { + return metricInfo.toPb(); + } + + private static com.google.api.MonitoredResourceDescriptor descriptorToPbFunction( + MonitoredResourceDescriptor descriptor) { + return descriptor.toPb(); + } private static final String EXCLUSION_NAME = "load-balancer-exclusion"; private static final String EXCLUSION_NAME_PB = @@ -438,14 +425,14 @@ public void testListSinks() { EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List sinkList = + ImmutableList sinkList = ImmutableList.of( new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); ListSinksResponse response = ListSinksResponse.newBuilder() .setNextPageToken(cursor) - .addAllSinks(Lists.transform(sinkList, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList, LoggingImplTest::sinkToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -463,21 +450,22 @@ public void testListSinksNextPage() { ListSinksRequest request1 = ListSinksRequest.newBuilder().setParent(PROJECT_PARENT).build(); ListSinksRequest request2 = ListSinksRequest.newBuilder().setParent(PROJECT_PARENT).setPageToken(cursor1).build(); - List sinkList1 = + ImmutableList sinkList1 = ImmutableList.of( new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); - List sinkList2 = ImmutableList.of(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); + ImmutableList sinkList2 = + ImmutableList.of(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); ListSinksResponse response1 = ListSinksResponse.newBuilder() .setNextPageToken(cursor1) - .addAllSinks(Lists.transform(sinkList1, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList1, LoggingImplTest::sinkToPbFunction)) .build(); String cursor2 = "nextCursor"; ListSinksResponse response2 = ListSinksResponse.newBuilder() .setNextPageToken(cursor2) - .addAllSinks(Lists.transform(sinkList2, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList2, LoggingImplTest::sinkToPbFunction)) .build(); ApiFuture futureResponse1 = ApiFutures.immediateFuture(response1); ApiFuture futureResponse2 = ApiFutures.immediateFuture(response2); @@ -497,11 +485,11 @@ public void testListSinksEmpty() { EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List sinkList = ImmutableList.of(); + ImmutableList sinkList = ImmutableList.of(); ListSinksResponse response = ListSinksResponse.newBuilder() .setNextPageToken("") - .addAllSinks(Lists.transform(sinkList, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList, LoggingImplTest::sinkToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -523,14 +511,14 @@ public void testListSinksWithOptions() { .setPageSize(42) .setParent(PROJECT_PARENT) .build(); - List sinkList = + ImmutableList sinkList = ImmutableList.of( new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); ListSinksResponse response = ListSinksResponse.newBuilder() .setNextPageToken(cursor) - .addAllSinks(Lists.transform(sinkList, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList, LoggingImplTest::sinkToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -546,14 +534,14 @@ public void testListSinksAsync() throws ExecutionException, InterruptedException EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List sinkList = + ImmutableList sinkList = ImmutableList.of( new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); ListSinksResponse response = ListSinksResponse.newBuilder() .setNextPageToken(cursor) - .addAllSinks(Lists.transform(sinkList, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList, LoggingImplTest::sinkToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -571,21 +559,22 @@ public void testListSinksAsyncNextPage() throws ExecutionException, InterruptedE ListSinksRequest request1 = ListSinksRequest.newBuilder().setParent(PROJECT_PARENT).build(); ListSinksRequest request2 = ListSinksRequest.newBuilder().setParent(PROJECT_PARENT).setPageToken(cursor1).build(); - List sinkList1 = + ImmutableList sinkList1 = ImmutableList.of( new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); - List sinkList2 = ImmutableList.of(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); + ImmutableList sinkList2 = + ImmutableList.of(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); ListSinksResponse response1 = ListSinksResponse.newBuilder() .setNextPageToken(cursor1) - .addAllSinks(Lists.transform(sinkList1, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList1, LoggingImplTest::sinkToPbFunction)) .build(); String cursor2 = "nextCursor"; ListSinksResponse response2 = ListSinksResponse.newBuilder() .setNextPageToken(cursor2) - .addAllSinks(Lists.transform(sinkList2, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList2, LoggingImplTest::sinkToPbFunction)) .build(); ApiFuture futureResponse1 = ApiFutures.immediateFuture(response1); ApiFuture futureResponse2 = ApiFutures.immediateFuture(response2); @@ -605,11 +594,11 @@ public void testListSinksAsyncEmpty() throws ExecutionException, InterruptedExce EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List sinkList = ImmutableList.of(); + ImmutableList sinkList = ImmutableList.of(); ListSinksResponse response = ListSinksResponse.newBuilder() .setNextPageToken("") - .addAllSinks(Lists.transform(sinkList, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList, LoggingImplTest::sinkToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -631,14 +620,14 @@ public void testListSinksWithOptionsAsync() throws ExecutionException, Interrupt .setPageSize(42) .setParent(PROJECT_PARENT) .build(); - List sinkList = + ImmutableList sinkList = ImmutableList.of( new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO))); ListSinksResponse response = ListSinksResponse.newBuilder() .setNextPageToken(cursor) - .addAllSinks(Lists.transform(sinkList, SINK_TO_PB_FUNCTION)) + .addAllSinks(Lists.transform(sinkList, LoggingImplTest::sinkToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -800,14 +789,14 @@ public void testListMetrics() { logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List sinkList = + ImmutableList sinkList = ImmutableList.of( new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO))); ListLogMetricsResponse response = ListLogMetricsResponse.newBuilder() .setNextPageToken(cursor) - .addAllMetrics(Lists.transform(sinkList, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList, LoggingImplTest::metricToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -826,22 +815,22 @@ public void testListMetricsNextPage() { ListLogMetricsRequest.newBuilder().setParent(PROJECT_PARENT).build(); ListLogMetricsRequest request2 = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PARENT).setPageToken(cursor1).build(); - List sinkList1 = + ImmutableList sinkList1 = ImmutableList.of( new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO))); - List sinkList2 = + ImmutableList sinkList2 = ImmutableList.of(new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO))); ListLogMetricsResponse response1 = ListLogMetricsResponse.newBuilder() .setNextPageToken(cursor1) - .addAllMetrics(Lists.transform(sinkList1, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList1, LoggingImplTest::metricToPbFunction)) .build(); String cursor2 = "nextCursor"; ListLogMetricsResponse response2 = ListLogMetricsResponse.newBuilder() .setNextPageToken(cursor2) - .addAllMetrics(Lists.transform(sinkList2, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList2, LoggingImplTest::metricToPbFunction)) .build(); ApiFuture futureResponse1 = ApiFutures.immediateFuture(response1); ApiFuture futureResponse2 = ApiFutures.immediateFuture(response2); @@ -862,11 +851,11 @@ public void testListMetricsEmpty() { logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List sinkList = ImmutableList.of(); + ImmutableList sinkList = ImmutableList.of(); ListLogMetricsResponse response = ListLogMetricsResponse.newBuilder() .setNextPageToken("") - .addAllMetrics(Lists.transform(sinkList, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList, LoggingImplTest::metricToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -888,14 +877,14 @@ public void testListMetricsWithOptions() { .setPageSize(42) .setParent(PROJECT_PARENT) .build(); - List sinkList = + ImmutableList sinkList = ImmutableList.of( new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO))); ListLogMetricsResponse response = ListLogMetricsResponse.newBuilder() .setNextPageToken(cursor) - .addAllMetrics(Lists.transform(sinkList, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList, LoggingImplTest::metricToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -912,14 +901,14 @@ public void testListMetricsAsync() throws ExecutionException, InterruptedExcepti logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List sinkList = + ImmutableList sinkList = ImmutableList.of( new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO))); ListLogMetricsResponse response = ListLogMetricsResponse.newBuilder() .setNextPageToken(cursor) - .addAllMetrics(Lists.transform(sinkList, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList, LoggingImplTest::metricToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -938,22 +927,22 @@ public void testListMetricsAsyncNextPage() throws ExecutionException, Interrupte ListLogMetricsRequest.newBuilder().setParent(PROJECT_PARENT).build(); ListLogMetricsRequest request2 = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PARENT).setPageToken(cursor1).build(); - List sinkList1 = + ImmutableList sinkList1 = ImmutableList.of( new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO))); - List sinkList2 = + ImmutableList sinkList2 = ImmutableList.of(new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO))); ListLogMetricsResponse response1 = ListLogMetricsResponse.newBuilder() .setNextPageToken(cursor1) - .addAllMetrics(Lists.transform(sinkList1, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList1, LoggingImplTest::metricToPbFunction)) .build(); String cursor2 = "nextCursor"; ListLogMetricsResponse response2 = ListLogMetricsResponse.newBuilder() .setNextPageToken(cursor2) - .addAllMetrics(Lists.transform(sinkList2, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList2, LoggingImplTest::metricToPbFunction)) .build(); ApiFuture futureResponse1 = ApiFutures.immediateFuture(response1); ApiFuture futureResponse2 = ApiFutures.immediateFuture(response2); @@ -974,11 +963,11 @@ public void testListMetricsAsyncEmpty() throws ExecutionException, InterruptedEx logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List sinkList = ImmutableList.of(); + ImmutableList sinkList = ImmutableList.of(); ListLogMetricsResponse response = ListLogMetricsResponse.newBuilder() .setNextPageToken("") - .addAllMetrics(Lists.transform(sinkList, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList, LoggingImplTest::metricToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -1000,14 +989,14 @@ public void testListMetricsWithOptionsAsync() throws ExecutionException, Interru .setPageSize(42) .setParent(PROJECT_PARENT) .build(); - List sinkList = + ImmutableList sinkList = ImmutableList.of( new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO))); ListLogMetricsResponse response = ListLogMetricsResponse.newBuilder() .setNextPageToken(cursor) - .addAllMetrics(Lists.transform(sinkList, METRIC_TO_PB_FUNCTION)) + .addAllMetrics(Lists.transform(sinkList, LoggingImplTest::metricToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); @@ -1206,7 +1195,7 @@ public void testListExclusions() { logging = options.getService(); ListExclusionsRequest request = ListExclusionsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List exclusionList = + ImmutableList exclusionList = ImmutableList.of( Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER), Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER)); @@ -1230,7 +1219,7 @@ public void testListExclusionEmpty() { logging = options.getService(); ListExclusionsRequest request = ListExclusionsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List exclusionList = ImmutableList.of(); + ImmutableList exclusionList = ImmutableList.of(); ListExclusionsResponse response = ListExclusionsResponse.newBuilder() .setNextPageToken("") @@ -1252,7 +1241,7 @@ public void testListExclusionNextPage() { logging = options.getService(); ListExclusionsRequest request1 = ListExclusionsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List exclusionList1 = + ImmutableList exclusionList1 = ImmutableList.of(Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER)); ListExclusionsResponse response1 = ListExclusionsResponse.newBuilder() @@ -1261,7 +1250,7 @@ public void testListExclusionNextPage() { .build(); ListExclusionsRequest request2 = ListExclusionsRequest.newBuilder().setParent(PROJECT_PARENT).setPageToken(CURSOR).build(); - List exclusionList2 = + ImmutableList exclusionList2 = ImmutableList.of(Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER)); ListExclusionsResponse response2 = ListExclusionsResponse.newBuilder() @@ -1293,7 +1282,7 @@ public void testListExclusionWithOptions() { .setPageSize(42) .setParent(PROJECT_PARENT) .build(); - List exclusionList = + ImmutableList exclusionList = ImmutableList.of( Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER), Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER)); @@ -1318,7 +1307,7 @@ public void testListExclusionsAsync() throws ExecutionException, InterruptedExce logging = options.getService(); ListExclusionsRequest request = ListExclusionsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List exclusionList = + ImmutableList exclusionList = ImmutableList.of( Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER), Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER)); @@ -1342,7 +1331,7 @@ public void testListExclusionAsyncEmpty() throws ExecutionException, Interrupted logging = options.getService(); ListExclusionsRequest request = ListExclusionsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List exclusionList = ImmutableList.of(); + ImmutableList exclusionList = ImmutableList.of(); ListExclusionsResponse response = ListExclusionsResponse.newBuilder() .setNextPageToken("") @@ -1364,7 +1353,7 @@ public void testListExclusionAsyncNextPage() throws ExecutionException, Interrup logging = options.getService(); ListExclusionsRequest request1 = ListExclusionsRequest.newBuilder().setParent(PROJECT_PARENT).build(); - List exclusionList1 = + ImmutableList exclusionList1 = ImmutableList.of(Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER)); ListExclusionsResponse response1 = ListExclusionsResponse.newBuilder() @@ -1373,7 +1362,7 @@ public void testListExclusionAsyncNextPage() throws ExecutionException, Interrup .build(); ListExclusionsRequest request2 = ListExclusionsRequest.newBuilder().setParent(PROJECT_PARENT).setPageToken(CURSOR).build(); - List exclusionList2 = + ImmutableList exclusionList2 = ImmutableList.of(Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER)); ListExclusionsResponse response2 = ListExclusionsResponse.newBuilder() @@ -1405,7 +1394,7 @@ public void testListExclusionAsyncWithOptions() throws ExecutionException, Inter .setPageSize(42) .setParent(PROJECT_PARENT) .build(); - List exclusionList = + ImmutableList exclusionList = ImmutableList.of( Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER), Exclusion.of(EXCLUSION_NAME, EXCLUSION_FILTER)); @@ -1430,12 +1419,14 @@ public void testListResourceDescriptor() { EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = - ListMonitoredResourceDescriptorsRequest.newBuilder().build(); - List descriptorList = ImmutableList.of(DESCRIPTOR, DESCRIPTOR); + ListMonitoredResourceDescriptorsRequest.getDefaultInstance(); + ImmutableList descriptorList = + ImmutableList.of(DESCRIPTOR, DESCRIPTOR); ListMonitoredResourceDescriptorsResponse response = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken(cursor) - .addAllResourceDescriptors(Lists.transform(descriptorList, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList, LoggingImplTest::descriptorToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); @@ -1454,21 +1445,24 @@ public void testListResourceDescriptorNextPage() { EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListMonitoredResourceDescriptorsRequest request1 = - ListMonitoredResourceDescriptorsRequest.newBuilder().build(); + ListMonitoredResourceDescriptorsRequest.getDefaultInstance(); ListMonitoredResourceDescriptorsRequest request2 = ListMonitoredResourceDescriptorsRequest.newBuilder().setPageToken(cursor1).build(); - List descriptorList1 = ImmutableList.of(DESCRIPTOR, DESCRIPTOR); - List descriptorList2 = ImmutableList.of(DESCRIPTOR); + ImmutableList descriptorList1 = + ImmutableList.of(DESCRIPTOR, DESCRIPTOR); + ImmutableList descriptorList2 = ImmutableList.of(DESCRIPTOR); ListMonitoredResourceDescriptorsResponse response1 = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken(cursor1) - .addAllResourceDescriptors(Lists.transform(descriptorList1, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList1, LoggingImplTest::descriptorToPbFunction)) .build(); String cursor2 = "nextCursor"; ListMonitoredResourceDescriptorsResponse response2 = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken(cursor2) - .addAllResourceDescriptors(Lists.transform(descriptorList2, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList2, LoggingImplTest::descriptorToPbFunction)) .build(); ApiFuture futureResponse1 = ApiFutures.immediateFuture(response1); @@ -1494,12 +1488,13 @@ public void testListResourceDescriptorEmpty() { EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = - ListMonitoredResourceDescriptorsRequest.newBuilder().build(); - List descriptorList = ImmutableList.of(); + ListMonitoredResourceDescriptorsRequest.getDefaultInstance(); + ImmutableList descriptorList = ImmutableList.of(); ListMonitoredResourceDescriptorsResponse response = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken("") - .addAllResourceDescriptors(Lists.transform(descriptorList, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList, LoggingImplTest::descriptorToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); @@ -1523,11 +1518,13 @@ public void testListResourceDescriptorWithOptions() { .setPageToken(cursor) .setPageSize(42) .build(); - List descriptorList = ImmutableList.of(DESCRIPTOR, DESCRIPTOR); + ImmutableList descriptorList = + ImmutableList.of(DESCRIPTOR, DESCRIPTOR); ListMonitoredResourceDescriptorsResponse response = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken(cursor) - .addAllResourceDescriptors(Lists.transform(descriptorList, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList, LoggingImplTest::descriptorToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); @@ -1548,12 +1545,14 @@ public void testListResourceDescriptorAsync() throws ExecutionException, Interru EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = - ListMonitoredResourceDescriptorsRequest.newBuilder().build(); - List descriptorList = ImmutableList.of(DESCRIPTOR, DESCRIPTOR); + ListMonitoredResourceDescriptorsRequest.getDefaultInstance(); + ImmutableList descriptorList = + ImmutableList.of(DESCRIPTOR, DESCRIPTOR); ListMonitoredResourceDescriptorsResponse response = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken(cursor) - .addAllResourceDescriptors(Lists.transform(descriptorList, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList, LoggingImplTest::descriptorToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); @@ -1574,21 +1573,24 @@ public void testListResourceDescriptorAsyncNextPage() EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListMonitoredResourceDescriptorsRequest request1 = - ListMonitoredResourceDescriptorsRequest.newBuilder().build(); + ListMonitoredResourceDescriptorsRequest.getDefaultInstance(); ListMonitoredResourceDescriptorsRequest request2 = ListMonitoredResourceDescriptorsRequest.newBuilder().setPageToken(cursor1).build(); - List descriptorList1 = ImmutableList.of(DESCRIPTOR, DESCRIPTOR); - List descriptorList2 = ImmutableList.of(DESCRIPTOR); + ImmutableList descriptorList1 = + ImmutableList.of(DESCRIPTOR, DESCRIPTOR); + ImmutableList descriptorList2 = ImmutableList.of(DESCRIPTOR); ListMonitoredResourceDescriptorsResponse response1 = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken(cursor1) - .addAllResourceDescriptors(Lists.transform(descriptorList1, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList1, LoggingImplTest::descriptorToPbFunction)) .build(); String cursor2 = "nextCursor"; ListMonitoredResourceDescriptorsResponse response2 = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken(cursor2) - .addAllResourceDescriptors(Lists.transform(descriptorList2, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList2, LoggingImplTest::descriptorToPbFunction)) .build(); ApiFuture futureResponse1 = ApiFutures.immediateFuture(response1); @@ -1616,12 +1618,13 @@ public void testListResourceDescriptorAsyncEmpty() EasyMock.replay(rpcFactoryMock); logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = - ListMonitoredResourceDescriptorsRequest.newBuilder().build(); - List descriptorList = ImmutableList.of(); + ListMonitoredResourceDescriptorsRequest.getDefaultInstance(); + ImmutableList descriptorList = ImmutableList.of(); ListMonitoredResourceDescriptorsResponse response = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken("") - .addAllResourceDescriptors(Lists.transform(descriptorList, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList, LoggingImplTest::descriptorToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); @@ -1647,11 +1650,13 @@ public void testListResourceDescriptorAsyncWithOptions() .setPageToken(cursor) .setPageSize(42) .build(); - List descriptorList = ImmutableList.of(DESCRIPTOR, DESCRIPTOR); + ImmutableList descriptorList = + ImmutableList.of(DESCRIPTOR, DESCRIPTOR); ListMonitoredResourceDescriptorsResponse response = ListMonitoredResourceDescriptorsResponse.newBuilder() .setNextPageToken(cursor) - .addAllResourceDescriptors(Lists.transform(descriptorList, DESCRIPTOR_TO_PB_FUNCTION)) + .addAllResourceDescriptors( + Lists.transform(descriptorList, LoggingImplTest::descriptorToPbFunction)) .build(); ApiFuture futureResponse = ApiFutures.immediateFuture(response); @@ -1672,7 +1677,7 @@ public void testListResourceDescriptorAsyncWithOptions() public void testListLogsWithLogNames() { EasyMock.replay(rpcFactoryMock); logging = options.getService(); - List logNames = ImmutableList.of(LOG_NAME1, LOG_NAME2); + ImmutableList logNames = ImmutableList.of(LOG_NAME1, LOG_NAME2); configureListLogsTests(logNames, LOG_NAMES_CURSOR); Page page = logging.listLogs(); @@ -1684,7 +1689,7 @@ public void testListLogsWithLogNames() { public void testListLogsWithEmptySet() { EasyMock.replay(rpcFactoryMock); logging = options.getService(); - List emptyList = ImmutableList.of(); + ImmutableList emptyList = ImmutableList.of(); configureListLogsTests(emptyList, LOG_NAMES_CURSOR); Page page = logging.listLogs(); @@ -1696,8 +1701,8 @@ public void testListLogsWithEmptySet() { public void testListLogsNextPageWithLogNames() throws ExecutionException, InterruptedException { EasyMock.replay(rpcFactoryMock); logging = options.getService(); - List logNames1 = ImmutableList.of(LOG_NAME1, LOG_NAME2); - List logNames2 = ImmutableList.of(LOG_NAME1); + ImmutableList logNames1 = ImmutableList.of(LOG_NAME1, LOG_NAME2); + ImmutableList logNames2 = ImmutableList.of(LOG_NAME1); String nextPageCursor = "nextCursor"; configureListLogsTests(logNames1, logNames2, LOG_NAMES_CURSOR, nextPageCursor); @@ -1713,7 +1718,7 @@ public void testListLogsNextPageWithLogNames() throws ExecutionException, Interr public void testListLogsAsyncWithLogNames() throws ExecutionException, InterruptedException { EasyMock.replay(rpcFactoryMock); logging = options.getService(); - List logNames = ImmutableList.of(LOG_NAME1, LOG_NAME2); + ImmutableList logNames = ImmutableList.of(LOG_NAME1, LOG_NAME2); configureListLogsTests(logNames, LOG_NAMES_CURSOR); AsyncPage page = logging.listLogsAsync().get(); @@ -1725,7 +1730,7 @@ public void testListLogsAsyncWithLogNames() throws ExecutionException, Interrupt public void testListLogsAsyncWithEmptySet() throws ExecutionException, InterruptedException { EasyMock.replay(rpcFactoryMock); logging = options.getService(); - List emptyList = ImmutableList.of(); + ImmutableList emptyList = ImmutableList.of(); configureListLogsTests(emptyList, LOG_NAMES_CURSOR); AsyncPage page = logging.listLogsAsync().get(); @@ -1738,8 +1743,8 @@ public void testListLogsAsyncNextPageWithLogNames() throws ExecutionException, InterruptedException { EasyMock.replay(rpcFactoryMock); logging = options.getService(); - List logNames1 = ImmutableList.of(LOG_NAME1, LOG_NAME2); - List logNames2 = ImmutableList.of(LOG_NAME1); + ImmutableList logNames1 = ImmutableList.of(LOG_NAME1, LOG_NAME2); + ImmutableList logNames2 = ImmutableList.of(LOG_NAME1); String nextPageCursor = "nextCursor"; configureListLogsTests(logNames1, logNames2, LOG_NAMES_CURSOR, nextPageCursor); @@ -1847,7 +1852,7 @@ public void testWriteLogEntries() { Iterables.transform( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), LogEntry.toPbFunction(PROJECT))) .build(); - WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); + WriteLogEntriesResponse response = WriteLogEntriesResponse.getDefaultInstance(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); @@ -1882,7 +1887,7 @@ public void testWriteLogEntriesWithSeverityFlushEnabled() { Iterables.transform( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), LogEntry.toPbFunction(PROJECT))) .build(); - WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); + WriteLogEntriesResponse response = WriteLogEntriesResponse.getDefaultInstance(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); @@ -1930,7 +1935,7 @@ public void testWriteLogEntriesAsync() { LOG_ENTRY1, LOG_ENTRY2, LOG_ENTRY_NO_DESTINATION, LOG_ENTRY_EMPTY), LogEntry.toPbFunction(PROJECT))) .build(); - WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); + WriteLogEntriesResponse response = WriteLogEntriesResponse.getDefaultInstance(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); @@ -1941,7 +1946,7 @@ public void testWriteLogEntriesAsync() { @Test public void testWriteLogEntriesAsyncWithOptions() { - Map labels = ImmutableMap.of("key", "value"); + ImmutableMap labels = ImmutableMap.of("key", "value"); WriteLogEntriesRequest request = WriteLogEntriesRequest.newBuilder() .putAllLabels(labels) @@ -1951,7 +1956,7 @@ public void testWriteLogEntriesAsyncWithOptions() { Iterables.transform( ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), LogEntry.toPbFunction(PROJECT))) .build(); - WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); + WriteLogEntriesResponse response = WriteLogEntriesResponse.getDefaultInstance(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); @@ -1970,7 +1975,7 @@ public void testListLogEntries() { EasyMock.replay(rpcFactoryMock); logging = options.getService(); - List entriesList = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); + ImmutableList entriesList = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); ListLogEntriesResponse response = ListLogEntriesResponse.newBuilder() .setNextPageToken(cursor) @@ -2004,8 +2009,8 @@ public void testListLogEntriesNextPage() throws ExecutionException, InterruptedE .setFilter(defaultTimeFilter) .setPageToken(cursor1) .build(); - List descriptorList1 = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); - List descriptorList2 = ImmutableList.of(LOG_ENTRY1); + ImmutableList descriptorList1 = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); + ImmutableList descriptorList2 = ImmutableList.of(LOG_ENTRY1); ListLogEntriesResponse response1 = ListLogEntriesResponse.newBuilder() .setNextPageToken(cursor1) @@ -2043,7 +2048,7 @@ public void testListLogEntriesEmpty() { .setFilter(LoggingImpl.defaultTimestampFilterCreator.createDefaultTimestampFilter()) .build(); - List entriesList = ImmutableList.of(); + ImmutableList entriesList = ImmutableList.of(); ListLogEntriesResponse response = ListLogEntriesResponse.newBuilder() .setNextPageToken(cursor) @@ -2071,7 +2076,7 @@ public void testListLogEntriesWithOptions() { "logName:syslog AND %s", LoggingImpl.defaultTimestampFilterCreator.createDefaultTimestampFilter())) .build(); - List entriesList = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); + ImmutableList entriesList = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); ListLogEntriesResponse response = ListLogEntriesResponse.newBuilder() .setNextPageToken(cursor) @@ -2098,7 +2103,7 @@ public void testListLogEntriesAsync() throws ExecutionException, InterruptedExce .addResourceNames(PROJECT_PARENT) .setFilter(LoggingImpl.defaultTimestampFilterCreator.createDefaultTimestampFilter()) .build(); - List entriesList = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); + ImmutableList entriesList = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); ListLogEntriesResponse response = ListLogEntriesResponse.newBuilder() .setNextPageToken(cursor) @@ -2128,8 +2133,8 @@ public void testListLogEntriesAsyncNextPage() { .setFilter(LoggingImpl.defaultTimestampFilterCreator.createDefaultTimestampFilter()) .setPageToken(cursor1) .build(); - List descriptorList1 = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); - List descriptorList2 = ImmutableList.of(LOG_ENTRY1); + ImmutableList descriptorList1 = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); + ImmutableList descriptorList2 = ImmutableList.of(LOG_ENTRY1); ListLogEntriesResponse response1 = ListLogEntriesResponse.newBuilder() .setNextPageToken(cursor1) @@ -2166,7 +2171,7 @@ public void testListLogEntriesAsyncEmpty() throws ExecutionException, Interrupte .addResourceNames(PROJECT_PARENT) .setFilter(LoggingImpl.defaultTimestampFilterCreator.createDefaultTimestampFilter()) .build(); - List entriesList = ImmutableList.of(); + ImmutableList entriesList = ImmutableList.of(); ListLogEntriesResponse response = ListLogEntriesResponse.newBuilder() .setNextPageToken(cursor) @@ -2195,7 +2200,7 @@ public void testListLogEntriesAsyncWithOptions() throws ExecutionException, Inte .setOrderBy("timestamp desc") .setFilter(filter) .build(); - List entriesList = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); + ImmutableList entriesList = ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2); ListLogEntriesResponse response = ListLogEntriesResponse.newBuilder() .setNextPageToken(cursor) @@ -2234,11 +2239,8 @@ public void testFlush() throws InterruptedException { logging.write(ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2)); Thread flushWaiter = new Thread( - new Runnable() { - @Override - public void run() { - logging.flush(); - } + () -> { + logging.flush(); }); flushWaiter.start(); @@ -2279,7 +2281,7 @@ public void run() { try { logging.write(ImmutableList.of(LOG_ENTRY1)); logging.flush(); - } catch (Exception ex) { + } catch (RuntimeException ex) { exceptions.incrementAndGet(); } } @@ -2319,7 +2321,7 @@ private void testDiagnosticInfoGeneration(boolean addPartialSuccessOption) { LogEntry.toPbFunction(PROJECT))) .setPartialSuccess(true) .build(); - WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); + WriteLogEntriesResponse response = WriteLogEntriesResponse.getDefaultInstance(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); logging = options.getService(); @@ -2344,7 +2346,7 @@ private void testDeleteByDestination( private void testWriteLogEntriesWithDestination( String projectId, String fullLogNamePath, LogDestinationName destination) { - Map labels = ImmutableMap.of("key", "value"); + ImmutableMap labels = ImmutableMap.of("key", "value"); WriteLogEntriesRequest expectedWriteLogEntriesRequest = WriteLogEntriesRequest.newBuilder() .putAllLabels(labels) @@ -2361,7 +2363,7 @@ private void testWriteLogEntriesWithDestination( LOG_ENTRY_EMPTY), LogEntry.toPbFunction(projectId))) .build(); - WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); + WriteLogEntriesResponse response = WriteLogEntriesResponse.getDefaultInstance(); EasyMock.expect(loggingRpcMock.write(expectedWriteLogEntriesRequest)) .andReturn(ApiFutures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingLevelTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingLevelTest.java index 96a3cf1a3..3a701b30e 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingLevelTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingLevelTest.java @@ -16,8 +16,8 @@ package com.google.cloud.logging; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import java.util.logging.Level; import org.junit.Test; @@ -32,8 +32,8 @@ public void testDebug() { LoggingLevel debug = LoggingLevel.DEBUG; assertEquals(Severity.DEBUG, debug.getSeverity()); assertEquals("DEBUG", debug.getName()); - assertTrue(debug.intValue() < Level.FINEST.intValue()); - assertTrue(debug.intValue() > Level.ALL.intValue()); + assertThat(debug.intValue()).isLessThan(Level.FINEST.intValue()); + assertThat(debug.intValue()).isGreaterThan(Level.ALL.intValue()); } @Test @@ -41,8 +41,8 @@ public void testNotice() { LoggingLevel notice = LoggingLevel.NOTICE; assertEquals(Severity.NOTICE, notice.getSeverity()); assertEquals("NOTICE", notice.getName()); - assertTrue(notice.intValue() > Level.INFO.intValue()); - assertTrue(notice.intValue() < Level.WARNING.intValue()); + assertThat(notice.intValue()).isGreaterThan(Level.INFO.intValue()); + assertThat(notice.intValue()).isLessThan(Level.WARNING.intValue()); } @Test @@ -50,8 +50,8 @@ public void testError() { LoggingLevel error = LoggingLevel.ERROR; assertEquals(Severity.ERROR, error.getSeverity()); assertEquals("ERROR", error.getName()); - assertTrue(error.intValue() > Level.WARNING.intValue()); - assertTrue(error.intValue() < Level.SEVERE.intValue()); + assertThat(error.intValue()).isGreaterThan(Level.WARNING.intValue()); + assertThat(error.intValue()).isLessThan(Level.SEVERE.intValue()); } @Test @@ -59,8 +59,8 @@ public void testCritical() { LoggingLevel critical = LoggingLevel.CRITICAL; assertEquals(Severity.CRITICAL, critical.getSeverity()); assertEquals("CRITICAL", critical.getName()); - assertTrue(critical.intValue() > LoggingLevel.SEVERE.intValue()); - assertTrue(critical.intValue() < Level.OFF.intValue()); + assertThat(critical.intValue()).isGreaterThan(LoggingLevel.SEVERE.intValue()); + assertThat(critical.intValue()).isLessThan(Level.OFF.intValue()); } @Test @@ -68,8 +68,8 @@ public void testAlert() { LoggingLevel alert = LoggingLevel.ALERT; assertEquals(Severity.ALERT, alert.getSeverity()); assertEquals("ALERT", alert.getName()); - assertTrue(alert.intValue() > LoggingLevel.CRITICAL.intValue()); - assertTrue(alert.intValue() < Level.OFF.intValue()); + assertThat(alert.intValue()).isGreaterThan(LoggingLevel.CRITICAL.intValue()); + assertThat(alert.intValue()).isLessThan(Level.OFF.intValue()); } @Test @@ -77,7 +77,7 @@ public void testEmergency() { LoggingLevel emergency = LoggingLevel.EMERGENCY; assertEquals(Severity.EMERGENCY, emergency.getSeverity()); assertEquals("EMERGENCY", emergency.getName()); - assertTrue(emergency.intValue() > LoggingLevel.ALERT.intValue()); - assertTrue(emergency.intValue() < Level.OFF.intValue()); + assertThat(emergency.intValue()).isGreaterThan(LoggingLevel.ALERT.intValue()); + assertThat(emergency.intValue()).isLessThan(Level.OFF.intValue()); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingOptionsTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingOptionsTest.java index d2769b084..b9e85ba07 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingOptionsTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingOptionsTest.java @@ -18,6 +18,7 @@ import static org.easymock.EasyMock.createMock; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import com.google.cloud.TransportOptions; import org.junit.Test; @@ -29,10 +30,12 @@ public class LoggingOptionsTest { private static final Boolean DONT_AUTO_POPULATE_METADATA = false; private static final String PROJECT_ID = "fake-project-id"; - @Test(expected = IllegalArgumentException.class) + @Test public void testNonGrpcTransportOptions() { TransportOptions invalidTransport = createMock(TransportOptions.class); - LoggingOptions.newBuilder().setTransportOptions(invalidTransport); + assertThrows( + IllegalArgumentException.class, + () -> LoggingOptions.newBuilder().setTransportOptions(invalidTransport)); } @Test diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingTest.java index 272082de1..22ff5b6c0 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingTest.java @@ -27,7 +27,6 @@ import com.google.cloud.logging.Logging.ListOption; import com.google.common.collect.ImmutableMap; import com.google.logging.v2.ListLogEntriesRequest; -import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -38,7 +37,7 @@ public class LoggingTest { private static final int PAGE_SIZE = 42; private static final String PAGE_TOKEN = "page token"; private static final String FILTER = "filter"; - private static final Map LABELS = ImmutableMap.of("key", "value"); + private static final ImmutableMap LABELS = ImmutableMap.of("key", "value"); private static final String LOG_NAME = "logName"; private static final MonitoredResource RESOURCE = MonitoredResource.of("global", ImmutableMap.of("project_id", "p")); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java index aa25a663f..1812507a7 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java @@ -55,11 +55,11 @@ private void initializeExpectedMetric(int optionsCalls) { expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); logging = createStrictMock(Logging.class); - expectedMetric = new Metric(serviceMockReturnsOptions, new Metric.BuilderImpl(METRIC_INFO)); + expectedMetric = new Metric(serviceMockReturnsOptions, new MetricInfo.BuilderImpl(METRIC_INFO)); } private void initializeMetric() { - metric = new Metric(logging, new Metric.BuilderImpl(METRIC_INFO)); + metric = new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)); } @After diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/MonitoredResourceUtilTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/MonitoredResourceUtilTest.java index 653b0465a..071c11d16 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/MonitoredResourceUtilTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/MonitoredResourceUtilTest.java @@ -22,11 +22,9 @@ import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import com.google.cloud.MonitoredResource; import com.google.common.collect.ImmutableMap; -import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -61,7 +59,7 @@ public void teardown() { @Test public void testResourceTypeGlobal() { - final Map ExpectedLabels = + final ImmutableMap ExpectedLabels = ImmutableMap.of("project_id", MonitoredResourceUtilTest.MOCKED_PROJECT_ID); // setup @@ -72,14 +70,14 @@ public void testResourceTypeGlobal() { MonitoredResource response = MonitoredResourceUtil.getResource("", ""); // verify assertEquals("global", response.getType()); - assertTrue(response.getLabels().equals(ExpectedLabels)); + assertEquals(ExpectedLabels, response.getLabels()); } @Test public void testGetResourceWithParameters() { final String MyProjectId = "my-project-id"; final String MyResourceType = "my-resource-type"; - final Map ExpectedLabels = ImmutableMap.of("project_id", MyProjectId); + final ImmutableMap ExpectedLabels = ImmutableMap.of("project_id", MyProjectId); // setup replay(getterMock); @@ -90,13 +88,13 @@ public void testGetResourceWithParameters() { getterMock.getAttribute(""); // verify assertEquals("my-resource-type", response.getType()); - assertTrue(response.getLabels().equals(ExpectedLabels)); + assertEquals(ExpectedLabels, response.getLabels()); } @Test public void testResourceTypeGCEInstance() { final String MockedInstanceId = "1234567890abcdefg"; - final Map ExpectedLabels = + final ImmutableMap ExpectedLabels = ImmutableMap.of( "project_id", MonitoredResourceUtilTest.MOCKED_PROJECT_ID, @@ -117,7 +115,7 @@ public void testResourceTypeGCEInstance() { MonitoredResource response = MonitoredResourceUtil.getResource("", ""); // verify assertEquals("gce_instance", response.getType()); - assertTrue(response.getLabels().equals(ExpectedLabels)); + assertEquals(ExpectedLabels, response.getLabels()); } /** @@ -131,7 +129,7 @@ public void testResourceTypeK8sContainer() { final String MockedNamespaceName = "default"; final String MockedPodName = "mocked-pod"; final String MockedContainerName = "mocked-container"; - final Map ExpectedLabels = + final ImmutableMap ExpectedLabels = ImmutableMap.builder() .put("project_id", MonitoredResourceUtilTest.MOCKED_PROJECT_ID) .put("cluster_name", MockedClusterName) @@ -139,7 +137,7 @@ public void testResourceTypeK8sContainer() { .put("namespace_name", MockedNamespaceName) .put("pod_name", MockedPodName) .put("container_name", MockedContainerName) - .build(); + .buildOrThrow(); // setup expect(getterMock.getAttribute("instance/attributes/cluster-name")) @@ -156,7 +154,7 @@ public void testResourceTypeK8sContainer() { MonitoredResource response = MonitoredResourceUtil.getResource("", ""); // verify assertEquals("k8s_container", response.getType()); - assertTrue(response.getLabels().equals(ExpectedLabels)); + assertEquals(ExpectedLabels, response.getLabels()); } private void setupCommonGAEMocks(String mockedModuleId, String mockedVersionId) { @@ -171,7 +169,7 @@ private void setupCommonGAEMocks(String mockedModuleId, String mockedVersionId) public void testResourceTypeGAEStandardEnvironment() { final String MockedModuleId = "mocked-module-id"; final String MockedVersionId = "mocked-version-id"; - final Map ExpectedLabels = + final ImmutableMap ExpectedLabels = ImmutableMap.of( "project_id", MonitoredResourceUtilTest.MOCKED_PROJECT_ID, @@ -192,14 +190,14 @@ public void testResourceTypeGAEStandardEnvironment() { MonitoredResource response = MonitoredResourceUtil.getResource("", ""); // verify assertEquals("gae_app", response.getType()); - assertTrue(response.getLabels().equals(ExpectedLabels)); + assertEquals(ExpectedLabels, response.getLabels()); } @Test public void testResourceTypeGAEFlexibleEnvironment() { final String MockedModuleId = "mocked-module-id"; final String MockedVersionId = "mocked-version-id"; - final Map ExpectedLabels = + final ImmutableMap ExpectedLabels = ImmutableMap.of( "project_id", MonitoredResourceUtilTest.MOCKED_PROJECT_ID, @@ -222,13 +220,13 @@ public void testResourceTypeGAEFlexibleEnvironment() { MonitoredResource response = MonitoredResourceUtil.getResource("", ""); // verify assertEquals("gae_app", response.getType()); - assertTrue(response.getLabels().equals(ExpectedLabels)); + assertEquals(ExpectedLabels, response.getLabels()); } @Test public void testResourceTypeCloudFunction() { final String MockedFunctionName = "mocked-function-name"; - final Map ExpectedLabels = + final ImmutableMap ExpectedLabels = ImmutableMap.of( "project_id", MonitoredResourceUtilTest.MOCKED_PROJECT_ID, @@ -253,7 +251,7 @@ public void testResourceTypeCloudFunction() { MonitoredResource response = MonitoredResourceUtil.getResource("", ""); // verify assertEquals("cloud_function", response.getType()); - assertTrue(response.getLabels().equals(ExpectedLabels)); + assertEquals(ExpectedLabels, response.getLabels()); } @Test @@ -261,7 +259,7 @@ public void testResourceTypeCloudRun() { final String MockedRevisionName = "mocked-revision-name"; final String MockedServiceName = "mocked-service-name"; final String MockedConfigurationName = "mocked-config-name"; - final Map ExpectedLabels = + final ImmutableMap ExpectedLabels = ImmutableMap.of( "project_id", MonitoredResourceUtilTest.MOCKED_PROJECT_ID, @@ -286,6 +284,6 @@ public void testResourceTypeCloudRun() { MonitoredResource response = MonitoredResourceUtil.getResource("", ""); // verify assertEquals("cloud_run_revision", response.getType()); - assertTrue(response.getLabels().equals(ExpectedLabels)); + assertEquals(ExpectedLabels, response.getLabels()); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/OptionTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/OptionTest.java index f3e57f366..275f5fb1b 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/OptionTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/OptionTest.java @@ -17,11 +17,11 @@ package com.google.cloud.logging; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import com.google.cloud.logging.Logging.ListOption; import com.google.cloud.logging.Option.OptionType; +import com.google.common.testing.EqualsTester; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -41,14 +41,11 @@ public class OptionTest { @Test public void testEquals() { - assertEquals(OPTION, OPTION_EQUALS); - assertNotEquals(OPTION, OPTION_NOT_EQUALS1); - assertNotEquals(OPTION, OPTION_NOT_EQUALS2); - } - - @Test - public void testHashCode() { - assertEquals(OPTION.hashCode(), OPTION_EQUALS.hashCode()); + new EqualsTester() + .addEqualityGroup(OPTION, OPTION_EQUALS) + .addEqualityGroup(OPTION_NOT_EQUALS1) + .addEqualityGroup(OPTION_NOT_EQUALS2) + .testEquals(); } @Test diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/PayloadTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/PayloadTest.java index d43d5a3dd..ac2e466df 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/PayloadTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/PayloadTest.java @@ -16,13 +16,12 @@ package com.google.cloud.logging; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import com.google.cloud.logging.Payload.JsonPayload; import com.google.cloud.logging.Payload.ProtoPayload; import com.google.cloud.logging.Payload.StringPayload; -import com.google.cloud.logging.Payload.Type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.protobuf.Any; @@ -31,7 +30,6 @@ import com.google.protobuf.Struct; import com.google.protobuf.Value; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; @@ -49,7 +47,8 @@ public class PayloadTest { private static final Value STRING_VALUE = Value.newBuilder().setStringValue(STRING).build(); private static final Boolean BOOLEAN = true; private static final Value BOOLEAN_VALUE = Value.newBuilder().setBoolValue(BOOLEAN).build(); - private static final List LIST = ImmutableList.of(NUMBER, STRING, BOOLEAN); + private static final ImmutableList LIST = + ImmutableList.of(NUMBER, STRING, BOOLEAN); private static final Value VALUE_LIST = Value.newBuilder() .setListValue( @@ -81,7 +80,7 @@ public class PayloadTest { .put("boolean", BOOLEAN_VALUE) .put("list", VALUE_LIST) .put("struct", Value.newBuilder().setStructValue(INNER_STRUCT).build()) - .build()) + .buildOrThrow()) .build(); static { @@ -105,15 +104,15 @@ public class PayloadTest { @Test public void testOf() { - assertEquals(Type.STRING, STRING_PAYLOAD.getType()); + assertEquals(Payload.Type.STRING, STRING_PAYLOAD.getType()); assertEquals(STRING_DATA, STRING_PAYLOAD.getData()); - assertEquals(Type.JSON, JSON_PAYLOAD.getType()); + assertEquals(Payload.Type.JSON, JSON_PAYLOAD.getType()); assertEquals(STRUCT_DATA, JSON_PAYLOAD.getData()); assertEquals(JSON_DATA, JSON_PAYLOAD.getDataAsMap()); - assertEquals(Type.PROTO, PROTO_PAYLOAD.getType()); + assertEquals(Payload.Type.PROTO, PROTO_PAYLOAD.getType()); assertEquals(PROTO_DATA, PROTO_PAYLOAD.getData()); JsonPayload jsonPayload = JsonPayload.of(STRUCT_DATA); - assertEquals(Type.JSON, jsonPayload.getType()); + assertEquals(Payload.Type.JSON, jsonPayload.getType()); assertEquals(STRUCT_DATA, jsonPayload.getData()); assertEquals(JSON_DATA, jsonPayload.getDataAsMap()); } @@ -121,13 +120,13 @@ public void testOf() { @Test public void testToAndFromPb() { Payload payload = Payload.fromPb(STRING_PAYLOAD.toPb().build()); - assertTrue(payload instanceof StringPayload); + assertThat(payload).isInstanceOf(StringPayload.class); comparePayload(STRING_PAYLOAD, payload); payload = Payload.fromPb(JSON_PAYLOAD.toPb().build()); - assertTrue(payload instanceof JsonPayload); + assertThat(payload).isInstanceOf(JsonPayload.class); comparePayload(JSON_PAYLOAD, payload); payload = ProtoPayload.fromPb(PROTO_PAYLOAD.toPb().build()); - assertTrue(payload instanceof ProtoPayload); + assertThat(payload).isInstanceOf(ProtoPayload.class); comparePayload(PROTO_PAYLOAD, payload); } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java index f78a5bd77..144436c1a 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java @@ -63,13 +63,13 @@ public class SerializationTest extends BaseSerializationTest { private static final LogEntry ENTRY = LogEntry.of(STRING_PAYLOAD); private static final MetricInfo METRIC_INFO = MetricInfo.of("metric", "logName=projects/my-projectid/logs/syslog"); - private static final Metric METRIC = new Metric(LOGGING, new Metric.BuilderImpl(METRIC_INFO)); + private static final Metric METRIC = new Metric(LOGGING, new MetricInfo.BuilderImpl(METRIC_INFO)); private static final BucketDestination BUCKET_DESTINATION = BucketDestination.of("bucket"); private static final DatasetDestination DATASET_DESTINATION = DatasetDestination.of("project", "dataset"); private static final TopicDestination TOPIC_DESTINATION = TopicDestination.of("project", "topic"); private static final SinkInfo SINK_INFO = SinkInfo.of("sink", BUCKET_DESTINATION); - private static final Sink SINK = new Sink(LOGGING, new Sink.BuilderImpl(SINK_INFO)); + private static final Sink SINK = new Sink(LOGGING, new SinkInfo.BuilderImpl(SINK_INFO)); private static final ListOption PAGE_TOKEN_OPTION = ListOption.pageToken("token"); private static final ListOption PAGE_SIZE_OPTION = ListOption.pageSize(42); private static final WriteOption LABELS_OPTION = diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkInfoTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkInfoTest.java index 701569def..787c8a064 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkInfoTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkInfoTest.java @@ -16,6 +16,7 @@ package com.google.cloud.logging; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; @@ -125,7 +126,9 @@ public void testToAndFromPbDestination() { Destination.fromPb("wrongDestination"); fail(); } catch (IllegalArgumentException expected) { - assertEquals("wrongDestination is not a valid sink destination", expected.getMessage()); + assertThat(expected) + .hasMessageThat() + .isEqualTo("wrongDestination is not a valid sink destination"); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java index 5f6f0e378..4cd59181f 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java @@ -63,11 +63,11 @@ private void initializeExpectedSink(int optionsCalls) { expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); logging = createStrictMock(Logging.class); - expectedSink = new Sink(serviceMockReturnsOptions, new Sink.BuilderImpl(SINK_INFO)); + expectedSink = new Sink(serviceMockReturnsOptions, new SinkInfo.BuilderImpl(SINK_INFO)); } private void initializeSink() { - sink = new Sink(logging, new Sink.BuilderImpl(SINK_INFO)); + sink = new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)); } @After diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SourceLocationTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SourceLocationTest.java index 8ae4af44b..d9b0d6da3 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SourceLocationTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SourceLocationTest.java @@ -64,7 +64,7 @@ public void testToAndFromPb() { @Test public void testFromCurrentContext() { - StackTraceElement expectedData = (new Exception()).getStackTrace()[0]; + StackTraceElement expectedData = new Exception().getStackTrace()[0]; SourceLocation data = SourceLocation.fromCurrentContext(); assertEquals(expectedData.getFileName(), data.getFile()); assertEquals(expectedData.getMethodName(), data.getFunction()); @@ -77,7 +77,7 @@ public void testFromCurrentContext() { @Test public void testFromCurrentContextWithExclusionList() { - StackTraceElement expectedData = (new Exception()).getStackTrace()[0]; + StackTraceElement expectedData = new Exception().getStackTrace()[0]; SourceLocation data = SourceLocation.fromCurrentContext(LoggingImpl.class.getName()); assertEquals(expectedData.getFileName(), data.getFile()); assertEquals(expectedData.getMethodName(), data.getFunction()); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/StructsTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/StructsTest.java index f370cc953..b2654a735 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/StructsTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/StructsTest.java @@ -16,8 +16,8 @@ package com.google.cloud.logging; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; @@ -26,9 +26,7 @@ import com.google.protobuf.NullValue; import com.google.protobuf.Struct; import com.google.protobuf.Value; -import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.junit.BeforeClass; import org.junit.Test; @@ -41,7 +39,8 @@ public class StructsTest { private static final Double NUMBER = 42.0; private static final String STRING = "string"; private static final Boolean BOOLEAN = true; - private static final List LIST = ImmutableList.of(NUMBER, STRING, BOOLEAN); + private static final ImmutableList LIST = + ImmutableList.of(NUMBER, STRING, BOOLEAN); private static final Map INNER_MAP = new HashMap<>(); private static final Map MAP = new HashMap<>(); private static final Value NULL_VALUE = @@ -65,7 +64,7 @@ public class StructsTest { "list", LIST_VALUE)) .build(); private static final Value STRUCT_VALUE = Value.newBuilder().setStructValue(INNER_STRUCT).build(); - private static final Map VALUE_MAP = + private static final ImmutableMap VALUE_MAP = ImmutableMap.builder() .put("null", NULL_VALUE) .put("number", NUMBER_VALUE) @@ -73,9 +72,9 @@ public class StructsTest { .put("boolean", BOOLEAN_VALUE) .put("list", LIST_VALUE) .put("struct", STRUCT_VALUE) - .build(); + .buildOrThrow(); private static final Struct STRUCT = Struct.newBuilder().putAllFields(VALUE_MAP).build(); - private static final Map EMPTY_MAP = Collections.emptyMap(); + private static final ImmutableMap EMPTY_MAP = ImmutableMap.of(); @BeforeClass public static void beforeClass() { @@ -93,8 +92,8 @@ public static void beforeClass() { } private void checkMapField(Map map, String key, T expected) { - assertTrue(map.containsKey(key)); - assertEquals(expected, map.get(key)); + assertThat(map).containsKey(key); + assertThat(map).containsEntry(key, expected); } private void checkStructField(Struct struct, String key, Value expected) { @@ -139,7 +138,7 @@ public void testAsMapRemove() { @Test public void testAsMapEmpty() { Map map = Structs.asMap(Struct.getDefaultInstance()); - assertTrue(map.isEmpty()); + assertThat(map).isEmpty(); assertEquals(EMPTY_MAP, map); } @@ -167,7 +166,7 @@ public void testNewStruct() { @Test public void testNewStructEmpty() { Struct struct = Structs.newStruct(EMPTY_MAP); - assertTrue(struct.getFieldsMap().isEmpty()); + assertThat(struct.getFieldsMap()).isEmpty(); } @Test @@ -185,7 +184,7 @@ public void testNumbers() { long longNumber = Long.MAX_VALUE; float floatNumber = Float.MIN_VALUE; double doubleNumber = Double.MAX_VALUE; - Map map = + ImmutableMap map = ImmutableMap.of( "int", intNumber, "long", longNumber, "float", floatNumber, "double", doubleNumber); Struct struct = Structs.newStruct(map); @@ -195,10 +194,10 @@ public void testNumbers() { checkStructField(struct, "float", Value.newBuilder().setNumberValue(floatNumber).build()); checkStructField(struct, "double", Value.newBuilder().setNumberValue(doubleNumber).build()); Map convertedMap = Structs.asMap(struct); - assertTrue(convertedMap.get("int") instanceof Double); - assertTrue(convertedMap.get("long") instanceof Double); - assertTrue(convertedMap.get("float") instanceof Double); - assertTrue(convertedMap.get("double") instanceof Double); + assertThat(convertedMap.get("int")).isInstanceOf(Double.class); + assertThat(convertedMap.get("long")).isInstanceOf(Double.class); + assertThat(convertedMap.get("float")).isInstanceOf(Double.class); + assertThat(convertedMap.get("double")).isInstanceOf(Double.class); int convertedInteger = ((Double) convertedMap.get("int")).intValue(); long convertedLong = ((Double) convertedMap.get("long")).longValue(); float convertedFloat = ((Double) convertedMap.get("float")).floatValue(); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/TailLogEntriesTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/TailLogEntriesTest.java index 0baaf9fde..4fac7f2f3 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/TailLogEntriesTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/TailLogEntriesTest.java @@ -27,6 +27,7 @@ import com.google.logging.v2.TailLogEntriesRequest; import com.google.logging.v2.TailLogEntriesResponse; import com.google.protobuf.Duration; +import com.google.protobuf.util.Durations; import org.easymock.EasyMock; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,7 +36,7 @@ @RunWith(JUnit4.class) public class TailLogEntriesTest { private static final String WINDOW = "20s"; - private static final Duration WINDOW_DURATION = Duration.newBuilder().setSeconds(20).build(); + private static final Duration WINDOW_DURATION = Durations.fromSeconds(20); private static final String FILTER = "severity) bidiStreamMock); + EasyMock.expect(loggingRpcMock.getTailLogEntriesStream()).andReturn(bidiStreamMock); bidiStreamMock.send(EasyMock.anyObject(TailLogEntriesRequest.class)); - EasyMock.expectLastCall() - .andAnswer( - () -> { - return null; - }); + EasyMock.expectLastCall().andAnswer(() -> null); EasyMock.replay(rpcFactoryMock, loggingRpcMock, bidiStreamMock); // execute diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/v2/testing/LocalLoggingImpl.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/v2/testing/LocalLoggingImpl.java index ab52005fc..9fc072149 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/v2/testing/LocalLoggingImpl.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/v2/testing/LocalLoggingImpl.java @@ -35,7 +35,7 @@ public class LocalLoggingImpl extends LoggingServiceV2Grpc.LoggingServiceV2ImplBase { - private Map> logs = new HashMap<>(); + private final Map> logs = new HashMap<>(); @Override public void deleteLog(DeleteLogRequest request, StreamObserver responseObserver) { @@ -47,14 +47,11 @@ public void deleteLog(DeleteLogRequest request, StreamObserver responseOb @Override public void writeLogEntries( WriteLogEntriesRequest request, StreamObserver responseObserver) { - List entries = logs.get(request.getLogName()); - if (entries == null) { - entries = new ArrayList(); - logs.put(request.getLogName(), entries); - } + List entries = + logs.computeIfAbsent(request.getLogName(), (String k) -> new ArrayList()); entries.addAll(request.getEntriesList()); // Response is empty - responseObserver.onNext(WriteLogEntriesResponse.newBuilder().build()); + responseObserver.onNext(WriteLogEntriesResponse.getDefaultInstance()); responseObserver.onCompleted(); }