Search in sources :

Example 51 with LockedDocument

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

the class ExistDocument method refreshLock.

public LockToken refreshLock(String token) throws PermissionDeniedException, DocumentAlreadyLockedException, EXistException, DocumentNotLockedException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("refresh lock {}  lock={}", xmldbUri, token);
    }
    if (token == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("token is null");
        }
        throw new EXistException("token is null");
    }
    // Try to get document
    try (final DBBroker broker = brokerPool.get(Optional.ofNullable(subject));
        final LockedDocument lockedDocument = broker.getXMLResource(xmldbUri, LockMode.WRITE_LOCK)) {
        final DocumentImpl document = lockedDocument.getDocument();
        if (document == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No resource found for path: {}", xmldbUri);
            }
            // return null; // throw exception?
            throw new EXistException("No resource found.");
        }
        // Get current userlock
        Account userLock = document.getUserLock();
        // Check if Resource is already locked.
        if (userLock == null) {
            final String msg = "Resource was not locked.";
            if (LOG.isDebugEnabled()) {
                LOG.debug(msg);
            }
            throw new DocumentNotLockedException(msg);
        }
        if (userLock.getName() != null && !userLock.getName().equals(subject.getName()) && !subject.hasDbaRole()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Resource is locked by {}", userLock.getName());
            }
            throw new PermissionDeniedException(userLock.getName());
        }
        LockToken lockToken = document.getLockToken();
        if (!token.equals(lockToken.getOpaqueLockToken())) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Token does not match");
            }
            throw new PermissionDeniedException(String.format("Token %s does not match %s", token, lockToken.getOpaqueLockToken()));
        }
        lockToken.setTimeOut(LockToken.LOCK_TIMEOUT_INFINITE);
        // Make token persistant
        final TransactionManager txnManager = brokerPool.getTransactionManager();
        try (final Txn txn = txnManager.beginTransaction()) {
            broker.storeXMLResource(txn, document);
            txnManager.commit(txn);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Successfully retrieved token");
        }
        return lockToken;
    } catch (EXistException | PermissionDeniedException e) {
        LOG.error(e);
        throw e;
    } finally {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Finished create lock");
        }
    }
}
Also used : Account(org.exist.security.Account) DBBroker(org.exist.storage.DBBroker) TransactionManager(org.exist.storage.txn.TransactionManager) LockedDocument(org.exist.dom.persistent.LockedDocument) LockToken(org.exist.dom.persistent.LockToken) PermissionDeniedException(org.exist.security.PermissionDeniedException) EXistException(org.exist.EXistException) Txn(org.exist.storage.txn.Txn) DocumentNotLockedException(org.exist.webdav.exceptions.DocumentNotLockedException) DocumentImpl(org.exist.dom.persistent.DocumentImpl)

Example 52 with LockedDocument

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

the class Source method exec.

@Override
public void exec() {
    if (fileURI == null) {
        return;
    }
    InputStream is = null;
    try {
        if (fileURI.toLowerCase().startsWith("dbgp://")) {
            String uri = fileURI.substring(7);
            if (uri.toLowerCase().startsWith("file:/")) {
                uri = fileURI.substring(5);
                is = Files.newInputStream(Paths.get(uri));
            } else {
                XmldbURI pathUri = XmldbURI.create(URLDecoder.decode(fileURI.substring(15), "UTF-8"));
                Database db = getJoint().getContext().getDatabase();
                try (final DBBroker broker = db.getBroker();
                    final LockedDocument resource = broker.getXMLResource(pathUri, LockMode.READ_LOCK)) {
                    if (resource.getDocument().getResourceType() == DocumentImpl.BINARY_FILE) {
                        is = broker.getBinaryResource((BinaryDocument) resource.getDocument());
                    } else {
                        // TODO: xml source???
                        return;
                    }
                } catch (EXistException e) {
                    exception = e;
                }
            }
        } else {
            URL url = new URL(fileURI);
            URLConnection conn = url.openConnection();
            is = conn.getInputStream();
        }
        UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
        byte[] buf = new byte[256];
        int c;
        while ((c = is.read(buf)) > -1) {
            // TODO: begin & end line should affect
            baos.write(buf, 0, c);
        }
        source = baos.toByteArray();
        success = true;
    } catch (PermissionDeniedException | IOException e) {
        exception = e;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                if (exception == null) {
                    exception = e;
                }
            }
        }
    }
}
Also used : InputStream(java.io.InputStream) EXistException(org.exist.EXistException) IOException(java.io.IOException) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) URL(java.net.URL) URLConnection(java.net.URLConnection) BinaryDocument(org.exist.dom.persistent.BinaryDocument) DBBroker(org.exist.storage.DBBroker) Database(org.exist.Database) LockedDocument(org.exist.dom.persistent.LockedDocument) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 53 with LockedDocument

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

the class RestoreHandler method restoreDeletedEntry.

private void restoreDeletedEntry(final Attributes atts) {
    final String name = atts.getValue("name");
    final String type = atts.getValue("type");
    if ("collection".equals(type)) {
        try {
            try (final Txn transaction = beginTransaction();
                final Collection collection = broker.openCollection(currentCollectionUri.append(name), Lock.LockMode.WRITE_LOCK)) {
                if (collection != null) {
                    final boolean triggersEnabled = broker.isTriggersEnabled();
                    try {
                        broker.setTriggersEnabled(false);
                        broker.removeCollection(transaction, collection);
                    } finally {
                        // restore triggers enabled setting
                        broker.setTriggersEnabled(triggersEnabled);
                    }
                }
                transaction.commit();
            }
        } catch (final PermissionDeniedException | IOException | TriggerException | TransactionException e) {
            listener.warn("Failed to remove deleted collection: " + name + ": " + e.getMessage());
        }
    } else if ("resource".equals(type)) {
        final XmldbURI docName = XmldbURI.create(name);
        try (final Txn transaction = beginTransaction();
            final Collection collection = broker.openCollection(currentCollectionUri.append(name), Lock.LockMode.WRITE_LOCK);
            final LockedDocument lockedDocument = collection.getDocumentWithLock(broker, docName, Lock.LockMode.WRITE_LOCK)) {
            // Check that the document exists
            if (lockedDocument != null) {
                final boolean triggersEnabled = broker.isTriggersEnabled();
                try {
                    broker.setTriggersEnabled(false);
                    final boolean xmlType = !(lockedDocument.getDocument() instanceof BinaryDocument);
                    if (xmlType) {
                        collection.removeXMLResource(transaction, broker, docName);
                    } else {
                        collection.removeBinaryResource(transaction, broker, docName);
                    }
                } finally {
                    // restore triggers enabled setting
                    broker.setTriggersEnabled(triggersEnabled);
                }
            }
            transaction.commit();
            // NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
            collection.close();
        } catch (final PermissionDeniedException | TransactionException | TriggerException | LockException | IOException e) {
            listener.warn("Failed to remove deleted resource: " + name + ": " + e.getMessage());
        }
    }
}
Also used : BinaryDocument(org.exist.dom.persistent.BinaryDocument) TransactionException(org.exist.storage.txn.TransactionException) LockedDocument(org.exist.dom.persistent.LockedDocument) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) Txn(org.exist.storage.txn.Txn) IOException(java.io.IOException) TriggerException(org.exist.collections.triggers.TriggerException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 54 with LockedDocument

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

the class ConstructedNodesRecoveryTest method testDocumentIsValid.

private void testDocumentIsValid(final DBBroker broker, final TransactionManager transact, final String documentName) throws PermissionDeniedException, IOException, SAXException, LockException, TransactionException {
    // create a transaction
    try (final Txn transaction = transact.beginTransaction()) {
        // get the test collection
        final Collection root = broker.getOrCreateCollection(transaction, TestConstants.TEST_COLLECTION_URI);
        assertNotNull(root);
        broker.saveCollection(transaction, root);
        // get the test document
        try (final LockedDocument lockedDoc = root.getDocumentWithLock(broker, XmldbURI.create(documentName), LockMode.READ_LOCK)) {
            final DocumentImpl doc = lockedDoc.getDocument();
            assertNotNull(doc);
            assertEquals(testDocument, serialize(broker, doc));
        }
        transact.commit(transaction);
    }
}
Also used : LockedDocument(org.exist.dom.persistent.LockedDocument) Collection(org.exist.collections.Collection) Txn(org.exist.storage.txn.Txn) DocumentImpl(org.exist.dom.persistent.DocumentImpl)

Example 55 with LockedDocument

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

the class InstallFunction method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence removed = BooleanValue.FALSE;
    boolean force = true;
    UserInteractionStrategy interact = new BatchUserInteraction();
    String pkgOrPath = args[0].getStringValue();
    Optional<ExistRepository> repo = getContext().getRepository();
    try {
        if (repo.isPresent()) {
            Repository parent_repo = repo.get().getParentRepo();
            Package pkg;
            if (isCalledAs("install")) {
                // download .xar from a URI
                URI uri = _getURI(pkgOrPath);
                pkg = parent_repo.installPackage(uri, force, interact);
                repo.get().reportAction(ExistRepository.Action.INSTALL, pkg.getName());
            } else {
                // .xar is stored as a binary resource
                try (final LockedDocument lockedDoc = getBinaryDoc(pkgOrPath);
                    final Txn transaction = context.getBroker().continueOrBeginTransaction()) {
                    final DocumentImpl doc = lockedDoc.getDocument();
                    LOG.debug("Installing file: {}", doc.getURI());
                    pkg = parent_repo.installPackage(new BinaryDocumentXarSource(context.getBroker().getBrokerPool(), transaction, (BinaryDocument) doc), force, interact);
                    repo.get().reportAction(ExistRepository.Action.INSTALL, pkg.getName());
                    transaction.commit();
                }
            }
            ExistPkgInfo info = (ExistPkgInfo) pkg.getInfo("exist");
            if (info != null && !info.getJars().isEmpty())
                ClasspathHelper.updateClasspath(context.getBroker().getBrokerPool(), pkg);
            // TODO: expath libs do not provide a way to see if there were any XQuery modules installed at all
            context.getBroker().getBrokerPool().getXQueryPool().clear();
            removed = BooleanValue.TRUE;
        } else {
            throw new XPathException("expath repository not available");
        }
    } catch (PackageException | TransactionException ex) {
        logger.error(ex.getMessage(), ex);
        return removed;
    // /TODO: _repo.removePackage seems to throw PackageException
    // throw new XPathException("Problem installing package " + pkg + " in expath repository, check that eXist-db has access permissions to expath repository file directory  ", ex);
    } catch (XPathException xpe) {
        logger.error(xpe.getMessage());
        return removed;
    }
    return removed;
}
Also used : XPathException(org.exist.xquery.XPathException) Sequence(org.exist.xquery.value.Sequence) Txn(org.exist.storage.txn.Txn) XmldbURI(org.exist.xmldb.XmldbURI) URI(java.net.URI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) ExistPkgInfo(org.exist.repo.ExistPkgInfo) ExistRepository(org.exist.repo.ExistRepository) TransactionException(org.exist.storage.txn.TransactionException) LockedDocument(org.exist.dom.persistent.LockedDocument) Package(org.expath.pkg.repo.Package) BatchUserInteraction(org.expath.pkg.repo.tui.BatchUserInteraction) ExistRepository(org.exist.repo.ExistRepository)

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