Skip to content

Instantly share code, notes, and snippets.

@akkida746
Created October 18, 2016 11:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkida746/468d0f19b5ed4ac64728d2ff18b34d89 to your computer and use it in GitHub Desktop.
Save akkida746/468d0f19b5ed4ac64728d2ff18b34d89 to your computer and use it in GitHub Desktop.
Configure Spring autowire in java Filter
public class WsFilter implements Filter {
private ApplicationContextProvider springContext;
private FilterConfig filterConfig;
private MessageFactory msgFactory = null;
private static final Logger logger_ = Logger.getLogger(WsFilter.class.getName());
private static final Logger soap_logger = Logger.getLogger("soapLogger");
@Autowired
private WsFilterHelper helper;
@Autowired
private OrderRequesDataBean orderRequesMetaData;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.springContext = new ApplicationContextProvider();
// Adding Autowiring in Java Filter
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());
try {
this.msgFactory = MessageFactory.newInstance();
} catch (SOAPException e) {
e.printStackTrace();
logger_.error("Error: " + e.getMessage());
}
}
@Override
public void destroy() {
this.filterConfig = null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
InputStream inStream = null;
BufferedReader br = null;
PrintWriter out = null;
try {
logger_.info(".................Calling Webservice...................");
// Custom Response Wrapper for writing in servlet output stream
HtmlResponseWrapper capturingResponseWrapper = new HtmlResponseWrapper(
(HttpServletResponse) response);
orderRequesMetaData.refresh();
chain.doFilter(request, capturingResponseWrapper);
out = response.getWriter();
String xmlResponse = null;
if(orderRequesMetaData.getRequestType() != null){
soap_logger.info("Incoming Request : " + orderRequesMetaData.getSoapMsg());
System.out.println("Incoming Request : " + orderRequesMetaData.getSoapMsg());
xmlResponse = generateResponse(request);
}
if (xmlResponse != null) {
out.write(xmlResponse);
System.out.println(xmlResponse);
soap_logger.info("Outgoing Response: " + xmlResponse);
} else {
String path = ((HttpServletRequest) request).getContextPath();
((HttpServletResponse) response).setContentType("text/xml");
((HttpServletResponse) response).sendRedirect(path
+ "/wsdl/LocateServices.wsdl");
soap_logger.info("Outgoing Response: Error occured sending wsdl. " + path
+ "/wsdl/LocateServices.wsdl");
}
} finally {
if (inStream != null)
inStream.close();
if (br != null)
br.close();
if (out != null)
out.close();
}
}
private String generateResponse(ServletRequest request) {
ServletContext context = request.getServletContext();
try{
String requestType = orderRequesMetaData.getRequestType();
File styleFile = new File(context.getRealPath("/WEB-INF/XmlFiles/Fulfillment_style.xsl"));
if (requestType != null && requestType.length() > 1)
if (requestType.equalsIgnoreCase("OrderSearch")) {
return helper.generateOrderSearchResponse(orderRequesMetaData, styleFile);
} else if (requestType.equalsIgnoreCase("OrderUpdate")) {
return helper.generateOrderUpdateResponse(orderRequesMetaData, styleFile);
} else if (requestType.equalsIgnoreCase("Fulfillments")) {
return helper.generateFulfillmentResponse(orderRequesMetaData, styleFile);
} else if (requestType.equalsIgnoreCase("StatusUpdate")) {
return helper.generateStatusUpdateResponse(orderRequesMetaData, styleFile);
} else if (requestType.equalsIgnoreCase("StatusRequest")) {
return helper.generateStatusRequestResponse(orderRequesMetaData, styleFile);
}
} catch(SAXException | IOException | TransformerException | ParserConfigurationException e){
e.printStackTrace();
logger_.error("Error: " + e.getMessage());
}
return null;
}
private class HtmlResponseWrapper extends HttpServletResponseWrapper {
private final ByteArrayOutputStream capture;
private ServletOutputStream output;
private PrintWriter writer;
public HtmlResponseWrapper(HttpServletResponse response) {
super(response);
capture = new ByteArrayOutputStream(response.getBufferSize());
}
@Override
public ServletOutputStream getOutputStream() {
if (writer != null) {
throw new IllegalStateException(
"getWriter() has already been called on this response.");
}
if (output == null) {
output = new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
capture.write(b);
}
@Override
public void flush() throws IOException {
capture.flush();
}
@Override
public void close() throws IOException {
capture.close();
}
//@Override
public boolean isReady() {
return false;
}
// @Override
public void setWriteListener(WriteListener arg0) {
}
};
}
return output;
}
@Override
public PrintWriter getWriter() throws IOException {
if (output != null) {
throw new IllegalStateException(
"getOutputStream() has already been called on this response.");
}
if (writer == null) {
writer = new PrintWriter(new OutputStreamWriter(capture,
getCharacterEncoding()));
}
return writer;
}
@Override
public void flushBuffer() throws IOException {
super.flushBuffer();
if (writer != null) {
writer.flush();
} else if (output != null) {
output.flush();
}
}
public byte[] getCaptureAsBytes() throws IOException {
if (writer != null) {
writer.close();
} else if (output != null) {
output.close();
}
return capture.toByteArray();
}
public String getCaptureAsString() throws IOException {
return new String(getCaptureAsBytes(), getCharacterEncoding());
}
}
}
@akkida746
Copy link
Author

Add below line in Filter init() method:

SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());

@anishtakkar7
Copy link

@akkida746 - Thanks a lot. This is exactly what I was looking for. Wondering why I didn't find any thing related to this on stackoverflow.

@akkida746
Copy link
Author

That’s great. Hope this solves your problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment