Stephen Cameron
2014-07-02 07:16:06 UTC
I imagine there might be some other interested in this perhaps. Here is a
first cut.
It needs the format=html query parameter to give you the cached translated
form.
So, a URL will be something like
http://thedomain.org/appcontext/forms/form.xml
or
http://thedomain.org/appcontext/forms/form.xml?format=html
The later being what I wanted to avoid for obvious reasons, but I cannot
get around it and have the behaviour that I'm seeking.
The web.xml follows the Java code. The SimpleRESTServlet can be replaced
with whatever you use to persist the raw XML forms.
It needs more work, use at own risk, comments welcomed.
Steve Cameron
package net.sourceforge.schema2xforms;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public final class XSLTFormsTransformerCachingServletFilter implements
Filter {
private FilterConfig filterConfig = null;
private Templates templates;
private static FormCache cache = new FormCache();
public void init(FilterConfig config) throws UnavailableException,
ServletException {
this.filterConfig = config;
String factory = config
.getInitParameter("javax.xml.transform.TransformerFactory");
System.out.println(factory);
if (factory != null) {
System.setProperty("javax.xml.transform.TransformerFactory",
factory);
}
Enumeration<String> initParams = config.getInitParameterNames();
for (int i = 0; initParams.hasMoreElements(); i++) {
System.out.println("param " + i + ": " +
initParams.nextElement());
}
if (config.getInitParameter("xsltforms_dir") == null) {
throw new UnavailableException("xsltforms_dir init-param not
found");
}
if (config.getInitParameter("xsltforms_baseurl") == null) {
throw new UnavailableException(
"xsltforms_baseurl init-param not found");
}
// create the XSLTforms Transformer
TransformerFactory transFactory = TransformerFactory.newInstance();
String xmlStylesheet = null;
try {
String path = config.getServletContext()
.getRealPath(
config.getInitParameter("xsltforms_dir")
+ "/xsltforms.xsl");
File stylesheet = new File(path);
if (!stylesheet.exists()) {
throw new UnavailableException(
"XSLTForms stylesheet not found at: " + path);
}
this.templates = transFactory.newTemplates(new StreamSource(
stylesheet));
} catch (TransformerConfigurationException tce) {
tce.printStackTrace();
throw new UnavailableException("Unable to compile stylesheet");
}
}
public void destroy() {
this.filterConfig = null;
this.templates = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String formName = ((HttpServletRequest) request).getRequestURI();
formName = formName.substring(formName.lastIndexOf("/") + 1);
String format = ((HttpServletRequest)
request).getParameter("format");
if (format == null)
format = "raw";
System.out.println("form=" + formName);
System.out.println("format=" + format);
if (format != null && !format.matches("((raw)|(html))")) {
throw new ServletException(
"expecting format parameter to be raw or html");
} else {
String method = ((HttpServletRequest) request).getMethod();
if (method.matches("(?i:(PUT)|(POST)|(DELETE))")) {
// invalidate the cached version
cache.remove(formName);
chain.doFilter(request, response);
} else if (method.matches("(?i:(GET))")) {
// check if the raw xml is required
if (format == "raw") {
// pass on the request
response.setContentType("text/xml");
chain.doFilter(request, response);
} else {
// check if there is a cached version
if (cache.containsKey(formName)) {
String formHTML = cache.get(formName);
response.setContentType("text/html");
response.setContentLength(formHTML.length());
response.getWriter().write(formHTML);
} else {
BufferedHttpServletResponseWrapper responseWrapper
= new BufferedHttpServletResponseWrapper(
(HttpServletResponse) response);
chain.doFilter(request, responseWrapper);
byte[] bytes = responseWrapper.toByteArray();
//System.out.println("RESPONSE -> " + new
String(bytes));
// do the transform
try {
Transformer trans = templates.newTransformer();
ErrorListener listener = new
ErrorListenerImpl();
trans.setErrorListener(listener);
trans.setParameter("baseuri", filterConfig
.getInitParameter("xsltforms_baseurl"));
CharArrayWriter caw = new CharArrayWriter();
trans.transform(new StreamSource(new
StringReader(
new String(bytes))), new
StreamResult(caw));
String formHTML = caw.toString();
response.setContentType("text/html");
response.setContentLength(formHTML.length());
response.getOutputStream().write(formHTML.getBytes("UTF-8"));
cache.put(formName, formHTML);
} catch (TransformerException e) {
throw new ServletException(e);
}
}
}
} else { // not GET|POST|PUT|DELETE HTTP method
chain.doFilter(request, response);
}
}
}
private static class ByteArrayServletStream extends ServletOutputStream
{
ByteArrayOutputStream baos;
ByteArrayServletStream(ByteArrayOutputStream baos) {
this.baos = baos;
}
public void write(int param) throws IOException {
baos.write(param);
}
}
private class BufferedHttpServletResponseWrapper extends
HttpServletResponseWrapper {
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
private PrintWriter pw = new PrintWriter(baos);
private ServletOutputStream sos = new ByteArrayServletStream(baos);
private boolean isWriter = false;
private boolean isStream = false;
public BufferedHttpServletResponseWrapper(HttpServletResponse
response) {
super(response);
}
@Override
public String toString() {
if (isWriter) {
return pw.toString();
} else if (isStream) {
return sos.toString();
} else {
return "";
}
}
@Override
public PrintWriter getWriter() {
isWriter = true;
return pw;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
isStream = true;
return sos;
}
byte[] toByteArray() {
return baos.toByteArray();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="
http://java.sun.com/xml/ns/javaee" xmlns:web="
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>XForms</display-name>
<context-param>
<param-name>javax.xml.transform.TransformerFactory</param-name>
<param-value>net.sf.saxon.TransformerFactoryImpl</param-value>
</context-param>
<servlet>
<servlet-name>XSLTFormsServlet</servlet-name>
<servlet-class>net.sourceforge.schema2xforms.XSLTFormsTransformerServlet</servlet-class>
<init-param>
<description></description>
<param-name>xsltforms_dir</param-name>
<param-value>/xsltforms</param-value>
</init-param>
<init-param>
<description></description>
<param-name>xsltforms_baseurl</param-name>
<param-value>http://localhost:8080/XForms/xsltforms/
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>SimpleRESTServlet</servlet-name>
<servlet-class>net.sourceforge.schema2xforms.SimpleRESTServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<filter>
<filter-name>XSLTFormsCachingFilter</filter-name>
<filter-class>net.sourceforge.schema2xforms.XSLTFormsTransformerCachingServletFilter</filter-class>
<init-param>
<param-name>xsltforms_dir</param-name>
<param-value>/xsltforms</param-value>
</init-param>
<init-param>
<param-name>xsltforms_baseurl</param-name>
<param-value>http://localhost:8080/XForms/xsltforms/
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>XSLTFormsCachingFilter</filter-name>
<url-pattern>/forms/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>SimpleRESTServlet</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>
</web-app>
first cut.
It needs the format=html query parameter to give you the cached translated
form.
So, a URL will be something like
http://thedomain.org/appcontext/forms/form.xml
or
http://thedomain.org/appcontext/forms/form.xml?format=html
The later being what I wanted to avoid for obvious reasons, but I cannot
get around it and have the behaviour that I'm seeking.
The web.xml follows the Java code. The SimpleRESTServlet can be replaced
with whatever you use to persist the raw XML forms.
It needs more work, use at own risk, comments welcomed.
Steve Cameron
package net.sourceforge.schema2xforms;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public final class XSLTFormsTransformerCachingServletFilter implements
Filter {
private FilterConfig filterConfig = null;
private Templates templates;
private static FormCache cache = new FormCache();
public void init(FilterConfig config) throws UnavailableException,
ServletException {
this.filterConfig = config;
String factory = config
.getInitParameter("javax.xml.transform.TransformerFactory");
System.out.println(factory);
if (factory != null) {
System.setProperty("javax.xml.transform.TransformerFactory",
factory);
}
Enumeration<String> initParams = config.getInitParameterNames();
for (int i = 0; initParams.hasMoreElements(); i++) {
System.out.println("param " + i + ": " +
initParams.nextElement());
}
if (config.getInitParameter("xsltforms_dir") == null) {
throw new UnavailableException("xsltforms_dir init-param not
found");
}
if (config.getInitParameter("xsltforms_baseurl") == null) {
throw new UnavailableException(
"xsltforms_baseurl init-param not found");
}
// create the XSLTforms Transformer
TransformerFactory transFactory = TransformerFactory.newInstance();
String xmlStylesheet = null;
try {
String path = config.getServletContext()
.getRealPath(
config.getInitParameter("xsltforms_dir")
+ "/xsltforms.xsl");
File stylesheet = new File(path);
if (!stylesheet.exists()) {
throw new UnavailableException(
"XSLTForms stylesheet not found at: " + path);
}
this.templates = transFactory.newTemplates(new StreamSource(
stylesheet));
} catch (TransformerConfigurationException tce) {
tce.printStackTrace();
throw new UnavailableException("Unable to compile stylesheet");
}
}
public void destroy() {
this.filterConfig = null;
this.templates = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String formName = ((HttpServletRequest) request).getRequestURI();
formName = formName.substring(formName.lastIndexOf("/") + 1);
String format = ((HttpServletRequest)
request).getParameter("format");
if (format == null)
format = "raw";
System.out.println("form=" + formName);
System.out.println("format=" + format);
if (format != null && !format.matches("((raw)|(html))")) {
throw new ServletException(
"expecting format parameter to be raw or html");
} else {
String method = ((HttpServletRequest) request).getMethod();
if (method.matches("(?i:(PUT)|(POST)|(DELETE))")) {
// invalidate the cached version
cache.remove(formName);
chain.doFilter(request, response);
} else if (method.matches("(?i:(GET))")) {
// check if the raw xml is required
if (format == "raw") {
// pass on the request
response.setContentType("text/xml");
chain.doFilter(request, response);
} else {
// check if there is a cached version
if (cache.containsKey(formName)) {
String formHTML = cache.get(formName);
response.setContentType("text/html");
response.setContentLength(formHTML.length());
response.getWriter().write(formHTML);
} else {
BufferedHttpServletResponseWrapper responseWrapper
= new BufferedHttpServletResponseWrapper(
(HttpServletResponse) response);
chain.doFilter(request, responseWrapper);
byte[] bytes = responseWrapper.toByteArray();
//System.out.println("RESPONSE -> " + new
String(bytes));
// do the transform
try {
Transformer trans = templates.newTransformer();
ErrorListener listener = new
ErrorListenerImpl();
trans.setErrorListener(listener);
trans.setParameter("baseuri", filterConfig
.getInitParameter("xsltforms_baseurl"));
CharArrayWriter caw = new CharArrayWriter();
trans.transform(new StreamSource(new
StringReader(
new String(bytes))), new
StreamResult(caw));
String formHTML = caw.toString();
response.setContentType("text/html");
response.setContentLength(formHTML.length());
response.getOutputStream().write(formHTML.getBytes("UTF-8"));
cache.put(formName, formHTML);
} catch (TransformerException e) {
throw new ServletException(e);
}
}
}
} else { // not GET|POST|PUT|DELETE HTTP method
chain.doFilter(request, response);
}
}
}
private static class ByteArrayServletStream extends ServletOutputStream
{
ByteArrayOutputStream baos;
ByteArrayServletStream(ByteArrayOutputStream baos) {
this.baos = baos;
}
public void write(int param) throws IOException {
baos.write(param);
}
}
private class BufferedHttpServletResponseWrapper extends
HttpServletResponseWrapper {
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
private PrintWriter pw = new PrintWriter(baos);
private ServletOutputStream sos = new ByteArrayServletStream(baos);
private boolean isWriter = false;
private boolean isStream = false;
public BufferedHttpServletResponseWrapper(HttpServletResponse
response) {
super(response);
}
@Override
public String toString() {
if (isWriter) {
return pw.toString();
} else if (isStream) {
return sos.toString();
} else {
return "";
}
}
@Override
public PrintWriter getWriter() {
isWriter = true;
return pw;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
isStream = true;
return sos;
}
byte[] toByteArray() {
return baos.toByteArray();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="
http://java.sun.com/xml/ns/javaee" xmlns:web="
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>XForms</display-name>
<context-param>
<param-name>javax.xml.transform.TransformerFactory</param-name>
<param-value>net.sf.saxon.TransformerFactoryImpl</param-value>
</context-param>
<servlet>
<servlet-name>XSLTFormsServlet</servlet-name>
<servlet-class>net.sourceforge.schema2xforms.XSLTFormsTransformerServlet</servlet-class>
<init-param>
<description></description>
<param-name>xsltforms_dir</param-name>
<param-value>/xsltforms</param-value>
</init-param>
<init-param>
<description></description>
<param-name>xsltforms_baseurl</param-name>
<param-value>http://localhost:8080/XForms/xsltforms/
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>SimpleRESTServlet</servlet-name>
<servlet-class>net.sourceforge.schema2xforms.SimpleRESTServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<filter>
<filter-name>XSLTFormsCachingFilter</filter-name>
<filter-class>net.sourceforge.schema2xforms.XSLTFormsTransformerCachingServletFilter</filter-class>
<init-param>
<param-name>xsltforms_dir</param-name>
<param-value>/xsltforms</param-value>
</init-param>
<init-param>
<param-name>xsltforms_baseurl</param-name>
<param-value>http://localhost:8080/XForms/xsltforms/
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>XSLTFormsCachingFilter</filter-name>
<url-pattern>/forms/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>SimpleRESTServlet</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>
</web-app>