Skip to content

Instantly share code, notes, and snippets.

@vijayakumar-psg587
Created January 11, 2019 05:56
Show Gist options
  • Save vijayakumar-psg587/5f91a5b27963b6899f27cfe969d7b6ad to your computer and use it in GitHub Desktop.
Save vijayakumar-psg587/5f91a5b27963b6899f27cfe969d7b6ad to your computer and use it in GitHub Desktop.
SwaggerFilter
@Component
public class SwaggerFilter implements Filter {
final String APPLICATION_XHTML = "application/xhtml";
final String XML_ELEMENT_START = "<Json>";
final String XML_ELEMENT_END = "</Json>";
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
ByteArrayPrinter pw = new ByteArrayPrinter();
HttpServletResponse wrappedResp = new HttpServletResponseWrapper(response) {
@Override
public void setContentType(final String type) {
super.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
}
@Override
public PrintWriter getWriter() {
return pw.getWriter();
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
ServletResponse response = this.getResponse();
String ct = (response != null) ? response.getContentType() : null;
if (ct != null && ct.contains(APPLICATION_XHTML)) {
response.setContentType(ct + "," + MediaType.APPLICATION_JSON_UTF8_VALUE);
}
return pw.getStream();
}
};
chain.doFilter(httpRequest, wrappedResp);
byte[] bytes = pw.toByteArray();
String respBody = new String(bytes);
if (respBody.startsWith(XML_ELEMENT_START)) {
List<String> s13 = Stream.of(respBody).filter((s1) -> s1.contains(XML_ELEMENT_START))
.map((sample) -> Arrays.asList(sample.split(" ")))
.flatMap((listString) -> {
StringBuffer sb = new StringBuffer();
listString.forEach(item -> {
sb.append(item);
});
return Stream
.of(sb.toString().trim().replace(XML_ELEMENT_START, "").replace(XML_ELEMENT_END, ""));
}).collect(Collectors.toList());
String s14 = String.join("", s13);
response.getOutputStream().write(s14.getBytes());
} else {
response.getOutputStream().write(bytes);
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment