Search in sources :

Example 1 with ReceiverToSAX

use of org.exist.util.serializer.ReceiverToSAX in project exist by eXist-db.

the class Serializer method setStylesheet.

/**
 *  Plug an XSL stylesheet into the processing pipeline.
 *  All output will be passed to this stylesheet.
 *
 * @param doc the document
 * @param stylesheet the stylesheet
 *
 * @throws TransformerConfigurationException if the stylesheet cannot be set
 */
public void setStylesheet(Document doc, String stylesheet) throws TransformerConfigurationException {
    if (stylesheet == null) {
        templates = null;
        return;
    }
    final long start = System.currentTimeMillis();
    xslHandler = null;
    XmldbURI stylesheetUri = null;
    URI externalUri = null;
    try {
        stylesheetUri = XmldbURI.xmldbUriFor(stylesheet);
        if (!stylesheetUri.toCollectionPathURI().equals(stylesheetUri)) {
            externalUri = stylesheetUri.getXmldbURI();
        }
    } catch (final URISyntaxException e) {
        // could be an external URI!
        try {
            externalUri = new URI(stylesheet);
        } catch (final URISyntaxException ee) {
            throw new IllegalArgumentException("Stylesheet URI could not be parsed: " + ee.getMessage());
        }
    }
    // does stylesheet point to an external resource?
    if (externalUri != null) {
        final StreamSource source = new StreamSource(externalUri.toString());
        this.templates = factory.get().newTemplates(source);
    // read stylesheet from the database
    } else {
        // current collection and normalize
        if (doc != null && doc instanceof DocumentImpl) {
            stylesheetUri = ((DocumentImpl) doc).getCollection().getURI().resolveCollectionPath(stylesheetUri).normalizeCollectionPath();
        }
        // load stylesheet from eXist
        DocumentImpl xsl = null;
        try {
            xsl = broker.getResource(stylesheetUri, Permission.READ);
        } catch (final PermissionDeniedException e) {
            throw new TransformerConfigurationException("permission denied to read " + stylesheetUri);
        }
        if (xsl == null) {
            throw new TransformerConfigurationException("stylesheet not found: " + stylesheetUri);
        }
        // TODO: use xmldbURI
        if (xsl.getCollection() != null) {
            factory.get().setURIResolver(new InternalURIResolver(xsl.getCollection().getURI().toString()));
        }
        // save handlers
        Receiver oldReceiver = receiver;
        // compile stylesheet
        factory.get().setErrorListener(new ErrorListener());
        final TemplatesHandler handler = factory.get().newTemplatesHandler();
        receiver = new ReceiverToSAX(handler);
        try {
            this.serializeToReceiver(xsl, true);
            templates = handler.getTemplates();
        } catch (final SAXException e) {
            throw new TransformerConfigurationException(e.getMessage(), e);
        }
        // restore handlers
        receiver = oldReceiver;
        factory.get().setURIResolver(null);
    }
    LOG.debug("compiling stylesheet took {}", System.currentTimeMillis() - start);
    if (templates != null) {
        xslHandler = factory.get().newTransformerHandler(templates);
        try {
            xslHandler.startDocument();
            documentStarted = true;
        } catch (final SAXException e) {
            throw new TransformerConfigurationException(e.getMessage(), e);
        }
    }
    // xslHandler.getTransformer().setOutputProperties(outputProperties);
    checkStylesheetParams();
}
Also used : TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ReceiverToSAX(org.exist.util.serializer.ReceiverToSAX) StreamSource(javax.xml.transform.stream.StreamSource) Receiver(org.exist.util.serializer.Receiver) TemplatesHandler(javax.xml.transform.sax.TemplatesHandler) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) XmldbURI(org.exist.xmldb.XmldbURI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) SAXException(org.xml.sax.SAXException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 2 with ReceiverToSAX

use of org.exist.util.serializer.ReceiverToSAX in project exist by eXist-db.

the class Serializer method setSAXHandlers.

/**
 * Set the ContentHandler to be used during serialization.
 *
 * @param  contentHandler the content handler
 * @param lexicalHandler the lexical handle
 */
public void setSAXHandlers(ContentHandler contentHandler, LexicalHandler lexicalHandler) {
    ReceiverToSAX toSAX = new ReceiverToSAX(contentHandler);
    toSAX.setLexicalHandler(lexicalHandler);
    if ("yes".equals(getProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes"))) {
        xinclude.setReceiver(toSAX);
        receiver = xinclude;
    } else {
        receiver = toSAX;
    }
}
Also used : ReceiverToSAX(org.exist.util.serializer.ReceiverToSAX)

Example 3 with ReceiverToSAX

use of org.exist.util.serializer.ReceiverToSAX in project exist by eXist-db.

the class Serializer method applyXSLHandler.

/**
 *  If an XSL stylesheet is present, plug it into
 *  the chain.
 *
 * @param writer the writer
 */
protected void applyXSLHandler(Writer writer) {
    final StreamResult result = new StreamResult(writer);
    xslHandler.setResult(result);
    if ("yes".equals(getProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes"))) {
        xinclude.setReceiver(new ReceiverToSAX(xslHandler));
        receiver = xinclude;
    } else {
        receiver = new ReceiverToSAX(xslHandler);
    }
}
Also used : StreamResult(javax.xml.transform.stream.StreamResult) ReceiverToSAX(org.exist.util.serializer.ReceiverToSAX)

Example 4 with ReceiverToSAX

use of org.exist.util.serializer.ReceiverToSAX in project exist by eXist-db.

the class Serializer method setXSLHandler.

protected void setXSLHandler(NodeProxy root, boolean applyFilters) {
    if (templates != null && xslHandler != null) {
        final SAXResult result = new SAXResult();
        boolean processXInclude = "yes".equals(getProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes"));
        final ReceiverToSAX filter;
        if (processXInclude) {
            final Receiver xincludeReceiver = xinclude.getReceiver();
            if (xincludeReceiver != null && xincludeReceiver instanceof SAXSerializer) {
                filter = new ReceiverToSAX((SAXSerializer) xincludeReceiver);
            } else {
                filter = (ReceiverToSAX) xincludeReceiver;
            }
        } else {
            filter = (ReceiverToSAX) receiver;
        }
        result.setHandler(filter.getContentHandler());
        result.setLexicalHandler(filter.getLexicalHandler());
        filter.setLexicalHandler(xslHandler);
        filter.setContentHandler(xslHandler);
        xslHandler.setResult(result);
        if (processXInclude) {
            xinclude.setReceiver(new ReceiverToSAX(xslHandler));
            receiver = xinclude;
        } else {
            receiver = new ReceiverToSAX(xslHandler);
        }
    }
    if (root != null && getHighlightingMode() != TAG_NONE) {
        final IndexController controller = broker.getIndexController();
        MatchListener listener = controller.getMatchListener(root);
        if (listener != null) {
            final MatchListener last = (MatchListener) listener.getLastInChain();
            last.setNextInChain(receiver);
            receiver = listener;
        }
    }
    if (applyFilters && root == null && customMatchListeners.getFirst() != null) {
        customMatchListeners.getLast().setNextInChain(receiver);
        receiver = customMatchListeners.getFirst();
    }
}
Also used : SAXResult(javax.xml.transform.sax.SAXResult) ReceiverToSAX(org.exist.util.serializer.ReceiverToSAX) IndexController(org.exist.indexing.IndexController) Receiver(org.exist.util.serializer.Receiver) SAXSerializer(org.exist.util.serializer.SAXSerializer) MatchListener(org.exist.indexing.MatchListener)

Example 5 with ReceiverToSAX

use of org.exist.util.serializer.ReceiverToSAX in project exist by eXist-db.

the class Transform method eval.

/* (non-Javadoc)
     * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
     */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final Properties attributes = new Properties();
    final Properties serializationProps = new Properties();
    final Properties stylesheetParams = new Properties();
    // Parameter 1 & 2
    final Sequence inputNode = args[0];
    final Item stylesheetItem = args[1].itemAt(0);
    // Parse 3rd parameter
    final Node options = args[2].isEmpty() ? null : ((NodeValue) args[2].itemAt(0)).getNode();
    if (options != null) {
        stylesheetParams.putAll(parseParameters(options));
    }
    // Parameter 4 when present
    if (getArgumentCount() >= 4) {
        final Sequence attrs = args[3];
        attributes.putAll(extractAttributes(attrs));
    }
    // Parameter 5 when present
    if (getArgumentCount() >= 5) {
        // extract serialization options
        final Sequence serOpts = args[4];
        serializationProps.putAll(extractSerializationProperties(serOpts));
    } else {
        context.checkOptions(serializationProps);
    }
    boolean expandXIncludes = "yes".equals(serializationProps.getProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes"));
    final XSLTErrorsListener<XPathException> errorListener = new XSLTErrorsListener<XPathException>(stopOnError, stopOnWarn) {

        @Override
        protected void raiseError(String error, Exception ex) throws XPathException {
            throw new XPathException(Transform.this, error, ex);
        }
    };
    // Setup handler and error listener
    final TransformerHandler handler = createHandler(stylesheetItem, stylesheetParams, attributes, errorListener);
    if (isCalledAs("transform")) {
        // transform:transform()
        final ValueSequence seq = new ValueSequence();
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final DocumentBuilderReceiver builderReceiver = new DocumentBuilderReceiver(builder, true);
            final SAXResult result = new SAXResult(builderReceiver);
            // preserve comments etc... from xslt output
            result.setLexicalHandler(builderReceiver);
            handler.setResult(result);
            final Receiver receiver = new ReceiverToSAX(handler);
            final Serializer serializer = context.getBroker().borrowSerializer();
            try {
                serializer.setProperties(serializationProps);
                serializer.setReceiver(receiver, true);
                if (expandXIncludes) {
                    String xiPath = serializationProps.getProperty(EXistOutputKeys.XINCLUDE_PATH);
                    if (xiPath != null && !xiPath.startsWith(XmldbURI.XMLDB_URI_PREFIX)) {
                        final Path f = Paths.get(xiPath).normalize();
                        if (!f.isAbsolute()) {
                            xiPath = Paths.get(context.getModuleLoadPath(), xiPath).normalize().toAbsolutePath().toString();
                        }
                    } else {
                        xiPath = context.getModuleLoadPath();
                    }
                    serializer.getXIncludeFilter().setModuleLoadPath(xiPath);
                }
                serializer.toSAX(inputNode, 1, inputNode.getItemCount(), false, false, 0, 0);
            } catch (final Exception e) {
                throw new XPathException(this, "Exception while transforming node: " + e.getMessage(), e);
            } finally {
                context.getBroker().returnSerializer(serializer);
            }
            errorListener.checkForErrors();
            Node next = builder.getDocument().getFirstChild();
            while (next != null) {
                seq.add((NodeValue) next);
                next = next.getNextSibling();
            }
            return seq;
        } finally {
            context.popDocumentContext();
        }
    } else {
        // transform:stream-transform()
        final Optional<ResponseWrapper> maybeResponse = Optional.ofNullable(context.getHttpContext()).map(XQueryContext.HttpContext::getResponse);
        if (!maybeResponse.isPresent()) {
            throw new XPathException(this, ErrorCodes.XPDY0002, "No response object found in the current XQuery context.");
        }
        final ResponseWrapper response = maybeResponse.get();
        if (!"org.exist.http.servlets.HttpResponseWrapper".equals(response.getClass().getName())) {
            throw new XPathException(this, ErrorCodes.XPDY0002, signatures[1] + " can only be used within the EXistServlet or XQueryServlet");
        }
        // setup the response correctly
        final String mediaType = handler.getTransformer().getOutputProperty("media-type");
        final String encoding = handler.getTransformer().getOutputProperty("encoding");
        if (mediaType != null) {
            if (encoding == null) {
                response.setContentType(mediaType);
            } else {
                response.setContentType(mediaType + "; charset=" + encoding);
            }
        }
        // do the transformation
        try {
            final OutputStream os = new BufferedOutputStream(response.getOutputStream());
            final StreamResult result = new StreamResult(os);
            handler.setResult(result);
            final Serializer serializer = context.getBroker().borrowSerializer();
            Receiver receiver = new ReceiverToSAX(handler);
            try {
                serializer.setProperties(serializationProps);
                if (expandXIncludes) {
                    XIncludeFilter xinclude = new XIncludeFilter(serializer, receiver);
                    String xiPath = serializationProps.getProperty(EXistOutputKeys.XINCLUDE_PATH);
                    if (xiPath != null) {
                        final Path f = Paths.get(xiPath).normalize();
                        if (!f.isAbsolute()) {
                            xiPath = Paths.get(context.getModuleLoadPath(), xiPath).normalize().toAbsolutePath().toString();
                        }
                    } else {
                        xiPath = context.getModuleLoadPath();
                    }
                    xinclude.setModuleLoadPath(xiPath);
                    receiver = xinclude;
                }
                serializer.setReceiver(receiver);
                serializer.toSAX(inputNode);
            } catch (final Exception e) {
                throw new XPathException(this, "Exception while transforming node: " + e.getMessage(), e);
            } finally {
                context.getBroker().returnSerializer(serializer);
            }
            errorListener.checkForErrors();
            os.close();
            // commit the response
            response.flushBuffer();
        } catch (final IOException e) {
            throw new XPathException(this, "IO exception while transforming node: " + e.getMessage(), e);
        }
        return Sequence.EMPTY_SEQUENCE;
    }
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) Node(org.w3c.dom.Node) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) ResponseWrapper(org.exist.http.servlets.ResponseWrapper) Properties(java.util.Properties) XIncludeFilter(org.exist.storage.serializers.XIncludeFilter) XSLTErrorsListener(org.exist.xslt.XSLTErrorsListener) BufferedOutputStream(java.io.BufferedOutputStream) Serializer(org.exist.storage.serializers.Serializer) Path(java.nio.file.Path) StreamResult(javax.xml.transform.stream.StreamResult) ReceiverToSAX(org.exist.util.serializer.ReceiverToSAX) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) Receiver(org.exist.util.serializer.Receiver) IOException(java.io.IOException) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) IOException(java.io.IOException) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) SAXResult(javax.xml.transform.sax.SAXResult)

Aggregations

ReceiverToSAX (org.exist.util.serializer.ReceiverToSAX)5 Receiver (org.exist.util.serializer.Receiver)3 SAXResult (javax.xml.transform.sax.SAXResult)2 StreamResult (javax.xml.transform.stream.StreamResult)2 BufferedOutputStream (java.io.BufferedOutputStream)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 Path (java.nio.file.Path)1 Properties (java.util.Properties)1 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)1 TemplatesHandler (javax.xml.transform.sax.TemplatesHandler)1 TransformerHandler (javax.xml.transform.sax.TransformerHandler)1 StreamSource (javax.xml.transform.stream.StreamSource)1 DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)1 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)1 DocumentImpl (org.exist.dom.persistent.DocumentImpl)1 ResponseWrapper (org.exist.http.servlets.ResponseWrapper)1 IndexController (org.exist.indexing.IndexController)1