dleslie 01/04/24 06:16:56
Modified: java/samples/servlet ApplyXSLT.java SimpleXSLTServlet.java
UseStylesheetParamServlet.java
Log:
1. Updated per comments by Albert Tsun about including
charset=UTF-8 in the SimpleServlet ContentType prior to gettting
a Print Writer from the response object.
2. Updated ApplyXSLT to use default output properties for anything
that the stylesheet does not supply for setting the ContentType.
3. Updated ApplyXSLT to be able to use a default Templates object
when an xslURL parameter is not included in the request
and the XML source doc does not include a stylesheet PI.
Useful for cases where the same stylesheet is being used for
many/most transformations performed by the servlet.
Revision Changes Path
1.17 +169 -96 xml-xalan/java/samples/servlet/ApplyXSLT.java
Index: ApplyXSLT.java
===================================================================
RCS file: /home/cvs/xml-xalan/java/samples/servlet/ApplyXSLT.java,v
retrieving revision 1.16
retrieving revision 1.17
diff -u -r1.16 -r1.17
--- ApplyXSLT.java 2001/03/07 18:22:04 1.16
+++ ApplyXSLT.java 2001/04/24 13:16:56 1.17
@@ -67,6 +67,7 @@
import org.apache.xalan.templates.Constants;
import org.apache.xalan.templates.StylesheetRoot;
+import org.apache.xalan.templates.OutputProperties;
// SAX2 Imports
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
@@ -81,6 +82,7 @@
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
+import javax.xml.transform.sax.SAXTransformerFactory;
import org.apache.xalan.transformer.TransformerImpl;
import org.apache.xalan.stree.SourceTreeHandler;
import org.apache.xpath.objects.XObject;
@@ -116,6 +118,8 @@
* @serial
*/
protected ApplyXSLTProperties ourDefaultParameters = null;
+ private boolean useDefaultTemplates = false;
+ private Templates defaultTemplates = null;
/**
* String representing the end of line characters for the System.
@@ -149,9 +153,28 @@
else
CURRENTDIR = System.getProperty("user.dir")+ FS;
- setDefaultParameters(config);
+ setDefaultParameters(config);
- setMediaProps(config.getInitParameter("mediaURL"));
+ setMediaProps(config.getInitParameter("mediaURL"));
+ String defaultXSL = config.getInitParameter("xslURL");
+ try
+ {
+ if (defaultXSL !=null && defaultXSL.length() > 0)
+ compileXSL(defaultXSL);
+ }
+ catch (Exception e){}
+ }
+
+ /**
+ * If a default setting exists for xslURL, create a Templates object
+ * for rapid transformations.
+ */
+ protected void compileXSL(String defaultXSL)
+ throws TransformerConfigurationException
+ {
+ TransformerFactory tFactory = TransformerFactory.newInstance();
+ defaultTemplates = tFactory.newTemplates(new StreamSource(defaultXSL));
+ useDefaultTemplates = true;
}
/**
@@ -273,7 +296,7 @@
*/
public void process(TransformerFactory tFactory,
- HttpServletRequest request,
+ HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, SAXException
{
@@ -285,10 +308,10 @@
// Listener to be used for all reporting
ApplyXSLTListener listener = new ApplyXSLTListener();
- listener.out.println("debug is " + debug);
+ listener.out.println("debug is " + debug);
- StreamSource xmlSource = null;
- StreamSource xslSource = null;
+ Source xmlSource = null;
+ Source xslSource = null;
try
{
if ((xmlSource = getDocument(request, listener)) == null)
@@ -306,17 +329,16 @@
}
// creating XSL Stylesheet
if (xmlSource != null)
- {
+ {
try
{
- if ((xslSource = getStylesheet(tFactory, request, xmlSource,
listener)) == null)
- {
+ if ((xslSource = getStylesheet(tFactory, request, xmlSource,
listener)) == null)
throw new ApplyXSLTException("getStylesheet() returned null",
- new NullPointerException(),
- response.SC_NOT_FOUND);
- }
- // For time being, must "reset" xmlSource after extracting
stylesheet PI
- xmlSource = getDocument(request, listener);
+ new NullPointerException(),
+ response.SC_NOT_FOUND);
+
+ // Must "reset" xmlSource (a StreamSource) after looking for
stylesheet PI
+ xmlSource = getDocument(request, listener);
}
catch (ApplyXSLTException axe)
{
@@ -328,19 +350,19 @@
}
// perform Transformation
- if ((xmlSource != null) && (xslSource != null))
+ if (useDefaultTemplates)
{
- try
- {
- listener.out.println("Performing transformation...");
-
- Templates templates = tFactory.newTemplates(xslSource);
- Transformer transformer = templates.newTransformer();
+ try
+ {
+ listener.out.println("Using default templates");
+ if (defaultTemplates == null)
{
- try
- {
+ listener.out.println("Must recompile default templates");
+ defaultTemplates = tFactory.newTemplates(xslSource);
+ }
+ Transformer transformer = defaultTemplates.newTransformer();
String contentType = null;
- contentType = getContentType(templates);
+ contentType = getContentType(defaultTemplates);
if (contentType != null);
response.setContentType(contentType);
@@ -355,6 +377,47 @@
if (debug)
writeLog(listener.getMessage(), response.SC_OK);
+
+ }
+ catch (Exception exc)
+ {
+ ApplyXSLTException axe = new ApplyXSLTException
+ ("Exception occurred during
Transformation:"
+ + EOL + listener.getMessage() + EOL
+ + exc.getMessage(),
+ exc,
+ response.SC_INTERNAL_SERVER_ERROR);
+ if (debug) writeLog(axe);
+ displayException(response, axe, debug);
+ }
+ }
+
+ else if ((xmlSource != null) && (xslSource != null))
+ {
+ try
+ {
+ listener.out.println("Performing transformation...");
+ Templates templates = tFactory.newTemplates(xslSource);
+ Transformer transformer = templates.newTransformer();
+
+ try
+ {
+ String contentType = null;
+ contentType = getContentType(templates);
+ if (contentType != null);
+ response.setContentType(contentType);
+
+ if (transformer instanceof TransformerImpl)
+ {
+ TransformerImpl transformerImpl =
(TransformerImpl)transformer;
+
transformerImpl.setQuietConflictWarnings(ourDefaultParameters.isNoCW(request));
+ }
+
+ setStylesheetParams(transformer, request);
+ transformer.transform(xmlSource, new
StreamResult(response.getOutputStream()));
+
+ if (debug)
+ writeLog(listener.getMessage(), response.SC_OK);
}
catch (Exception exc)
{
@@ -371,32 +434,31 @@
{
// transformer.reset();
} // end of try ... catch ... finally
- }
- }
- catch (/*org.xml.sax.SAX*/Exception saxExc)
- {
- ApplyXSLTException axe = new ApplyXSLTException
+ }
+ catch (/*org.xml.sax.SAX*/Exception saxExc)
+ {
+ ApplyXSLTException axe = new ApplyXSLTException
("Exception occurred during
ctor/Transformation:"
- + EOL + listener.getMessage() +
EOL
- + saxExc.getMessage(),
-
saxExc,
- response.SC_INTERNAL_SERVER_ERROR);
- if (debug) writeLog(axe);
- displayException(response, axe, debug);
- } // end of new try ... catch
- } // end of if((stylesheetRoot != null) ...
- if (debug)
- {
- time = System.currentTimeMillis() - time;
- writeLog(" No Conflict Warnings = " +
ourDefaultParameters.isNoCW(request) +
- " Transformation time: " + time + " ms", response.SC_OK);
+ + EOL + listener.getMessage() + EOL
+ + saxExc.getMessage(),
+ saxExc,
+ response.SC_INTERNAL_SERVER_ERROR);
+ if (debug) writeLog(axe);
+ displayException(response, axe, debug);
+ } // end of new try ... catch
+ } // end of if((stylesheetRoot != null) ...
+ if (debug)
+ {
+ time = System.currentTimeMillis() - time;
+ writeLog(" No Conflict Warnings = " +
ourDefaultParameters.isNoCW(request) +
+ " Transformation time: " + time + " ms", response.SC_OK);
+ }
}
- }
}
/**
- * Returns an XML XSLTInputSource DOM. Attempts will be make to create
the DOM from the following
- * sources:
+ * Returns a Source object with the XML document to be transformed.
Attempts will be make to create the
+ * Source object from the following:
* <ol>
* <li>A relative URL specified in the HTTP request's path information.
This capability is intended
* for use by <b>servlet engines that map</b> some or all XML data to be
processed at the server.</li>
@@ -405,12 +467,12 @@
* security reasons, this URL will be forced to the local IP host.</li>
* <li>The HTTP request's XML input stream. This capability is intended
for use by chained servlets.</li>
* </ol>
- * @param request May contain or point to the XML XSLTInputSource
+ * @param request client HTTPRequest object
* @param listener To record detailed parsing messages for possible return
to requestor
- * @return XML XSLTInputSource DOM, or null if the XSLTInputSource could
not be parsed
+ * @return Source with XML document to be transformed, or null if the
Source could not be located
* @exception ApplyXSLTException Thrown if exception occurs while handling
request
*/
- protected StreamSource getDocument(HttpServletRequest request,
+ protected Source getDocument(HttpServletRequest request,
ApplyXSLTListener listener)
throws ApplyXSLTException
{
@@ -451,34 +513,35 @@
}
/**
- * Returns a Templates (StylesheetRoot) object. Attempts will be make to
create the Stylesheet
- * from the followingsources:
+ * Returns a Source object containing the stylesheet. Attempts will be
make to obtain the stylesheet
+ * from the following sources:
* <ol>
- * <li>A URL specified in the HTTP request's <code>xslURL=</code>
parameter. This capability
- * is intended for clients wishing to selectively override the server
algorithm for applying XSL
- * stylesheets. For security reasons, this URL will be forced to the
local IP host.</li>
- * <li>XML association. XML documents may contain references to one or
more stylesheets using
- * <a HREF="http://www.w3.org/TR/1999/PR-xml-stylesheet-19990114">this</a>
W3C proposed recommendation.
+ * <li>A URL specified in the HTTP request's <code>xslURL=</code>
parameter. For security reasons,
+ * this URL will be forced to the local IP host.</li>
+ * <li>A URL specified in the XML document xsl:stylesheet Processing
Instruction. XML documents may contain
+ * Processing Instruction references to one or more stylesheets using the
+ * <a HREF="http://www.w3.org/TR/xml-stylesheet/>Associating Style Sheets
with XML documents</a>
+ * W3C ecommendation.
* If the XML document does contain such references, a best match will be
chosen based on the browser
* type making the request and the default association. This capability
enables relationships to be
* defined between client capabilities and stylesheets capable of acting
on these capabilities.</li>
- * <li>A configured default stylesheet URL</li>
+ * <li>A default stylesheet URL specified when the servlet is loaded.
During init(), the servlet
+ * uses this xslURL startup parameter to create a Templates object, which
is the used for transformations
+ * where no other stylesheet is designated.</li>
* </ol>
- * @param request May contain or point to the XSL XSLTInputSource
- * @param xmlSource May point to the XSL XSLTInputSource
+ * @param request the client HTTP request, which may include an xslURL
parameter
+ * @param xmlSource the XML document to be transformed
* @param listener To record detailed parsing messages for possible return
to requestor
- * @return XSL XSLTInputSource, or null if the request could not be parsed
- * @see #makeDocument
+ * @return Source, or null if the stylesheet could not be located.
* @see #getMedia
* @see #STYLESHEET_ATTRIBUTE
- * @see #getXSLURLfromDoc
* @see #toAcceptLanguageConnection
- * @exception ApplyXSLTException Thrown if exception occurs while handling
request
+ * @exception ApplyXSLTException Thrown if exception occurs while locating
the stylesheet
*/
- protected StreamSource getStylesheet(TransformerFactory tFactory,
-
HttpServletRequest request,
- StreamSource xmlSource,
- ApplyXSLTListener listener)
+ protected Source getStylesheet(TransformerFactory tFactory,
+
HttpServletRequest request,
+ Source xmlSource,
+ ApplyXSLTListener listener)
throws ApplyXSLTException
{
try
@@ -489,19 +552,26 @@
if (xslURL != null)
listener.out.println("Parsing XSL Stylesheet Document from request
parameter: "
+ xslURL);
- else
+ else
{
// find stylesheet from XML Document, Media tag preference
- if (xmlSource != null){
- listener.out.println("calling getXSLURLfromDoc and getMedia " +
getMedia(request) );
- xslURL = getXSLURLfromDoc(xmlSource, STYLESHEET_ATTRIBUTE,
getMedia(request), tFactory);
+ if (!useDefaultTemplates)
+ {
+ SAXTransformerFactory stf = (SAXTransformerFactory)tFactory;
+ Source styleSource =
+ stf.getAssociatedStylesheet(xmlSource,getMedia(request),
null, null);
+ if (styleSource != null)
+ {
+ listener.out.println("Parsing XSL Stylesheet from XML document
stylesheet PI.");
+ return styleSource;
+ }
+ }
+ // Configuration Default
+ if ((xslURL = ourDefaultParameters.getXSLurl(null)) != null)
+ {
+ listener.out.println("Parsing XSL Stylesheet Document from
configuration: " + xslURL);
+ useDefaultTemplates = true;
}
- if (xslURL != null)
- listener.out.println("Parsing XSL Stylesheet Document from XML
Document tag: " + xslURL);
- else
- // Configuration Default
- if ((xslURL = ourDefaultParameters.getXSLurl(null)) != null)
- listener.out.println("Parsing XSL Stylesheet Document from
configuration: " + xslURL);
}
return new StreamSource(xslURL);
}
@@ -518,6 +588,7 @@
/**
* Returns the response content type specified by the media-type and
encoding attributes of
* the <xsl:output> element(s) of the stylesheet.
+ * Default output property settings are used for any properties not set by
the stylesheet.
* @param xslSourceRoot XSL Stylesheet to be examined for <xsl:output>
elements.
* @return The response content type (MIME type and charset) of the
stylesheet output
* @see #process
@@ -525,24 +596,26 @@
public String getContentType(Templates templates)
{
Properties oprops = templates.getOutputProperties();
- String encoding = oprops.getProperty(OutputKeys.ENCODING);
- String media = oprops.getProperty(OutputKeys.MEDIA_TYPE);
- if (media != null)
- {
- if (encoding != null)
- return media + "; charset=" + encoding;
- return media;
- }
- else
- {
- String method = oprops.getProperty(OutputKeys.METHOD);
- if (method.equals("html"))
- return "text/html";
- else if (method.equals("text"))
- return "text/plain";
- else
- return "text/xml";
- }
+ String method = oprops.getProperty(OutputKeys.METHOD);
+ if (method == null) method = "xml"; // the default.
+
+ Properties defoprops = null;
+ if (method.equals("html"))
+ defoprops = OutputProperties.getDefaultMethodProperties("html");
+ else if (method.equals("text"))
+ defoprops = OutputProperties.getDefaultMethodProperties("text");
+ else
+ defoprops = OutputProperties.getDefaultMethodProperties("xml");
+
+ String encoding = oprops.getProperty(OutputKeys.ENCODING);
+ if (encoding == null)
+ encoding = defoprops.getProperty(OutputKeys.ENCODING);
+
+ String media = oprops.getProperty(OutputKeys.MEDIA_TYPE);
+ if (media == null)
+ media = defoprops.getProperty(OutputKeys.MEDIA_TYPE);
+
+ return media + "; charset=" + encoding;
}
@@ -747,7 +820,7 @@
* @return The preferred XSL stylesheet URL, or null if no XSL stylesheet
association is found
* @see #getStylesheet
*/
- public static String getXSLURLfromDoc(StreamSource xmlSource,
+/* public static String getXSLURLfromDoc(StreamSource xmlSource,
String attributeName,
String attributeValue,
TransformerFactory tFactory)
@@ -784,7 +857,7 @@
}
return returnURL;
}
-
+*/
/**
* The attribute name in the <?xml-stylesheet> tag used in stylesheet
selection.
*/
1.3 +4 -4 xml-xalan/java/samples/servlet/SimpleXSLTServlet.java
Index: SimpleXSLTServlet.java
===================================================================
RCS file: /home/cvs/xml-xalan/java/samples/servlet/SimpleXSLTServlet.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- SimpleXSLTServlet.java 2001/03/07 18:22:08 1.2
+++ SimpleXSLTServlet.java 2001/04/24 13:16:56 1.3
@@ -86,12 +86,12 @@
public void doGet (HttpServletRequest request,
HttpServletResponse response)
- throws ServletException, IOException
+ throws ServletException, IOException, java.net.MalformedURLException
{
- // Output goes in the response stream.
- PrintWriter out = new PrintWriter (response.getOutputStream());
// The servlet returns HTML.
- response.setContentType("text/html");
+ response.setContentType("text/html; charset=UTF-8");
+ // Output goes in the response stream.
+ PrintWriter out = response.getWriter();
try
{
TransformerFactory tFactory = TransformerFactory.newInstance();
1.2 +1 -1
xml-xalan/java/samples/servlet/UseStylesheetParamServlet.java
Index: UseStylesheetParamServlet.java
===================================================================
RCS file:
/home/cvs/xml-xalan/java/samples/servlet/UseStylesheetParamServlet.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- UseStylesheetParamServlet.java 2001/03/20 17:03:19 1.1
+++ UseStylesheetParamServlet.java 2001/04/24 13:16:56 1.2
@@ -27,7 +27,7 @@
HttpServletResponse res)
throws ServletException, IOException {
try {
- res.setContentType("text/html");
+ res.setContentType("text/html; charset=UTF-8");
out = res.getWriter();
paramValue = req.getParameter("PVAL");
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]