Skip to content

Commit bf02f73

Browse files
committed
RestClient implement getUrlTemplate
1 parent a7b5a6f commit bf02f73

File tree

1 file changed

+55
-2
lines changed

1 file changed

+55
-2
lines changed

instrumentation/spring/spring-web/spring-web-3.1/library/src/main/java/io/opentelemetry/instrumentation/spring/web/v3_1/SpringWebHttpAttributesGetter.java

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,18 @@
77

88
import static java.util.Collections.emptyList;
99

10-
import io.opentelemetry.instrumentation.api.semconv.http.HttpClientAttributesGetter;
10+
import io.opentelemetry.instrumentation.api.incubator.semconv.http.HttpClientExperimentalAttributesGetter;
1111
import java.lang.invoke.MethodHandle;
1212
import java.lang.invoke.MethodHandles;
1313
import java.lang.invoke.MethodType;
1414
import java.util.List;
15+
import java.util.Map;
1516
import javax.annotation.Nullable;
1617
import org.springframework.http.HttpRequest;
1718
import org.springframework.http.client.ClientHttpResponse;
1819

1920
enum SpringWebHttpAttributesGetter
20-
implements HttpClientAttributesGetter<HttpRequest, ClientHttpResponse> {
21+
implements HttpClientExperimentalAttributesGetter<HttpRequest, ClientHttpResponse> {
2122
INSTANCE;
2223

2324
@Override
@@ -107,4 +108,56 @@ public String getServerAddress(HttpRequest httpRequest) {
107108
public Integer getServerPort(HttpRequest httpRequest) {
108109
return httpRequest.getURI().getPort();
109110
}
111+
112+
private static final String URI_TEMPLATE_ATTRIBUTE = "org.springframework.web.client.RestClient.uriTemplate";
113+
@Nullable private static final MethodHandle GET_ATTRIBUTES;
114+
115+
static {
116+
MethodHandle getAttributes = null;
117+
Class<?> httpRequestClass = null;
118+
119+
try {
120+
httpRequestClass = Class.forName("org.springframework.http.HttpRequest");
121+
} catch (ClassNotFoundException e) {
122+
// ignored
123+
}
124+
125+
if (httpRequestClass != null) {
126+
MethodHandles.Lookup lookup = MethodHandles.publicLookup();
127+
try {
128+
getAttributes =
129+
lookup.findVirtual(
130+
httpRequestClass,
131+
"getAttributes",
132+
MethodType.methodType(java.util.Map.class));
133+
} catch (NoSuchMethodException | IllegalAccessException ignored) {
134+
// ignored
135+
}
136+
}
137+
138+
GET_ATTRIBUTES = getAttributes;
139+
}
140+
141+
@Nullable
142+
@Override
143+
public String getUrlTemplate(HttpRequest httpRequest) {
144+
if (GET_ATTRIBUTES == null) {
145+
return null;
146+
}
147+
148+
try {
149+
Object attributes = GET_ATTRIBUTES.invoke(httpRequest);
150+
if (attributes instanceof java.util.Map) {
151+
Map<?, ?> map = (Map<?, ?>) attributes;
152+
Object value = map.get(URI_TEMPLATE_ATTRIBUTE);
153+
if (value instanceof String) {
154+
return (String) value;
155+
}
156+
}
157+
} catch (Throwable e) {
158+
// ignore
159+
}
160+
161+
return null;
162+
}
110163
}

0 commit comments

Comments
 (0)