org.springframework.boot.actuate.info.RequestInfoContributor Maven / Gradle / Ivy
package org.springframework.boot.actuate.info;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.actuate.info.Info.Builder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
public class RequestInfoContributor implements org.springframework.boot.actuate.info.InfoContributor {
private final boolean requestContext = ClassUtils.isPresent("org.springframework.web.context.request.RequestContextHolder", getClass().getClassLoader());
@Override
public void contribute(Builder builder) {
if (this.requestContext) {
HttpServletRequest httpServletRequest = getRequest();
if (httpServletRequest != null) {
Map request = new LinkedHashMap();
ServletServerHttpRequest servletServerHttpRequest = new ServletServerHttpRequest(httpServletRequest);
Map address = new LinkedHashMap();
address.put("local", servletServerHttpRequest.getLocalAddress());
address.put("remote", servletServerHttpRequest.getRemoteAddress());
address.put("server", InetSocketAddress.createUnresolved(httpServletRequest.getServerName(), httpServletRequest.getServerPort()));
request.put("address", address);
Map header = new LinkedHashMap();
for (Map.Entry> entry : servletServerHttpRequest.getHeaders().entrySet()) {
String headerName = entry.getKey();
String headerValue = HttpHeaders.COOKIE.equalsIgnoreCase(headerName) ? StringUtils.collectionToDelimitedString(entry.getValue(), "; ")
: StringUtils.collectionToCommaDelimitedString(entry.getValue());
header.put(headerName, headerValue);
}
request.put("header", header);
request.put("secure", httpServletRequest.isSecure());
request.put("contextPath", httpServletRequest.getContextPath());
request.put("uri", ServletUriComponentsBuilder.fromRequest(httpServletRequest).build().toUri());
try {
request.put("url", servletServerHttpRequest.getURI().toURL());
}
catch (MalformedURLException e) {
// ignore
}
request.put("method", servletServerHttpRequest.getMethod());
builder.withDetail("request", request);
}
}
}
private HttpServletRequest getRequest() {
org.springframework.web.context.request.RequestAttributes requestAttributes = org.springframework.web.context.request.RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof org.springframework.web.context.request.ServletRequestAttributes) {
return ((org.springframework.web.context.request.ServletRequestAttributes) requestAttributes).getRequest();
}
return null;
}
}