use of org.exist.dom.persistent.DocumentImpl 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();
}
use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.
the class NativeStructuralIndexWorker method scanIndex.
/**
* Collect index statistics. Used by functions like util:index-keys.
*
* @param context the xquery context
* @param docs The documents to which the index entries belong
* @param contextSet ignored by this index
* @param hints Some "hints" for retrieving the index entries. See such hints in
* {@link org.exist.indexing.OrderedValuesIndex} and {@link org.exist.indexing.QNamedKeysIndex}.
* @return the matching occurrences
*/
public Occurrences[] scanIndex(XQueryContext context, DocumentSet docs, NodeSet contextSet, Map hints) {
final Map<String, Occurrences> occurrences = new TreeMap<>();
for (final Iterator<DocumentImpl> i = docs.getDocumentIterator(); i.hasNext(); ) {
final DocumentImpl doc = i.next();
final List<QName> qnames = getQNamesForDoc(doc);
for (final QName qname : qnames) {
final String name;
if (qname.getNameType() == ElementValue.ATTRIBUTE) {
name = "@" + qname.getLocalPart();
} else {
name = qname.getLocalPart();
}
final byte[] fromKey = computeKey(qname.getNameType(), qname, doc.getDocId());
final byte[] toKey = computeKey(qname.getNameType(), qname, doc.getDocId() + 1);
final IndexQuery query = new IndexQuery(IndexQuery.RANGE, new Value(fromKey), new Value(toKey));
try (final ManagedLock<ReentrantLock> btreeLock = index.lockManager.acquireBtreeReadLock(index.btree.getLockName())) {
index.btree.query(query, (value, pointer) -> {
Occurrences oc = occurrences.get(name);
if (oc == null) {
oc = new Occurrences(name);
occurrences.put(name, oc);
oc.addDocument(doc);
oc.addOccurrences(1);
} else {
oc.addOccurrences(1);
oc.addDocument(doc);
}
return true;
});
} catch (final LockException e) {
NativeStructuralIndex.LOG.warn("Failed to lock structural index: {}", e.getMessage(), e);
} catch (final Exception e) {
NativeStructuralIndex.LOG.warn("Exception caught while reading structural index for document {}: {}", doc.getURI(), e.getMessage(), e);
}
}
}
final Occurrences[] result = new Occurrences[occurrences.size()];
int i = 0;
for (Occurrences occ : occurrences.values()) {
result[i++] = occ;
}
return result;
}
use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.
the class XPathUtil method getNode.
/**
* Converts an XMLResource into a NodeProxy.
*
* @param broker The DBBroker to use to access the database
* @param xres The XMLResource to convert
* @return A NodeProxy for accessing the content represented by xres
* @throws XPathException if an XMLDBException is encountered
*/
public static final NodeProxy getNode(DBBroker broker, XMLResource xres) throws XPathException {
if (xres instanceof LocalXMLResource) {
final LocalXMLResource lres = (LocalXMLResource) xres;
try {
return lres.getNode();
} catch (final XMLDBException xe) {
throw new XPathException("Failed to convert LocalXMLResource to node: " + xe.getMessage());
}
}
DocumentImpl document;
try {
document = broker.getCollection(XmldbURI.xmldbUriFor(xres.getParentCollection().getName())).getDocument(broker, XmldbURI.xmldbUriFor(xres.getDocumentId()));
} catch (final URISyntaxException xe) {
throw new XPathException(xe);
} catch (final XMLDBException xe) {
throw new XPathException("Failed to get document for RemoteXMLResource: " + xe.getMessage());
} catch (final PermissionDeniedException pde) {
throw new XPathException("Failed to get document: " + pde.getMessage());
}
final NodeId nodeId = broker.getBrokerPool().getNodeFactory().createFromString(((RemoteXMLResource) xres).getNodeId());
return new NodeProxy(document, nodeId);
}
use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.
the class FunDoc method registerUpdateListener.
protected void registerUpdateListener() {
if (listener == null) {
listener = new UpdateListener() {
@Override
public void documentUpdated(DocumentImpl document, int event) {
// clear all
}
@Override
public void unsubscribe() {
FunDoc.this.listener = null;
}
public void nodeMoved(NodeId oldNodeId, NodeHandle newNode) {
// not relevant
}
@Override
public void debug() {
logger.debug("UpdateListener: Line: {}: {}", getLine(), FunDoc.this.toString());
}
};
context.registerUpdateListener(listener);
}
}
use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.
the class FunInScopePrefixes method collectPrefixes.
public static Map<String, String> collectPrefixes(XQueryContext context, NodeValue nodeValue) {
final Map<String, String> prefixes = new LinkedHashMap<>();
prefixes.put("xml", Namespaces.XML_NS);
final Map<String, String> inScopePrefixes = context.getInScopePrefixes();
if (inScopePrefixes != null) {
prefixes.putAll(inScopePrefixes);
}
if (nodeValue.getImplementationType() == NodeValue.PERSISTENT_NODE) {
// NodeProxy proxy = (NodeProxy) node;
Node node = nodeValue.getNode();
if (context.preserveNamespaces()) {
// Horrible hacks to work-around bad in-scope NS : we reconstruct a NS context !
if (context.inheritNamespaces()) {
// Grab ancestors' NS
final Deque<Element> stack = new ArrayDeque<>();
do {
stack.add((Element) node);
node = node.getParentNode();
} while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
while (!stack.isEmpty()) {
collectNamespacePrefixes(stack.pop(), prefixes);
}
/*
NodeSet ancestors = nodeValue.getAncestors(contextId, true);
for (Iterator i = ancestors.iterator(); i.hasNext(); ) {
proxy = (NodeProxy) i.next();
collectNamespacePrefixes((ElementImpl)node, prefixes);
}
*/
} else {
// Grab self's NS
if (node.getNodeType() == Node.ELEMENT_NODE) {
collectNamespacePrefixes((Element) node, prefixes);
}
}
} else {
// untested : copied from below
if (context.inheritNamespaces()) {
// get the top-most ancestor
final Deque<Element> stack = new ArrayDeque<>();
do {
if (node.getParentNode() == null || node.getParentNode() instanceof DocumentImpl) {
stack.add((Element) node);
}
node = node.getParentNode();
} while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
while (!stack.isEmpty()) {
collectNamespacePrefixes(stack.pop(), prefixes);
}
}
}
} else {
// In-memory node
// NodeImpl nodeImpl = (NodeImpl) node;
Node node = nodeValue.getNode();
if (context.preserveNamespaces()) {
// Horrible hacks to work-around bad in-scope NS : we reconstruct a NS context !
if (context.inheritNamespaces()) {
// Grab ancestors' NS
final Deque<Element> stack = new ArrayDeque<>();
do {
if (node.getNodeType() == Node.ELEMENT_NODE) {
stack.add((Element) node);
}
node = node.getParentNode();
} while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
while (!stack.isEmpty()) {
collectNamespacePrefixes(stack.pop(), prefixes);
}
} else {
// Grab self's NS
if (node.getNodeType() == Node.ELEMENT_NODE) {
collectNamespacePrefixes((Element) node, prefixes);
}
}
} else {
if (context.inheritNamespaces()) {
// get the top-most ancestor
final Deque<Element> stack = new ArrayDeque<>();
do {
if (node.getParentNode() == null || node.getParentNode() instanceof org.exist.dom.memtree.DocumentImpl) {
stack.add((Element) node);
}
node = node.getParentNode();
} while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
while (!stack.isEmpty()) {
collectNamespacePrefixes(stack.pop(), prefixes);
}
}
}
}
// clean up
String key = null;
String value = null;
for (final Entry<String, String> entry : prefixes.entrySet()) {
key = entry.getKey();
value = entry.getValue();
if ((key == null || key.isEmpty()) && (value == null || value.isEmpty())) {
prefixes.remove(key);
}
}
return prefixes;
}
Aggregations