Skip to content

Instantly share code, notes, and snippets.

View jkuipers's full-sized avatar

Joris Kuipers jkuipers

  • Trifork
  • The Netherlands, near Amsterdam
View GitHub Profile
@jkuipers
jkuipers / LoggingClientHttpRequestInterceptor.java
Last active November 27, 2023 18:44
RestTemplate-interceptor that logs outgoing requests and resulting responses
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;
@jkuipers
jkuipers / HttpClientAutoConfiguration.java
Last active November 27, 2023 18:44
Spring Boot auto-configuration example for an Apache Components HTTP client and its usage in all RestTemplates created by the RestTemplateBuilder, plus trace logging support
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateCustomizer;
@jkuipers
jkuipers / TracingSqsListenerConfig.java
Last active November 7, 2023 08:34
Configuration and code to add tracing support to Spring Cloud AWS's message listeners
@AutoConfiguration(before = io.awspring.cloud.autoconfigure.sqs.SqsAutoConfiguration.class,
afterName = "org.springframework.boot.actuate.autoconfigure.tracing.BraveAutoConfiguration")
@ConditionalOnBean(Tracing.class)
public class SqsTracingAutoConfiguration {
@Bean(name = SqsBeanNames.SQS_LISTENER_ANNOTATION_BEAN_POST_PROCESSOR_BEAN_NAME)
TracingSqsListenerAnnotationBeanPostProcessor tracingSLABPP(Tracing tracing) {
return new TracingSqsListenerAnnotationBeanPostProcessor(tracing);
}
static class TracingSqsListenerAnnotationBeanPostProcessor extends SqsListenerAnnotationBeanPostProcessor {
@jkuipers
jkuipers / TracingSqsTemplateConfig.java
Created November 7, 2023 08:23
Adds tracing headers to messages sent via Spring Cloud AWS's SqsTemplate
@Bean
SqsTemplate sqsTemplate(SqsAsyncClient sqsAsyncClient, ObjectMapper objectMapper, Tracing tracing) {
var injector = tracing.propagation().injector(
(Propagation.Setter<Map<String, Object>, String>) (headersMap, key, value) -> {
// only propagate the traceparent attr, no additional baggage, since SQS only supports a max of 10 attrs
if (key.startsWith("trace")) headersMap.put(key, value);
});
var converter = new SqsMessagingMessageConverter() {
@Override
public Message fromMessagingMessage(org.springframework.messaging.Message<?> message, MessageConversionContext context) {
@jkuipers
jkuipers / HttpClientMetricsConfig.java
Created March 14, 2023 07:55
Spring bean definition that ensures that client.name tags are included in HTTP client metrics again
/**
* Starting with Boot 3, the {@code client.name} tag is no longer included by default
* in the {@code http.client.requests} metrics. Restore it by overriding
* {@link DefaultClientRequestObservationConvention#getLowCardinalityKeyValues(ClientRequestObservationContext)}.
*
* @return {@link ClientRequestObservationConvention} that adds the {@code client.name} to the low cardinality key-values.
*/
@Bean
ClientRequestObservationConvention clientNameAddingObservationConvention() {
return new DefaultClientRequestObservationConvention() {
@jkuipers
jkuipers / RestTemplateConfigSample.java
Created May 21, 2012 20:50
RestTemplate with basic or digest authentication configured
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
DefaultHttpClient client = (DefaultHttpClient) factory.getHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope(hostName, portNumber),
new UsernamePasswordCredentials(username, password));
RestTemplate restTemplate = new RestTemplate(factory);
@jkuipers
jkuipers / MDCPropagatingTaskDecorator.java
Created January 5, 2022 08:25
Spring TaskDecorator that propagates an SLF4J MDC to the runner's thread. Accounts for the possibility that the runner's thread is actually the same as the caller's thread by restoring the old MDC context, if existing.
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
import java.util.Map;
public class MDCPropagatingTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
Map<String, String> callerContext = MDC.getCopyOfContextMap();
@jkuipers
jkuipers / formMacros.ftl
Last active June 21, 2022 13:43
FreeMarker macros for rendering Bootstrap horizontal form inputs in Spring-MVC applications
<#ftl strip_whitespace=true>
<#import "spring.ftl" as spring />
<#-- This file contains form-related macros for use in the other Freemarker template files.
The generated HTML is intended for use with Twitter Bootstrap based forms. -->
<#--
* radioButtons
*
* @param path the name of the field to bind to
@jkuipers
jkuipers / TomcatAutoConfiguration.java
Created January 14, 2022 14:32
Spring Boot (auto-)configuration class that defines an additional Tomcat Connector for health checks
import org.apache.catalina.connector.Connector;
import org.apache.coyote.AbstractProtocol;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@jkuipers
jkuipers / OpenJ9MemoryMetrics.java
Created January 14, 2022 14:26
Micrometer.io heap statistics for OpenJ9 VMs
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.BaseUnits;
import io.micrometer.core.instrument.binder.MeterBinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;