use of org.exist.xslt.Stylesheet in project exist by eXist-db.
the class Transform method createHandler.
/**
* @param stylesheetItem
* @param options
* @param attributes Attributes to set on the Transformer Factory
* @throws TransformerFactoryConfigurationError
* @throws XPathException
*/
private TransformerHandler createHandler(Item stylesheetItem, Properties options, Properties attributes, XSLTErrorsListener<XPathException> errorListener) throws TransformerFactoryConfigurationError, XPathException {
boolean useCache = true;
final Object property = context.getBroker().getConfiguration().getProperty(TransformerFactoryAllocator.PROPERTY_CACHING_ATTRIBUTE);
if (property != null) {
useCache = (Boolean) property;
}
TransformerHandler handler;
try {
Stylesheet stylesheet = null;
if (Type.subTypeOf(stylesheetItem.getType(), Type.NODE)) {
final NodeValue stylesheetNode = (NodeValue) stylesheetItem;
// we construct an XMLDB URI and use the caching implementation.
if (stylesheetNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
final NodeProxy root = (NodeProxy) stylesheetNode;
if (root.getNodeId() == NodeId.DOCUMENT_NODE || root.getNodeId().getTreeLevel() == 1) {
final String uri = XmldbURI.XMLDB_URI_PREFIX + context.getBroker().getBrokerPool().getId() + "://" + root.getOwnerDocument().getURI();
stylesheet = TemplatesFactory.stylesheet(uri, context.getModuleLoadPath(), attributes, useCache);
}
}
if (stylesheet == null) {
stylesheet = TemplatesFactory.stylesheet(getContext().getBroker(), stylesheetNode, context.getModuleLoadPath());
}
} else {
String baseUri = context.getModuleLoadPath();
if (stylesheetItem instanceof Document) {
baseUri = ((Document) stylesheetItem).getDocumentURI();
/*
* This must be checked because in the event the stylesheet is
* an in-memory document, it will cause an NPE
*/
if (baseUri == null) {
baseUri = context.getModuleLoadPath();
} else {
baseUri = baseUri.substring(0, baseUri.lastIndexOf('/'));
}
}
final String uri = stylesheetItem.getStringValue();
stylesheet = TemplatesFactory.stylesheet(uri, baseUri, attributes, useCache);
}
handler = stylesheet.newTransformerHandler(getContext().getBroker(), errorListener);
if (options != null) {
setParameters(options, handler.getTransformer());
}
} catch (final Exception e) {
if (e instanceof XPathException) {
throw (XPathException) e;
}
throw new XPathException(this, "Unable to set up transformer: " + e.getMessage(), e);
}
return handler;
}
use of org.exist.xslt.Stylesheet in project exist by eXist-db.
the class XSLTServlet method doPost.
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final String uri = (String) request.getAttribute(REQ_ATTRIBUTE_STYLESHEET);
if (uri == null) {
throw new ServletException("No stylesheet source specified!");
}
Item inputNode = null;
final String sourceAttrib = (String) request.getAttribute(REQ_ATTRIBUTE_INPUT);
if (sourceAttrib != null) {
Object sourceObj = request.getAttribute(sourceAttrib);
if (sourceObj != null) {
if (sourceObj instanceof ValueSequence) {
final ValueSequence seq = (ValueSequence) sourceObj;
if (seq.size() == 1) {
sourceObj = seq.itemAt(0);
}
}
if (sourceObj instanceof Item) {
inputNode = (Item) sourceObj;
if (!Type.subTypeOf(inputNode.getType(), Type.NODE)) {
throw new ServletException("Input for XSLT servlet is not a node. Read from attribute " + sourceAttrib);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Taking XSLT input from request attribute {}", sourceAttrib);
}
} else {
throw new ServletException("Input for XSLT servlet is not a node. Read from attribute " + sourceAttrib);
}
}
}
try {
pool = BrokerPool.getInstance();
} catch (final EXistException e) {
throw new ServletException(e.getMessage(), e);
}
Subject user = pool.getSecurityManager().getGuestSubject();
Subject requestUser = HttpAccount.getUserFromServletRequest(request);
if (requestUser != null) {
user = requestUser;
}
// Retrieve username / password from HTTP request attributes
final String userParam = (String) request.getAttribute("xslt.user");
final String passwd = (String) request.getAttribute("xslt.password");
if (userParam != null) {
try {
user = pool.getSecurityManager().authenticate(userParam, passwd);
} catch (final AuthenticationException e1) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Wrong password or user");
return;
}
}
final Stylesheet stylesheet = stylesheet(uri, request, response);
if (stylesheet == null) {
return;
}
// do the transformation
try (final DBBroker broker = pool.get(Optional.of(user))) {
final TransformerHandler handler = stylesheet.newTransformerHandler(broker, errorListener);
setTransformerParameters(request, handler.getTransformer());
final Properties properties = handler.getTransformer().getOutputProperties();
setOutputProperties(request, properties);
String encoding = properties.getProperty("encoding");
if (encoding == null) {
encoding = "UTF-8";
}
response.setCharacterEncoding(encoding);
final String mediaType = properties.getProperty("media-type");
if (mediaType != null) {
// check, do mediaType have "charset"
if (!mediaType.contains("charset")) {
response.setContentType(mediaType + "; charset=" + encoding);
} else {
response.setContentType(mediaType);
}
}
final SAXSerializer sax = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
final Writer writer = new BufferedWriter(response.getWriter());
sax.setOutput(writer, properties);
final SAXResult result = new SAXResult(sax);
handler.setResult(result);
final Serializer serializer = broker.borrowSerializer();
Receiver receiver = new ReceiverToSAX(handler);
try {
XIncludeFilter xinclude = new XIncludeFilter(serializer, receiver);
receiver = xinclude;
String baseUri;
final String base = (String) request.getAttribute(REQ_ATTRIBUTE_BASE);
if (base != null) {
baseUri = getServletContext().getRealPath(base);
} else if (uri.startsWith("xmldb:exist://")) {
baseUri = XmldbURI.xmldbUriFor(uri).getCollectionPath();
} else {
baseUri = getCurrentDir(request).toAbsolutePath().toString();
}
xinclude.setModuleLoadPath(baseUri);
serializer.setReceiver(receiver);
if (inputNode != null) {
serializer.toSAX((NodeValue) inputNode);
} else {
final SAXToReceiver saxreceiver = new SAXToReceiver(receiver);
final XMLReader reader = pool.getParserPool().borrowXMLReader();
try {
reader.setContentHandler(saxreceiver);
// Handle gziped input stream
InputStream stream;
InputStream inStream = new BufferedInputStream(request.getInputStream());
inStream.mark(10);
try {
stream = new GZIPInputStream(inStream);
} catch (final IOException e) {
inStream.reset();
stream = inStream;
}
reader.parse(new InputSource(stream));
} finally {
pool.getParserPool().returnXMLReader(reader);
}
}
} catch (final SAXParseException e) {
LOG.error(e.getMessage());
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
} catch (final SAXException e) {
throw new ServletException("SAX exception while transforming node: " + e.getMessage(), e);
} finally {
SerializerPool.getInstance().returnObject(sax);
broker.returnSerializer(serializer);
}
writer.flush();
response.flushBuffer();
} catch (final IOException e) {
throw new ServletException("IO exception while transforming node: " + e.getMessage(), e);
} catch (final TransformerException e) {
throw new ServletException("Exception while transforming node: " + e.getMessage(), e);
} catch (final Throwable e) {
LOG.error(e);
throw new ServletException("An error occurred: " + e.getMessage(), e);
}
}
Aggregations