Java spring get body of post request - spring

I have the following problem: I try to get body of a POST request before it is handled by a spring controller. For that I am using the HandlerInterceptorAdapter's preHandle() method.
As stated in this discussion Spring REST service: retrieving JSON from Request I also use the HttpServletRequestWrapper. With this wrapper I managed to print the body of the first POST request, but the second POST throws an IOException: StreamClosed.
Do you have any ideas on how I can get the body of all POST requests?
Here is the preHandle() method from the interceptor:
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println(request.getMethod());
MyRequestWrapper w = new MyRequestWrapper(request);
BufferedReader r = w.getReader();
System.out.println(r.readLine());
return super.preHandle(request, response, handler);
}
The HttpServletRequestWrapper:
public class MyRequestWrapper extends HttpServletRequestWrapper {
private ByteArrayOutputStream cachedBytes;
private HttpServletRequest request;
public MyRequestWrapper(HttpServletRequest request) {
super(request);
this.request = request;
}
#Override
public ServletInputStream getInputStream() throws IOException {
cachedBytes = new ByteArrayOutputStream();
if (request.getMethod().equals("POST"))
cacheInputStream();
return new CachedServletInputStream();
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
private void cacheInputStream() throws IOException {
/*
* Cache the inputstream in order to read it multiple times. For
* convenience, I use apache.commons IOUtils
*/
ServletInputStream inputStream = super.getInputStream();
if (inputStream == null) {
return;
}
IOUtils.copy(inputStream, cachedBytes);
}
/* An inputstream which reads the cached request body */
public class CachedServletInputStream extends ServletInputStream {
private ByteArrayInputStream input;
public CachedServletInputStream() {
/* create a new input stream from the cached request body */
input = new ByteArrayInputStream(cachedBytes.toByteArray());
}
#Override
public int read() throws IOException {
return input.read();
}
}
}
The console output:
2014-10-15 12:13:00 INFO [http-nio-8080-exec-1] org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcherServlet': initialization completed in 9 ms
GET
null
GET
null
POST
{"long":null,"owner":{"__type":"Owner","id":20,"version":1,"md5Password":""},"string":"ws","tool":{"__type":"Tool","id":33,"version":1}}
POST
2014-10-15 12:13:00 ERROR [http-nio-8080-exec-3] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet dispatcherServlet threw exception
java.io.IOException: Stream closed

You're attempting to read from the original request in your Wrapper, but after this, the original request is still being read - hence the request input stream has been consumed and cannot be read from again.
Instead of using an Interceptor, consider using a javax.servlet.Filter. In the doFilter method, you can pass the wrapped request on down the chain.

I've used filter that implements Filter & interceptor that extends HandlerInterceptorAdapter (because in the filter all fields are nullable and I can't save anything to DB. see Autowired Null Pointer Exception) to retreive request and response body and save them to DB. If your filter works fine then use only filter.
filter. Here I wrap a request and a response to read from them not only once. You can use ContentCachingRequestWrapper and ContentCachingResponseWrapper for that.
#Component
public class RequestLogFilter implements Filter {
private final Logger logger = LoggerFactory.getLogger(RequestLogFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
logger.info("======================> FILTER <======================");
HttpServletRequest requestToCache = new ContentCachingRequestWrapper((HttpServletRequest) request);
HttpServletResponse responseToCache = new ContentCachingResponseWrapper((HttpServletResponse) response);
// before method
chain.doFilter(requestToCache, responseToCache);
// after method
// your logic(save to DB, logging...)
getRequestData(request);
getResponseData(response);
}
#Override
public void destroy() {
}
}
-
#Component
public class RequestLogInterceptor extends HandlerInterceptorAdapter {
private final Logger logger = LoggerFactory.getLogger(RequestLogInterceptor.class);
#Autowired
private InboundRequestLogStore inboundRequestLogStore;
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
logger.info("====================> INTERCEPTOR <========================");
try {
if (request.getAttribute(InboundRequestAspect.INBOUND_LOG_MARKER) != null) {
InboundRequestLogRecord logRecord = new InboundRequestLogRecord();
logRecord.setIpAddress(request.getRemoteAddr());
// getting request and response body
logRecord.setRequestBody(getRequestData(request));
logRecord.setResponseBody(getResponseData(response));
logRecord.setResponseCode(((HttpServletResponse) response).getStatus());
String uri = request.getScheme() + "://" + request.getServerName()
+ ("http".equals(request.getScheme()) && request.getServerPort() == 80
|| "https".equals(request.getScheme()) && request.getServerPort() == 443 ? ""
: ":" + request.getServerPort())
+ request.getRequestURI()
+ (request.getQueryString() != null ? "?" + request.getQueryString() : "");
logRecord.setUrl(uri);
inboundRequestLogStore.add(logRecord); // save to DB
} else {
((ContentCachingResponseWrapper) response).copyBodyToResponse(); // in other case you send null to the response
}
} catch (Exception e) {
logger.error("error ", e);
try {
((ContentCachingResponseWrapper) response).copyBodyToResponse(); // in other case you send null to the response
} catch (Exception e2) {
// TODO Auto-generated catch block
logger.error("error ", e2);
}
}
}
public static String getRequestData(final HttpServletRequest request) throws UnsupportedEncodingException {
String payload = null;
ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
}
}
return payload;
}
public static String getResponseData(final HttpServletResponse response) throws UnsupportedEncodingException, IOException {
String payload = null;
ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
}
wrapper.copyBodyToResponse(); // in other case you send null to the response
}
return payload;
}
}
add to servlet-context.xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<beans:bean class="path.to.RequestLogInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
namespaces:
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
ContentCachingRequestWrapper - http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/ContentCachingRequestWrapper.html
ContentCachingResponseWrapper - http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/ContentCachingResponseWrapper.html

Related

Spring boot application filter response body

I am working on a spring boot application. I want to modify the response of the request by request body field "Id".
I have implemented below, but still getting just the name in the output while implementing.Any suggestions on implementing below would be helpful:
Below is the requestBody:
{
"id" : "123"
}
In response, I want to append that field to response id(fieldname from request body).
responseBody:
{
"name" : "foo123" //name + id from request
}
MyCustomFilter:
public class TestFilter implements Filter {
#Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream ps = new PrintStream(baos);
MultiReadHttpServletRequest wrapper = new MultiReadHttpServletRequest((HttpServletRequest) request);
MyRequestWrapper req = new MyRequestWrapper(wrapper);
String userId = req.getId();
chain.doFilter(wrapper, new HttpServletResponseWrapper(res) {
#Override
public ServletOutputStream getOutputStream() throws IOException {
return new DelegatingServletOutputStream(new TeeOutputStream(super.getOutputStream(), ps)
);
}
#Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(new DelegatingServletOutputStream(new TeeOutputStream(super.getOutputStream(), ps))
);
}
});
String responseBody = baos.toString();
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(responseBody);
String name = node.get("name").astext();
((ObjectNode) node1).put("name", name + userId);
chain.doFilter(wrapper, res);
}
MyRequestWrapper:
public class MyRequestWrapper extends HttpServletRequestWrapper {
private ServletInputStream input;
public MyRequestWrapper(ServletRequest request) {
super((HttpServletRequest)request);
}
public String getId() throws IOException {
if (input == null) {
try {
JSONObject jsonObject = new JSONObject(IOUtils.toString(super.getInputStream()));
String userId = jsonObject.getString("id");
userId = userId.replaceAll("\\D+","");
return userId;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
MultiReadHttpServletRequest.java
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private byte[] body;
public MultiReadHttpServletRequest(HttpServletRequest request) {
super(request);
try {
body = IOUtils.toByteArray(request.getInputStream());
} catch (IOException ex) {
body = new byte[0];
}
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
}
#Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
ByteArrayInputStream wrapperStream = new ByteArrayInputStream(body);
#Override
public boolean isFinished() {
return false;
}
#Override
public boolean isReady() {
return false;
}
#Override
public void setReadListener(ReadListener readListener) {
}
#Override
public int read() throws IOException {
return wrapperStream.read();
}
};
}
}
Any suggestions are appreciated. TIA.
Nte: After update i am not able to see the updated response as output. I am still seeing just the name but not id appended to it.
The one issue I see with your own implementation of ServletRequest is that you call super.getInputStream() instead of request.getInputStream(). Your own request is empty by default, that's why you're getting time out exception. You have to delegate a call to the actual request:
public class MyRequestWrapper extends HttpServletRequestWrapper {
private ServletInputStream input;
public MyRequestWrapper(ServletRequest request) {
super((HttpServletRequest)request);
}
public String getId() throws IOException {
if (input == null) {
try {
JSONObject jsonObject = new JSONObject(IOUtils.toString(/*DELETEGATE TO ACTUAL REQUEST*/request.getInputStream()));
String userId = jsonObject.getString("id");
userId = userId.replaceAll("\\D+","");
return userId;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}

Spring Interceptor

I need to create an interceptor that will intercept HTTP requests and responses, but it seems to me that I'm doing something wrong, can someone tell me what I should change or add?
public class HttpInterceptor extends HandlerInterceptorAdapter implements ClientHttpRequestInterceptor
{
#Override
public ClientHttpResponse intercept(final HttpRequest httpRequest, final byte[] bytes, final ClientHttpRequestExecution clientHttpRequestExecution) throws IOException
{
RestTemplate restTemplate = new RestTemplate();
final ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
final String httpResponseName = response.toString();
final HttpHeaders httpHeaders = response.getHeaders();
final HttpStatus httpStatusCode = response.getStatusCode();
final String statusText = response.getStatusText();
final String body = httpHeaders.toString() + httpStatusCode.toString() + statusText;
//And then i will put body to DB
return response;
}
xml
<bean id="httpInterceptor" class="HttpInterceptor"/>
<bean id="httpInterceptor" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">
<property name="interceptor" ref="httpInterceptor"/>
<property name="typeCode" value="Message"/>
</bean>
I understood that you try to create service (it can be rest, soap or any other). If I am right, you need to create controller for handling http request.
#Controller("MyController")
public class MyController extends AbstractController {
#RequestMapping(value = "/mymethod/{id}", method = RequestMethod.GET)
public void myMethod(#PathVariable final String id, final HttpServletRequest request, final HttpServletResponse out) throws Exception {
try {
if (StringUtils.isEmpty(id))
throw new UnknownIdentifierException("id is null!");
out.setContentType(MediaType.APPLICATION_TXT_VALUE);
IOUtils.copy(myStream, out.getOutputStream());
} catch (UnknownIdentifierException ex) {
out.setStatus(HttpServletResponse.SC_BAD_REQUEST);
out.setContentType(MediaType.TEXT_PLAIN_VALUE);
String message = "My error text!";
IOUtils.copy(new ByteArrayInputStream(message.getBytes()), out.getOutputStream());
}
}
I recommande to implements Filter to transform or use the information contained in the requests or responses. and not Interceptor , it provide more information then Interceptor Here's an exemple of the use of Filter for logging :
#Component
public class HttpLoggingFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(HttpLoggingFilter.class);
#Value("${output.trace.actif}")
private boolean isOutputActif;
private static String getRequestData(final HttpServletRequest request) throws UnsupportedEncodingException {
String payload = null;
ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
}
}
return payload;
}
private static String getResponseData(final HttpServletResponse response) throws IOException {
String payload = null;
ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
wrapper.copyBodyToResponse();
}
}
return payload;
}
#Override
public void init(FilterConfig filterConfig) {
logger.info("start http filter");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
ContentCachingRequestWrapper requestToCache = new ContentCachingRequestWrapper(httpServletRequest);
ContentCachingResponseWrapper responseToCache = new ContentCachingResponseWrapper(httpServletResponse);
HttpUtil.majMDCRestInfo(httpServletRequest);
long start = System.currentTimeMillis();
chain.doFilter(requestToCache, responseToCache);
long elapsedTime = System.currentTimeMillis() - start;
String requestBody = new String(requestToCache.getContentAsByteArray());
String responseBody = new String(responseToCache.getContentAsByteArray());
final StringBuilder logMessage = new StringBuilder().append("[METHOD:").append(httpServletRequest.getMethod())
.append("] [PARAMS:")
.append(httpServletRequest.getQueryString()).append("] [BODY:").append(requestBody).append("]");
if (isOutputActif) {
String respContent = responseBody;
if (respContent.equals("")) {
respContent = "no data";
}
logMessage.append(" [RESPONSE:").append(respContent).append("]");
}
logMessage.append(" [STATUS:").append(responseToCache.getStatus()).append("] [Time:").append(elapsedTime).append("ms]");
String[] nonLoggingPaths = {"/api/"};
String urlPath = httpServletRequest.getRequestURL().toString();
if ((Arrays.stream(nonLoggingPaths).parallel().anyMatch(urlPath::contains))) {
logger.info("{}", logMessage);
}
getRequestData(requestToCache);
getResponseData(responseToCache);
}
}

How to read httpServletResponse in the interceptor?

I have a spring boot application. And now I need to read request and response in interceptor.I use a HttpServletRequestWrapper replace the request in DispatcherServlet
#Component("dispatcherServlet")
public class FofDisPatcherServlet extends DispatcherServlet {
#Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultiReadHttpServletRequest requestWrapper = null;
try {
requestWrapper = new MultiReadHttpServletRequest(request);
super.doDispatch(requestWrapper, response);
} catch (Exception e) {
super.doDispatch(request,response);
}
}
}
And in my interceptor , I can read the request body. But when I want to read the response body, it doesn't works.when I replace the response in the CustomerDispatcherServlet I got nothing response.I have tried ContentCachingResponseWrapper , but I got the payload with "".
It's a old question.and I have search some questions but didn't find a suitable solution.
I know I can solve the problem with AOP.But I want to know how can I do it in the interceptor?
here is my interceptor code
public class CustomerInterceptor extends HandlerInterceptorAdapter{
#Override
public void postHandle(...){
MultiReadHttpServletRequest req = (MultiReadHttpServletRequest) request;
ContentCachingResponseWrapper res = new ContentCachingResponseWrapper(response);
Byte[] body = res. getContentAsByteArray();
...
}
}
the body I got is [].
After few days .I find the answer.In the CustomerDispatcherServlet I should add responseWrapper.copyBodyToResponse()
the CustomerDIspatcherServlet like this:
#Component("dispatcherServlet")
public class FofDisPatcherServlet extends DispatcherServlet {
#Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultiReadHttpServletRequest requestWrapper = null;
try {
requestWrapper = new MultiReadHttpServletRequest(request);
if (!(response instanceof ContentCachingResponseWrapper)) {
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
super.doDispatch(requestWrapper, responseWrapper);
responseWrapper.copyBodyToResponse();
}else {
super.doDispatch(requestWrapper, response);
}
} catch (Exception e) {
super.doDispatch(request, response);
}
}
}
Try this:
#Component("dispatcherServlet")
public class FofDisPatcherServlet extends DispatcherServlet {
#Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultiReadHttpServletRequest requestWrapper = null;
try {
requestWrapper = new MultiReadHttpServletRequest(request);
super.doDispatch(requestWrapper, new ContentCachingResponseWrapper(request));
} catch (Exception e) {
super.doDispatch(request,response);
}
}
}
.
public class CustomerInterceptor extends HandlerInterceptorAdapter{
#Override
public void postHandle(..., HttpServletResponse response){
if (response instanceof ContentCachingResponseWrapper) {
Byte[] body = ((ContentCachingResponseWrapper)response). getContentAsByteArray();
}
...
}
}
The error is in your code
public class CustomerInterceptor extends HandlerInterceptorAdapter{
#Override
public void postHandle((HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
MultiReadHttpServletRequest req = (MultiReadHttpServletRequest) request;
ContentCachingResponseWrapper res = new ContentCachingResponseWrapper(response);
Byte[] body = res. getContentAsByteArray();
...
}
}
You are passing request in ContentCachingResponseWrapper.
See this question very similar problem .

How I get the HandlerMethod matchs a HttpServletRequest in a Filter

I'm writing a simple proxy app, and want mapped url will be handled by my controller, but other url (includes error) can be forwarded to another different address. So I use Filter rather than HandlerInterceptorAdapter that cannot be invoked if the resourece is not found because certain "resourece path handler" deals it.
Expectation
http://localhost:8090/upload.html > Filter > http://localhost:8092/upload.html
http://localhost:8090/files/upload > Controller > http://localhost:8092/files/upload
Not
http://localhost:8090/upload.html > Filter > http://localhost:8092/upload.html
http://localhost:8090/files/upload > Controller > http://localhost:8092/files/upload
Or
http://localhost:8090/upload.html > Interceptor > http://localhost:8090/error Not found
http://localhost:8090/files/upload > Filter > http://localhost:8092/files/upload
Demo
I set up a Filter in my subclass of WebMvcConfigurerAdapter.
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
private javax.servlet.Filter proxyFilter() {
return new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("[doFilterInternal]isCommitted=" + response.isCommitted() + ", URI = " + request.getRequestURI());
// if(!isRequestMappedInController(request, "my.pakcage"))
httpProxyForward(request, response);
}
};
}
// #Bean
// private FilterRegistrationBean loggingFilterRegistration() {
// FilterRegistrationBean registration = new FilterRegistrationBean(proxyFilter());
// registration.addUrlPatterns("/**");
// return registration;
// }
Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptorAdapter() {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// How I determine a controller has handled the request in my interceptor?
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = ((HandlerMethod) handler);
if (handlerMethod.getMethod().getDeclaringClass().getName().startsWith("nxtcasb.casbproxy")) {
System.out.println("[preHandle]dealt: request uri = " + request.getRequestURI() + ", HandlerMethod = " + ((HandlerMethod) handler).getMethod());
return true;
} else {
System.out.println("[preHandle]isCommitted=" + response.isCommitted() + ", HandlerMethod = " + ((HandlerMethod) handler).getMethod());
}
}
// act as an api-gateway
System.out.println("[preHandle]undealt: request uri = " + request.getRequestURI() + ", handler = " + handler);
//ModelAndView modelView = new ModelAndView("redirect: http://www.bing.com");
//throw new ModelAndViewDefiningException(modelView);
httpProxyForward(request, response);
return false;
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (handler instanceof HandlerMethod) {
System.out.println("[postHandle]dealt: uri = " + request.getRequestURI() + ", handler = " + ((HandlerMethod) handler).getMethod());
} else {
System.out.println("[postHandle]undealt uri = " + request.getRequestURI() + ", handler = " + handler);
}
}
}).addPathPatterns("/**", "/error");
}
/**
* this is the same as <mvc:default-servlet-handler/> <!-- This tag allows for mapping the DispatcherServlet to "/" -->
*
* #param configurer
*/
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("/**").addResourceLocations("classpath:/public");
}
protected void httpProxyForward(HttpServletRequest request, HttpServletResponse response) {
HttpClient httpClient = CreateHttpClient();
HttpUriRequest targetRequest = null;
HttpResponse targetResponse = null;
try {
targetRequest = createHttpUriRequest(request);
targetResponse = httpClient.execute(targetRequest);
} catch (IOException e) {
e.printStackTrace();
} finally {
// make sure the entire entity was consumed, so the connection is released
if (targetResponse != null) {
EntityUtils.consumeQuietly(targetResponse.getEntity()); // #since 4.2
//Note: Don't need to close servlet outputStream:
// http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
}
}
}
}
The api url /files/upload:
#RestController
#RequestMapping(value = "/files")
public class FileUploadProxyController {
private static final Logger logger = LoggerFactory.getLogger(FileUploadProxyController.class);
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity upload(HttpServletResponse response, HttpServletRequest request) {
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator<String> it = multipartRequest.getFileNames();
MultipartFile multipart = multipartRequest.getFile(it.next());
String fileName = multipart.getOriginalFilename();
File dir = new File("files", "proxy-uploaded");
dir.mkdirs();
logger.debug("current dir = {}, uploaded dir = {}", System.getProperty("user.dir"), dir.getAbsolutePath());
File file = new File(dir, fileName);
Files.copy(multipart.getInputStream(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
//FileCopyUtils.copy(multipart.getInputStream())
// byte[] bytes = multipart.getBytes();
// BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream("upload" + fileName));
// stream.write(bytes);
// stream.close();
RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
//// if Spring version < 3.1, see https://jira.springsource.org/browse/SPR-7909
// requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);
String url = "http://localhost:8092/files/upload";
// [resttemplate multipart post](https://jira.spring.io/browse/SPR-13571)
// [Spring RestTemplate - how to enable full debugging/logging of requests/responses?](https://stackoverflow.com/questions/7952154/spring-resttemplate-how-to-enable-full-debugging-logging-of-requests-responses?rq=1)
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", new FileSystemResource(file));
param.add("param1", fileName);
param.add("param2", "Leo");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String,Object>>(param);
ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
//String string = restTemplate.postForObject(url, param, String.class);
//ResponseEntity e = restTemplate.exchange(url, HttpMethod.POST,
// new HttpEntity<Resource>(new FileSystemResource(file)), String.class);
return responseEntity;
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity("Upload failed", HttpStatus.BAD_REQUEST);
}
}
#RequestMapping("/hello")
public String hello() {
return "hello word";
}
}
Afer reading Spring mvc autowire RequestMappingHandlerMapping or Get destination controller from a HttpServletRequest
The following code works:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
// https://stackoverflow.com/questions/129207/getting-spring-application-context
#Autowired
private org.springframework.context.ApplicationContext appContext;
private static final String MY_CONTROLLER_PACKAGE_NAME = "nxtcasb.casbproxy";
#Bean
protected javax.servlet.Filter proxyFilter() {
return new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HandlerMethod handlerMethod = null;
try {
RequestMappingHandlerMapping req2HandlerMapping = (RequestMappingHandlerMapping) appContext.getBean("requestMappingHandlerMapping");
// Map<RequestMappingInfo, HandlerMethod> handlerMethods = req2HandlerMapping.getHandlerMethods();
HandlerExecutionChain handlerExeChain = req2HandlerMapping.getHandler(request);
if (Objects.nonNull(handlerExeChain)) {
handlerMethod = (HandlerMethod) handlerExeChain.getHandler();
if (handlerMethod.getBeanType().getName().startsWith(MY_CONTROLLER_PACKAGE_NAME)) {
filterChain.doFilter(request, response);
return;
}
}
} catch (Exception e) {
logger.warn("Lookup the handler method", e);
} finally {
logger.debug("URI = " + request.getRequestURI() + ", handlerMethod = " + handlerMethod);
}
httpProxyForward(request, response);
}
};
}
// #Bean
// private FilterRegistrationBean loggingFilterRegistration() {
// FilterRegistrationBean registration = new FilterRegistrationBean(proxyFilter());
// registration.addUrlPatterns("/**");
// return registration;
// }
/**
* this is the same as <mvc:default-servlet-handler/> <!-- This tag allows for mapping the DispatcherServlet to "/" -->
*
* #param configurer
*/
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("/**").addResourceLocations("classpath:/public");
}
protected void httpProxyForward(HttpServletRequest request, HttpServletResponse response) {
HttpClient httpClient = CreateHttpClient();
HttpUriRequest targetRequest = null;
HttpResponse targetResponse = null;
try {
targetRequest = createHttpUriRequest(request);
targetResponse = httpClient.execute(targetRequest);
} catch (IOException e) {
e.printStackTrace();
} finally {
// make sure the entire entity was consumed, so the connection is released
if (targetResponse != null) {
EntityUtils.consumeQuietly(targetResponse.getEntity()); // #since 4.2
//Note: Don't need to close servlet outputStream:
// http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
}
}
}
}

Make simple servlet filter work with #ControllerAdvice

I've a simple filter just to check if a request contains a special header with static key - no user auth - just to protect endpoints. The idea is to throw an AccessForbiddenException if the key does not match which then will be mapped to response with a class annotated with #ControllerAdvice. However I can't make it work. My #ExceptionHandler isn't called.
ClientKeyFilter
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Controller
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
#Controller //I know that #Component might be here
public class ClientKeyFilter implements Filter {
#Value('${CLIENT_KEY}')
String clientKey
public void init(FilterConfig filterConfig) {}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
req = (HttpServletRequest) req
def reqClientKey = req.getHeader('Client-Key')
if (!clientKey.equals(reqClientKey)) {
throw new AccessForbiddenException('Invalid API key')
}
chain.doFilter(req, res)
}
public void destroy() {}
}
AccessForbiddenException
public class AccessForbiddenException extends RuntimeException {
AccessForbiddenException(String message) {
super(message)
}
}
ExceptionController
#ControllerAdvice
class ExceptionController {
static final Logger logger = LoggerFactory.getLogger(ExceptionController)
#ExceptionHandler(AccessForbiddenException)
public ResponseEntity handleException(HttpServletRequest request, AccessForbiddenException e) {
logger.error('Caught exception.', e)
return new ResponseEntity<>(e.getMessage(), I_AM_A_TEAPOT)
}
}
Where I'm wrong? Can simple servlet filter work with spring-boot's exception mapping?
As specified by the java servlet specification Filters execute always before a Servlet is invoked. Now a #ControllerAdvice is only useful for controller which are executed inside the DispatcherServlet. So using a Filter and expecting a #ControllerAdvice or in this case the #ExceptionHandler, to be invoked isn't going to happen.
You need to either put the same logic in the filter (for writing a JSON response) or instead of a filter use a HandlerInterceptor which does this check. The easiest way is to extend the HandlerInterceptorAdapter and just override and implement the preHandle method and put the logic from the filter into that method.
public class ClientKeyInterceptor extends HandlerInterceptorAdapter {
#Value('${CLIENT_KEY}')
String clientKey
#Override
public boolean preHandle(ServletRequest req, ServletResponse res, Object handler) {
String reqClientKey = req.getHeader('Client-Key')
if (!clientKey.equals(reqClientKey)) {
throw new AccessForbiddenException('Invalid API key')
}
return true;
}
}
You can't use #ControllerAdvice, because it gets called in case of an exception in some controller, but your ClientKeyFilter is not a #Controller.
You should replace the #Controller annotation with the #Component and just set response body and status like this:
#Component
public class ClientKeyFilter implements Filter {
#Value('${CLIENT_KEY}')
String clientKey
public void init(FilterConfig filterConfig) {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String reqClientKey = request.getHeader("Client-Key");
if (!clientKey.equals(reqClientKey)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid API key");
return;
}
chain.doFilter(req, res);
}
public void destroy() {
}
}
Servlet Filters in Java classes are used for the following purposes:
To check requests from client before they access resources at backend.
To check responses from server before sent back to the client.
Exception throw from Filter may not be catch by #ControllerAdvice because in may not reach DispatcherServlet. I am handling in my project as below:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
String token = null;
String bearerToken = request.getHeader("Authorization");
if (bearerToken != null && (bearerToken.contains("Bearer "))) {
if (bearerToken.startsWith("Bearer "))
token = bearerToken.substring(7, bearerToken.length());
try {
AuthenticationInfo authInfo = TokenHandler.validateToken(token);
logger.debug("Found id:{}", authInfo.getId());
authInfo.uri = request.getRequestURI();
AuthPersistenceBean persistentBean = new AuthPersistenceBean(authInfo);
SecurityContextHolder.getContext().setAuthentication(persistentBean);
logger.debug("Found id:'{}', added into SecurityContextHolder", authInfo.getId());
} catch (AuthenticationException authException) {
logger.error("User Unauthorized: Invalid token provided");
raiseException(request, response);
return;
} catch (Exception e) {
raiseException(request, response);
return;
}
// Wrapping the error response
private void raiseException(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
ApiError apiError = new ApiError(HttpStatus.UNAUTHORIZED);
apiError.setMessage("User Unauthorized: Invalid token provided");
apiError.setPath(request.getRequestURI());
byte[] body = new ObjectMapper().writeValueAsBytes(apiError);
response.getOutputStream().write(body);
}
// ApiError class
public class ApiError {
// 4xx and 5xx
private HttpStatus status;
// holds a user-friendly message about the error.
private String message;
// holds a system message describing the error in more detail.
private String debugMessage;
// returns the part of this request's URL
private String path;
public ApiError(HttpStatus status) {
this();
this.status = status;
}
//setter and getters

Resources