Search in sources :

Example 1 with Receiver

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

the class SystemExport method exportDocument.

private void exportDocument(final BackupHandler bh, final BackupWriter output, final Date date, final BackupDescriptor prevBackup, final SAXSerializer serializer, final int docsCount, final int count, final DocumentImpl doc) throws IOException, SAXException, TerminatedException {
    if (callback != null) {
        callback.startDocument(doc.getFileURI().toString(), count, docsCount);
    }
    if ((monitor != null) && !monitor.proceed()) {
        throw (new TerminatedException("system export terminated by db"));
    }
    final boolean needsBackup = (prevBackup == null) || (date.getTime() < doc.getLastModified());
    if (needsBackup) {
        // Note: do not auto-close the output stream or the zip will be closed!
        try {
            final OutputStream os = output.newEntry(Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
            if (doc.getResourceType() == DocumentImpl.BINARY_FILE) {
                broker.readBinaryResource((BinaryDocument) doc, os);
            } else {
                final SAXSerializer contentSerializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
                final Writer writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
                try {
                    // write resource to contentSerializer
                    contentSerializer.setOutput(writer, defaultOutputProperties);
                    final Receiver receiver;
                    if (chainFactory != null) {
                        chainFactory.getLast().setNextInChain(contentSerializer);
                        receiver = chainFactory.getFirst();
                    } else {
                        receiver = contentSerializer;
                    }
                    writeXML(doc, receiver);
                } finally {
                    SerializerPool.getInstance().returnObject(contentSerializer);
                    writer.flush();
                }
            }
        } catch (final Exception e) {
            reportError("A write error occurred while exporting document: '" + doc.getFileURI() + "'. Continuing with next document.", e);
            return;
        } finally {
            output.closeEntry();
        }
    }
    final Permission perms = doc.getPermissions();
    // store permissions
    final AttributesImpl attr = new AttributesImpl();
    attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", (doc.getResourceType() == DocumentImpl.BINARY_FILE) ? "BinaryResource" : "XMLResource");
    attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", doc.getFileURI().toString());
    attr.addAttribute(Namespaces.EXIST_NS, "skip", "skip", "CDATA", (needsBackup ? "no" : "yes"));
    Backup.writeUnixStylePermissionAttributes(attr, perms);
    try {
        final String created = new DateTimeValue(new Date(doc.getCreated())).getStringValue();
        final String modified = new DateTimeValue(new Date(doc.getLastModified())).getStringValue();
        attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", created);
        attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", modified);
    } catch (final XPathException e) {
        LOG.warn(e.getMessage(), e);
    }
    attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
    String mimeType = "application/xml";
    if (doc.getMimeType() != null) {
        mimeType = Backup.encode(doc.getMimeType());
    }
    attr.addAttribute(Namespaces.EXIST_NS, "mimetype", "mimetype", "CDATA", mimeType);
    // output by serializer
    // if( ( doc.getResourceType() == DocumentImpl.XML_FILE ) && ( metadata != null ) && ( doc.getDoctype() != null ) ) {
    // 
    // if( doc.getDoctype().getName() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "namedoctype", "namedoctype", "CDATA", doc.getDoctype().getName() );
    // }
    // 
    // if( doc.getDoctype().getPublicId() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "publicid", "publicid", "CDATA", doc.getDoctype().getPublicId() );
    // }
    // 
    // if( doc.getDoctype().getSystemId() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "systemid", "systemid", "CDATA", doc.getDoctype().getSystemId() );
    // }
    // }
    bh.backup(doc, attr);
    serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr);
    if (perms instanceof ACLPermission) {
        Backup.writeACLPermission(serializer, (ACLPermission) perms);
    }
    bh.backup(doc, serializer);
    serializer.endElement(Namespaces.EXIST_NS, "resource", "resource");
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) ACLPermission(org.exist.security.ACLPermission) Receiver(org.exist.util.serializer.Receiver) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) TerminatedException(org.exist.xquery.TerminatedException) XMLStreamException(javax.xml.stream.XMLStreamException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) SAXSerializer(org.exist.util.serializer.SAXSerializer) TerminatedException(org.exist.xquery.TerminatedException)

Example 2 with Receiver

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

the class Serializer method toReceiver.

public void toReceiver(NodeProxy p, boolean highlightMatches, boolean checkAttributes) throws SAXException {
    Receiver oldReceiver = highlightMatches ? setupMatchListeners(p) : receiver;
    serializeToReceiver(p, false, checkAttributes);
    receiver = oldReceiver;
}
Also used : Receiver(org.exist.util.serializer.Receiver)

Example 3 with Receiver

use of org.exist.util.serializer.Receiver 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 4 with Receiver

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

the class HighlightMatches method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (args[0].isEmpty())
        return Sequence.EMPTY_SEQUENCE;
    context.pushDocumentContext();
    final Serializer serializer = context.getBroker().borrowSerializer();
    try (FunctionReference func = (FunctionReference) args[1].itemAt(0)) {
        MemTreeBuilder builder = context.getDocumentBuilder();
        NGramIndexWorker index = (NGramIndexWorker) context.getBroker().getIndexController().getWorkerByIndexId(NGramIndex.ID);
        DocumentBuilderReceiver docBuilder = new DocumentBuilderReceiver(builder);
        MatchCallback matchCb = new MatchCallback(func, docBuilder);
        ValueSequence result = new ValueSequence();
        for (SequenceIterator i = args[0].iterate(); i.hasNext(); ) {
            NodeValue v = (NodeValue) i.nextItem();
            try {
                int nodeNr = builder.getDocument().getLastNode();
                if (v.getImplementationType() == NodeValue.IN_MEMORY_NODE) {
                    ((NodeImpl) v).copyTo(context.getBroker(), docBuilder);
                } else {
                    NodeProxy p = (NodeProxy) v;
                    MatchListener ml = index.getMatchListener(context.getBroker(), p, matchCb);
                    Receiver receiver;
                    if (ml == null)
                        receiver = docBuilder;
                    else {
                        ml.setNextInChain(docBuilder);
                        receiver = ml;
                    }
                    serializer.setReceiver(receiver);
                    serializer.toReceiver((NodeProxy) v, false);
                }
                result.add(builder.getDocument().getNode(++nodeNr));
            } catch (SAXException e) {
                LOG.warn(e.getMessage(), e);
                throw new XPathException(this, e.getMessage());
            }
        }
        return result;
    } finally {
        context.getBroker().returnSerializer(serializer);
        context.popDocumentContext();
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) NodeImpl(org.exist.dom.memtree.NodeImpl) XPathException(org.exist.xquery.XPathException) NGramIndexWorker(org.exist.indexing.ngram.NGramIndexWorker) NGramMatchCallback(org.exist.indexing.ngram.NGramMatchCallback) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) Receiver(org.exist.util.serializer.Receiver) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) NodeProxy(org.exist.dom.persistent.NodeProxy) SAXException(org.xml.sax.SAXException) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) SequenceIterator(org.exist.xquery.value.SequenceIterator) ValueSequence(org.exist.xquery.value.ValueSequence) FunctionReference(org.exist.xquery.value.FunctionReference) MatchListener(org.exist.indexing.MatchListener) Serializer(org.exist.storage.serializers.Serializer)

Example 5 with Receiver

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

the class AbstractMatchListener method getLastInChain.

@Override
public Receiver getLastInChain() {
    Receiver last = this;
    Receiver next = getNextInChain();
    while (next != null) {
        last = next;
        next = ((MatchListener) next).getNextInChain();
    }
    return last;
}
Also used : Receiver(org.exist.util.serializer.Receiver)

Aggregations

Receiver (org.exist.util.serializer.Receiver)9 MatchListener (org.exist.indexing.MatchListener)3 ReceiverToSAX (org.exist.util.serializer.ReceiverToSAX)3 SAXException (org.xml.sax.SAXException)3 SAXResult (javax.xml.transform.sax.SAXResult)2 DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)2 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)2 IndexController (org.exist.indexing.IndexController)2 PermissionDeniedException (org.exist.security.PermissionDeniedException)2 Serializer (org.exist.storage.serializers.Serializer)2 SAXSerializer (org.exist.util.serializer.SAXSerializer)2 XPathException (org.exist.xquery.XPathException)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 XMLStreamException (javax.xml.stream.XMLStreamException)1