Skip to content

Commit 53117a3

Browse files
committed
fix: simplify logic of header getter
1 parent c721960 commit 53117a3

1 file changed

Lines changed: 8 additions & 21 deletions

File tree

gax-java/gax/src/main/java/com/google/api/gax/tracing/SpanTracer.java

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@
3838
import io.opentelemetry.api.trace.Tracer;
3939
import java.util.HashMap;
4040
import java.util.Map;
41+
import java.util.TreeMap;
42+
import java.util.function.Supplier;
4143

4244
/** An implementation of {@link ApiTracer} that uses OpenTelemetry to record traces. */
4345
@BetaApi
@@ -138,29 +140,14 @@ public void responseHeadersReceived(java.util.Map<String, Object> headers) {
138140
* @param headers the map of response headers.
139141
* @return the content length in bytes, or -1 if the header is missing or malformed.
140142
*/
141-
private long extractContentLength(java.util.Map<String, Object> headers) {
142-
if (headers == null) {
143+
private long extractContentLength(final java.util.Map<String, Object> headers) {
144+
final Map<String, Object> iHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
145+
iHeaders.putAll(headers);
146+
Supplier<Object> headerGetter = () -> iHeaders.get(CONTENT_LENGTH_KEY);
147+
if (headers == null || headerGetter.get() == null) {
143148
return -1;
144149
}
145-
for (Map.Entry<String, Object> entry : headers.entrySet()) {
146-
if (CONTENT_LENGTH_KEY.equalsIgnoreCase(entry.getKey())) {
147-
return parseContentLength(entry.getValue());
148-
}
149-
}
150-
return -1;
151-
}
152-
153-
/**
154-
* Safely parses the content length Object representation into a long integer.
155-
*
156-
* @param value the header value to parse.
157-
* @return the parsed content length value, or -1 if it was null or failed to parse.
158-
*/
159-
private long parseContentLength(Object value) {
160-
if (value == null) {
161-
return -1;
162-
}
163-
return Long.parseLong(String.valueOf(value));
150+
return Long.parseLong(String.valueOf(headerGetter.get()));
164151
}
165152

166153
private void endAttempt() {

0 commit comments

Comments
 (0)