Search in sources :

Example 36 with LockedDocument

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

the class GMLIndexTest method indexDocument.

@Test
public void indexDocument() throws EXistException, CollectionConfigurationException, PermissionDeniedException, IOException, SAXException, LockException, URISyntaxException, SQLException {
    final BrokerPool pool = server.getBrokerPool();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction();
        final Collection testCollection = broker.openCollection(TEST_COLLECTION_URI, Lock.LockMode.READ_LOCK)) {
        // final CollectionConfigurationManager mgr = pool.getConfigurationManager();
        // mgr.addConfiguration(transaction, broker, testCollection, COLLECTION_CONFIG);
        // 
        // for (int i = 0; i < FILES.length; i++) {
        // final URL url = getClass().getResource("/" + FILES[i]);
        // final IndexInfo indexInfo;
        // try (final InputStream is = Files.newInputStream(Paths.get(url.toURI()))) {
        // final InputSource source = new InputSource();
        // source.setByteStream(is);
        // indexInfo = testCollection.validateXMLResource(transaction, broker, XmldbURI.create(FILES[i]), source);
        // }
        // try (final InputStream is = Files.newInputStream(Paths.get(url.toURI()))) {
        // final InputSource source = new InputSource();
        // source.setByteStream(is);
        // testCollection.store(transaction, broker, indexInfo, source);
        // }
        // }
        GMLHSQLIndexWorker indexWorker = (GMLHSQLIndexWorker) broker.getIndexController().getWorkerByIndexId(AbstractGMLJDBCIndex.ID);
        // Unplugged
        if (indexWorker != null) {
            Connection conn = null;
            try {
                conn = indexWorker.acquireConnection();
                for (int i = 0; i < FILES.length; i++) {
                    try (final LockedDocument lockedDoc = broker.getXMLResource(TEST_COLLECTION_URI.append(FILES[i]), Lock.LockMode.READ_LOCK)) {
                        final DocumentImpl doc = lockedDoc.getDocument();
                        PreparedStatement ps = conn.prepareStatement("SELECT * FROM " + GMLHSQLIndex.TABLE_NAME + " WHERE DOCUMENT_URI = ?;");
                        ps.setString(1, testCollection.getURI().append(doc.getURI()).getRawCollectionPath());
                        ResultSet rs = ps.executeQuery();
                        while (rs.next()) {
                        // Let be sure we have the right count
                        }
                        int count = rs.getRow();
                        ps.close();
                        assertEquals(0, count);
                    }
                }
            } finally {
                indexWorker.releaseConnection(conn);
            }
        }
        transaction.commit();
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) Connection(java.sql.Connection) LockedDocument(org.exist.dom.persistent.LockedDocument) ResultSet(java.sql.ResultSet) Collection(org.exist.collections.Collection) PreparedStatement(java.sql.PreparedStatement) Txn(org.exist.storage.txn.Txn) DocumentImpl(org.exist.dom.persistent.DocumentImpl) BrokerPool(org.exist.storage.BrokerPool)

Example 37 with LockedDocument

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

the class Deploy method installAndDeployFromDb.

private Optional<String> installAndDeployFromDb(final Txn transaction, final String path, final String repoURI) throws XPathException {
    final XmldbURI docPath = XmldbURI.createInternal(path);
    try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(docPath, LockMode.READ_LOCK)) {
        if (lockedDoc == null) {
            throw new XPathException(this, EXPathErrorCode.EXPDY001, path + " no such .xar", new StringValue(path));
        }
        final DocumentImpl doc = lockedDoc.getDocument();
        if (doc.getResourceType() != DocumentImpl.BINARY_FILE) {
            throw new XPathException(this, EXPathErrorCode.EXPDY001, path + " is not a valid .xar", new StringValue(path));
        }
        RepoPackageLoader loader = null;
        if (repoURI != null) {
            loader = new RepoPackageLoader(repoURI);
        }
        final XarSource xarSource = new BinaryDocumentXarSource(context.getBroker().getBrokerPool(), transaction, (BinaryDocument) doc);
        final Deployment deployment = new Deployment();
        return deployment.installAndDeploy(context.getBroker(), transaction, xarSource, loader);
    } catch (PackageException | IOException | PermissionDeniedException e) {
        LOG.error(e.getMessage(), e);
        throw new XPathException(this, EXPathErrorCode.EXPDY007, "Package installation failed: " + e.getMessage(), new StringValue(e.getMessage()));
    }
}
Also used : Deployment(org.exist.repo.Deployment) IOException(java.io.IOException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) XarSource(org.expath.pkg.repo.XarSource) LockedDocument(org.exist.dom.persistent.LockedDocument) PackageException(org.expath.pkg.repo.PackageException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 38 with LockedDocument

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

the class EmbeddedInputStream method openStream.

private static Either<IOException, InputStream> openStream(final BrokerPool pool, final XmldbURL url) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Begin document download");
    }
    try {
        final XmldbURI path = XmldbURI.create(url.getPath());
        try (final DBBroker broker = pool.getBroker()) {
            try (final LockedDocument lockedResource = broker.getXMLResource(path, Lock.LockMode.READ_LOCK)) {
                if (lockedResource == null) {
                    // Test for collection
                    try (final Collection collection = broker.openCollection(path, Lock.LockMode.READ_LOCK)) {
                        if (collection == null) {
                            // No collection, no document
                            return Left(new IOException("Resource " + url.getPath() + " not found."));
                        } else {
                            // Collection
                            return Left(new IOException("Resource " + url.getPath() + " is a collection."));
                        }
                    }
                } else {
                    final DocumentImpl resource = lockedResource.getDocument();
                    if (resource.getResourceType() == DocumentImpl.XML_FILE) {
                        final Serializer serializer = broker.borrowSerializer();
                        try {
                            // Preserve doctype
                            serializer.setProperty(EXistOutputKeys.OUTPUT_DOCTYPE, "yes");
                            // serialize the XML to a temporary file
                            final TemporaryFileManager tempFileManager = TemporaryFileManager.getInstance();
                            final Path tempFile = tempFileManager.getTemporaryFile();
                            try (final Writer writer = Files.newBufferedWriter(tempFile, UTF_8, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                                serializer.serialize(resource, writer);
                            }
                            // NOTE: the temp file will be returned to the manager when the InputStream is closed
                            return Right(new CloseNotifyingInputStream(Files.newInputStream(tempFile, StandardOpenOption.READ), () -> tempFileManager.returnTemporaryFile(tempFile)));
                        } finally {
                            broker.returnSerializer(serializer);
                        }
                    } else if (resource.getResourceType() == BinaryDocument.BINARY_FILE) {
                        return Right(broker.getBinaryResource((BinaryDocument) resource));
                    } else {
                        return Left(new IOException("Unknown resource type " + url.getPath() + ": " + resource.getResourceType()));
                    }
                }
            } finally {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("End document download");
                }
            }
        }
    } catch (final EXistException | PermissionDeniedException | SAXException e) {
        LOG.error(e);
        return Left(new IOException(e.getMessage(), e));
    } catch (final IOException e) {
        return Left(e);
    }
}
Also used : Path(java.nio.file.Path) CloseNotifyingInputStream(org.exist.util.io.CloseNotifyingInputStream) EXistException(org.exist.EXistException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) TemporaryFileManager(org.exist.util.io.TemporaryFileManager) SAXException(org.xml.sax.SAXException) DBBroker(org.exist.storage.DBBroker) LockedDocument(org.exist.dom.persistent.LockedDocument) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI) Serializer(org.exist.storage.serializers.Serializer)

Example 39 with LockedDocument

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

the class PermissionFactory method updatePermissions.

private static void updatePermissions(final DBBroker broker, final Txn transaction, final XmldbURI pathUri, final ConsumerE<Permission, PermissionDeniedException> permissionModifier) throws PermissionDeniedException {
    final BrokerPool brokerPool = broker.getBrokerPool();
    try {
        try (final Collection collection = broker.openCollection(pathUri, LockMode.WRITE_LOCK)) {
            if (collection == null) {
                try (final LockedDocument lockedDoc = broker.getXMLResource(pathUri, LockMode.WRITE_LOCK)) {
                    if (lockedDoc == null) {
                        throw new XPathException("Resource or collection '" + pathUri.toString() + "' does not exist.");
                    }
                    final DocumentImpl doc = lockedDoc.getDocument();
                    // // keep a write lock in the transaction
                    // transaction.acquireDocumentLock(() -> brokerPool.getLockManager().acquireDocumentWriteLock(doc.getURI()));
                    final Permission permissions = doc.getPermissions();
                    permissionModifier.accept(permissions);
                    broker.storeXMLResource(transaction, doc);
                }
            } else {
                // // keep a write lock in the transaction
                // transaction.acquireCollectionLock(() -> brokerPool.getLockManager().acquireCollectionWriteLock(collection.getURI()));
                final Permission permissions = collection.getPermissionsNoLock();
                permissionModifier.accept(permissions);
                broker.saveCollection(transaction, collection);
            }
            broker.flush();
        }
    } catch (final XPathException | PermissionDeniedException | IOException e) {
        throw new PermissionDeniedException("Permission to modify permissions is denied for user '" + broker.getCurrentSubject().getName() + "' on '" + pathUri.toString() + "': " + e.getMessage(), e);
    }
}
Also used : XPathException(org.exist.xquery.XPathException) LockedDocument(org.exist.dom.persistent.LockedDocument) Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) IOException(java.io.IOException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) BrokerPool(org.exist.storage.BrokerPool)

Example 40 with LockedDocument

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

the class RepoBackup method restore.

public static void restore(final Txn transaction, final DBBroker broker) throws IOException, PermissionDeniedException {
    final XmldbURI docPath = XmldbURI.createInternal(XmldbURI.ROOT_COLLECTION + "/" + REPO_ARCHIVE);
    try (final LockedDocument lockedDoc = broker.getXMLResource(docPath, LockMode.READ_LOCK)) {
        if (lockedDoc == null) {
            return;
        }
        final DocumentImpl doc = lockedDoc.getDocument();
        if (doc.getResourceType() != DocumentImpl.BINARY_FILE) {
            throw new IOException(docPath + " is not a binary resource");
        }
        try (final InputStream is = broker.getBrokerPool().getBlobStore().get(transaction, ((BinaryDocument) doc).getBlobId())) {
            final Path directory = ExistRepository.getRepositoryDir(broker.getConfiguration());
            unzip(doc.getURI(), is, directory);
        }
    }
}
Also used : Path(java.nio.file.Path) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) LockedDocument(org.exist.dom.persistent.LockedDocument) IOException(java.io.IOException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) XmldbURI(org.exist.xmldb.XmldbURI)

Aggregations

LockedDocument (org.exist.dom.persistent.LockedDocument)91 DocumentImpl (org.exist.dom.persistent.DocumentImpl)40 XmldbURI (org.exist.xmldb.XmldbURI)39 DBBroker (org.exist.storage.DBBroker)36 PermissionDeniedException (org.exist.security.PermissionDeniedException)30 Collection (org.exist.collections.Collection)28 Txn (org.exist.storage.txn.Txn)27 BrokerPool (org.exist.storage.BrokerPool)21 EXistException (org.exist.EXistException)20 Test (org.junit.Test)20 IOException (java.io.IOException)18 BinaryDocument (org.exist.dom.persistent.BinaryDocument)18 Serializer (org.exist.storage.serializers.Serializer)15 XPathException (org.exist.xquery.XPathException)14 URISyntaxException (java.net.URISyntaxException)13 InputStream (java.io.InputStream)11 LockException (org.exist.util.LockException)11 Tuple2 (com.evolvedbinary.j8fu.tuple.Tuple2)9 Lock (org.exist.storage.lock.Lock)9 TransactionManager (org.exist.storage.txn.TransactionManager)9