Search in sources :

Example 66 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class SystemExportImportTest method exportImport.

@Test
public void exportImport() throws EXistException, IOException, PermissionDeniedException, SAXException, ParserConfigurationException, AuthenticationException, URISyntaxException, XMLDBException {
    Path file;
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        final Collection test = broker.getCollection(TEST_COLLECTION_URI);
        assertNotNull(test);
        final SystemExport sysexport = new SystemExport(broker, transaction, null, null, direct);
        final String backupDir = temporaryFolder.newFolder().getAbsolutePath();
        file = sysexport.export(backupDir, false, zip, null);
        transaction.commit();
    }
    clean();
    final SystemImport restore = new SystemImport(pool);
    final RestoreListener listener = new LogRestoreListener();
    restore.restore(TestUtils.ADMIN_DB_USER, TestUtils.ADMIN_DB_PWD, null, file, listener);
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        final Collection test = broker.getCollection(TEST_COLLECTION_URI);
        assertNotNull(test);
        DocumentImpl doc = getDoc(broker, test, doc01uri.lastSegment());
        assertEquals(XML1, serializer(broker, doc));
        doc = getDoc(broker, test, doc02uri.lastSegment());
        assertEquals(XML2_PROPER, serializer(broker, doc));
        doc = getDoc(broker, test, doc03uri.lastSegment());
        assertEquals(XML3_PROPER, serializer(broker, doc));
        doc = getDoc(broker, test, doc11uri.lastSegment());
        assertTrue(doc instanceof BinaryDocument);
        try (final InputStream is = broker.getBinaryResource(transaction, ((BinaryDocument) doc))) {
            assertEquals(BINARY, InputStreamUtil.readString(is, UTF_8));
        }
        transaction.commit();
    }
}
Also used : Path(java.nio.file.Path) LogRestoreListener(org.exist.backup.restore.listener.LogRestoreListener) InputStream(java.io.InputStream) Txn(org.exist.storage.txn.Txn) DocumentImpl(org.exist.dom.persistent.DocumentImpl) BinaryDocument(org.exist.dom.persistent.BinaryDocument) DBBroker(org.exist.storage.DBBroker) Collection(org.exist.collections.Collection) LogRestoreListener(org.exist.backup.restore.listener.LogRestoreListener) RestoreListener(org.exist.backup.restore.listener.RestoreListener) BrokerPool(org.exist.storage.BrokerPool)

Example 67 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class Replace method process.

@Override
public long process(Txn transaction) throws PermissionDeniedException, LockException, EXistException, XPathException, TriggerException {
    final NodeList children = content;
    if (children.getLength() == 0) {
        return 0;
    }
    if (children.getLength() > 1) {
        throw new EXistException("xupdate:replace requires exactly one content node");
    }
    LOG.debug("processing replace ...");
    int modifications = children.getLength();
    try {
        final StoredNode[] ql = selectAndLock(transaction);
        final NotificationService notifier = broker.getBrokerPool().getNotificationService();
        Node temp;
        TextImpl text;
        AttrImpl attribute;
        ElementImpl parent;
        for (final StoredNode node : ql) {
            if (node == null) {
                LOG.warn("select {} returned empty node set", selectStmt);
                continue;
            }
            final DocumentImpl doc = node.getOwnerDocument();
            if (!doc.getPermissions().validate(broker.getCurrentSubject(), Permission.WRITE)) {
                throw new PermissionDeniedException("User '" + broker.getCurrentSubject().getName() + "' does not have permission to write to the document '" + doc.getDocumentURI() + "'!");
            }
            parent = (ElementImpl) node.getParentStoredNode();
            if (parent == null) {
                throw new EXistException("The root element of a document can not be replaced with 'xu:replace'. " + "Please consider removing the document or use 'xu:update' to just replace the children of the root.");
            }
            switch(node.getNodeType()) {
                case Node.ELEMENT_NODE:
                    if (modifications == 0) {
                        modifications = 1;
                    }
                    temp = children.item(0);
                    parent.replaceChild(transaction, temp, node);
                    break;
                case Node.TEXT_NODE:
                    temp = children.item(0);
                    text = new TextImpl(temp.getNodeValue());
                    modifications = 1;
                    text.setOwnerDocument(doc);
                    parent.updateChild(transaction, node, text);
                    break;
                case Node.ATTRIBUTE_NODE:
                    final AttrImpl attr = (AttrImpl) node;
                    temp = children.item(0);
                    attribute = new AttrImpl(attr.getQName(), temp.getNodeValue(), broker.getBrokerPool().getSymbols());
                    attribute.setOwnerDocument(doc);
                    parent.updateChild(transaction, node, attribute);
                    break;
                default:
                    throw new EXistException("unsupported node-type");
            }
            doc.setLastModified(System.currentTimeMillis());
            modifiedDocuments.add(doc);
            broker.storeXMLResource(transaction, doc);
            notifier.notifyUpdate(doc, UpdateListener.UPDATE);
        }
        checkFragmentation(transaction, modifiedDocuments);
    } finally {
        unlockDocuments(transaction);
    }
    return modifications;
}
Also used : ElementImpl(org.exist.dom.persistent.ElementImpl) NodeList(org.w3c.dom.NodeList) StoredNode(org.exist.dom.persistent.StoredNode) Node(org.w3c.dom.Node) NotificationService(org.exist.storage.NotificationService) PermissionDeniedException(org.exist.security.PermissionDeniedException) EXistException(org.exist.EXistException) AttrImpl(org.exist.dom.persistent.AttrImpl) DocumentImpl(org.exist.dom.persistent.DocumentImpl) TextImpl(org.exist.dom.persistent.TextImpl) StoredNode(org.exist.dom.persistent.StoredNode)

Example 68 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class EXistURIResolver method databaseSource.

private Source databaseSource(final String path) throws TransformerException {
    final XmldbURI uri = XmldbURI.create(path);
    final DBBroker broker = db.getActiveBroker();
    final DocumentImpl doc;
    try {
        doc = broker.getResource(uri, Permission.READ);
        if (doc == null) {
            LOG.error("Document {} not found", path);
            throw new TransformerException("Resource " + path + " not found in database.");
        }
        final Source source;
        if (doc instanceof BinaryDocument) {
            /*
         * NOTE: this is extremely unpleasant as we let a reference to the blob file
         * escape from the closure into the StreamSource. This means that the file could have been deleted
         * by time the user comes to access the StreamSource, however this was also
         * the case with eXist-db's previous design, and due to the lack of resource
         * management of the StreamSource class, there is little we can do to improve
         * the situation - AR.
         */
            try (final Txn transaction = broker.getBrokerPool().getTransactionManager().beginTransaction()) {
                source = broker.withBinaryFile(transaction, (BinaryDocument) doc, p -> {
                    final StreamSource source1 = new StreamSource(p.toFile());
                    source1.setSystemId(p.toUri().toString());
                    return source1;
                });
                transaction.commit();
                return source;
            }
        } else {
            source = new EXistDbSource(broker, doc);
            source.setSystemId(uri.toASCIIString());
            return source;
        }
    } catch (final PermissionDeniedException | TransactionException | IOException e) {
        throw new TransformerException(e.getMessage(), e);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Txn(org.exist.storage.txn.Txn) Array(java.lang.reflect.Array) BrokerPool(org.exist.storage.BrokerPool) TransformerException(javax.xml.transform.TransformerException) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) StreamSource(javax.xml.transform.stream.StreamSource) URIResolver(javax.xml.transform.URIResolver) IOException(java.io.IOException) Source(javax.xml.transform.Source) PermissionDeniedException(org.exist.security.PermissionDeniedException) TransactionException(org.exist.storage.txn.TransactionException) Logger(org.apache.logging.log4j.Logger) DBBroker(org.exist.storage.DBBroker) XmldbURI(org.exist.xmldb.XmldbURI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) URI(java.net.URI) LogManager(org.apache.logging.log4j.LogManager) BinaryDocument(org.exist.dom.persistent.BinaryDocument) Permission(org.exist.security.Permission) StreamSource(javax.xml.transform.stream.StreamSource) Txn(org.exist.storage.txn.Txn) IOException(java.io.IOException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) BinaryDocument(org.exist.dom.persistent.BinaryDocument) DBBroker(org.exist.storage.DBBroker) TransactionException(org.exist.storage.txn.TransactionException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI) TransformerException(javax.xml.transform.TransformerException)

Example 69 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class Modification method checkFragmentation.

/**
 * Check if any of the modified documents needs defragmentation.
 *
 * Defragmentation will take place if the number of split pages in the
 * document exceeds the limit defined in the configuration file.
 *
 * @param transaction the database transaction.
 * @param docs the documents
 *
 * @throws EXistException if an error occurs
 */
protected void checkFragmentation(Txn transaction, DocumentSet docs) throws EXistException {
    int fragmentationLimit = -1;
    final Object property = broker.getBrokerPool().getConfiguration().getProperty(DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR);
    if (property != null) {
        fragmentationLimit = (Integer) property;
    }
    for (final Iterator<DocumentImpl> i = docs.getDocumentIterator(); i.hasNext(); ) {
        final DocumentImpl next = i.next();
        if (next.getSplitCount() > fragmentationLimit) {
            broker.defragXMLResource(transaction, next);
        }
        broker.checkXMLResourceConsistency(next);
    }
}
Also used : DocumentImpl(org.exist.dom.persistent.DocumentImpl)

Example 70 with DocumentImpl

use of org.exist.dom.persistent.DocumentImpl in project exist by eXist-db.

the class CollectionOrderTest method assertOrderOfDocuments.

private void assertOrderOfDocuments(final BrokerPool pool, final List<String> documentNames) throws EXistException, PermissionDeniedException, LockException {
    // iterate the collections ensuring they are in the same order as we created them
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        try (final Collection testCollection = broker.openCollection(TEST_COLLECTION, Lock.LockMode.READ_LOCK)) {
            final Iterator<DocumentImpl> documents = testCollection.iterator(broker);
            int idx = 0;
            while (documents.hasNext()) {
                final DocumentImpl document = documents.next();
                final String documentName = documentNames.get(idx++);
                assertEquals("Document names are not equal at index: " + idx, documentName, document.getFileURI().lastSegment().toString());
            }
        }
        transaction.commit();
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) Txn(org.exist.storage.txn.Txn) DocumentImpl(org.exist.dom.persistent.DocumentImpl)

Aggregations

DocumentImpl (org.exist.dom.persistent.DocumentImpl)128 PermissionDeniedException (org.exist.security.PermissionDeniedException)51 Collection (org.exist.collections.Collection)40 LockedDocument (org.exist.dom.persistent.LockedDocument)39 Txn (org.exist.storage.txn.Txn)35 XmldbURI (org.exist.xmldb.XmldbURI)34 EXistException (org.exist.EXistException)27 LockException (org.exist.util.LockException)26 DBBroker (org.exist.storage.DBBroker)25 IOException (java.io.IOException)19 NodeProxy (org.exist.dom.persistent.NodeProxy)18 URISyntaxException (java.net.URISyntaxException)17 BrokerPool (org.exist.storage.BrokerPool)17 TransactionManager (org.exist.storage.txn.TransactionManager)17 Test (org.junit.Test)17 XPathException (org.exist.xquery.XPathException)16 NodeId (org.exist.numbering.NodeId)14 SAXException (org.xml.sax.SAXException)13 StoredNode (org.exist.dom.persistent.StoredNode)12 BinaryDocument (org.exist.dom.persistent.BinaryDocument)11