|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.opentelemetry.smoketest.springboot.controller; |
| 18 | + |
| 19 | +import io.opentelemetry.api.trace.Span; |
| 20 | +import java.net.URI; |
| 21 | +import org.slf4j.Logger; |
| 22 | +import org.slf4j.LoggerFactory; |
| 23 | +import org.springframework.boot.web.client.RestTemplateBuilder; |
| 24 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 25 | +import org.springframework.web.bind.annotation.RestController; |
| 26 | +import org.springframework.web.client.RestTemplate; |
| 27 | +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; |
| 28 | + |
| 29 | +/** |
| 30 | + * This controller demonstrates that context propagation works across http calls. |
| 31 | + * Calling <code>/front</code> should return a string which contains two traceId separated by ";". |
| 32 | + * First traceId was reported by <code>/front</code> handler, the second one was returned by |
| 33 | + * <code>/back</code> handler which was called by <code>/front</code>. If context propagation |
| 34 | + * works correctly, then both values should be the same. |
| 35 | + */ |
| 36 | +@RestController |
| 37 | +public class PropagatingController { |
| 38 | + private static final Logger LOGGER = LoggerFactory.getLogger(PropagatingController.class); |
| 39 | + |
| 40 | + private final RestTemplate restTemplate; |
| 41 | + |
| 42 | + public PropagatingController(RestTemplateBuilder restTemplateBuilder) { |
| 43 | + this.restTemplate = restTemplateBuilder.build(); |
| 44 | + } |
| 45 | + |
| 46 | + @RequestMapping("/front") |
| 47 | + public String front() { |
| 48 | + URI backend = ServletUriComponentsBuilder |
| 49 | + .fromCurrentContextPath() |
| 50 | + .path("/back") |
| 51 | + .build() |
| 52 | + .toUri(); |
| 53 | + String backendTraceId = restTemplate.getForObject(backend, String.class); |
| 54 | + String frontendTraceId = Span.current().getSpanContext().getTraceIdAsHexString(); |
| 55 | + return String.format("%s;%s", frontendTraceId, backendTraceId); |
| 56 | + } |
| 57 | + |
| 58 | + @RequestMapping("/back") |
| 59 | + public String back() { |
| 60 | + return Span.current().getSpanContext().getTraceIdAsHexString(); |
| 61 | + } |
| 62 | +} |
0 commit comments