Search in sources :

Example 91 with Collection

use of org.exist.collections.Collection 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 92 with Collection

use of org.exist.collections.Collection in project exist by eXist-db.

the class Deployment method storeRepoXML.

/**
 * Store repo.xml into the db. Adds the time of deployment to the descriptor.
 *
 * @param repoXML
 * @param targetCollection
 * @throws XPathException
 */
private void storeRepoXML(final DBBroker broker, final Txn transaction, final DocumentImpl repoXML, final XmldbURI targetCollection, final Optional<RequestedPerms> requestedPerms) throws PackageException, XPathException {
    // Store repo.xml
    final DateTimeValue time = new DateTimeValue(new Date());
    final MemTreeBuilder builder = new MemTreeBuilder();
    builder.startDocument();
    final UpdatingDocumentReceiver receiver = new UpdatingDocumentReceiver(builder, time.getStringValue());
    try {
        repoXML.copyTo(broker, receiver);
    } catch (final SAXException e) {
        throw new PackageException("Error while updating repo.xml in-memory: " + e.getMessage(), e);
    }
    builder.endDocument();
    final DocumentImpl updatedXML = builder.getDocument();
    try {
        final Collection collection = broker.getOrCreateCollection(transaction, targetCollection);
        final XmldbURI name = XmldbURI.createInternal("repo.xml");
        final Permission permission = PermissionFactory.getDefaultResourcePermission(broker.getBrokerPool().getSecurityManager());
        setPermissions(broker, requestedPerms, false, MimeType.XML_TYPE, permission);
        collection.storeDocument(transaction, broker, name, updatedXML, MimeType.XML_TYPE, null, null, permission, null, null);
    } catch (final PermissionDeniedException | IOException | SAXException | LockException | EXistException e) {
        throw new PackageException("Error while storing updated repo.xml: " + e.getMessage(), e);
    }
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) IOException(java.io.IOException) EXistException(org.exist.EXistException) SAXException(org.xml.sax.SAXException) UnixStylePermission(org.exist.security.UnixStylePermission) Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 93 with Collection

use of org.exist.collections.Collection 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 94 with Collection

use of org.exist.collections.Collection in project exist by eXist-db.

the class ExtCollection method eval.

@Override
public Sequence eval(final Sequence contextSequence, final Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().start(this);
        context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
        if (contextSequence != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
        }
        if (contextItem != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
        }
    }
    final List<String> args = getParameterValues(contextSequence, contextItem);
    final Sequence result;
    try {
        if (args.isEmpty()) {
            final Sequence docs = toSequence(context.getStaticallyKnownDocuments());
            final Sequence dynamicCollection = context.getDynamicallyAvailableCollection("");
            if (dynamicCollection != null) {
                result = new ValueSequence();
                result.addAll(docs);
                result.addAll(dynamicCollection);
            } else {
                result = docs;
            }
        } else {
            final Sequence dynamicCollection = context.getDynamicallyAvailableCollection(asUri(args.get(0)).toString());
            if (dynamicCollection != null) {
                result = dynamicCollection;
            } else {
                final MutableDocumentSet ndocs = new DefaultDocumentSet();
                for (final String next : args) {
                    final XmldbURI uri = new AnyURIValue(next).toXmldbURI();
                    try (final Collection coll = context.getBroker().openCollection(uri, Lock.LockMode.READ_LOCK)) {
                        if (coll == null) {
                            if (context.isRaiseErrorOnFailedRetrieval()) {
                                throw new XPathException(this, ErrorCodes.FODC0002, "Can not access collection '" + uri + "'");
                            }
                        } else {
                            if (context.inProtectedMode()) {
                                context.getProtectedDocs().getDocsByCollection(coll, ndocs);
                            } else {
                                coll.allDocs(context.getBroker(), ndocs, includeSubCollections, context.getProtectedDocs());
                            }
                        }
                    }
                }
                result = toSequence(ndocs);
            }
        }
    } catch (final XPathException e) {
        // From AnyURIValue constructor
        e.setLocation(line, column);
        Sequence flattenedArgs = Sequence.EMPTY_SEQUENCE;
        try {
            flattenedArgs = argsToSeq(contextSequence, contextItem);
        } catch (final XPathException xe) {
            LOG.warn(e.getMessage(), xe);
        }
        throw new XPathException(this, ErrorCodes.FODC0002, e.getMessage(), flattenedArgs, e);
    } catch (final PermissionDeniedException e) {
        Sequence flattenedArgs = Sequence.EMPTY_SEQUENCE;
        try {
            flattenedArgs = argsToSeq(contextSequence, contextItem);
        } catch (final XPathException xe) {
            LOG.warn(e.getMessage(), xe);
        }
        throw new XPathException(this, ErrorCodes.FODC0002, "Can not access collection '" + e.getMessage() + "'", flattenedArgs, e);
    } catch (final LockException e) {
        Sequence flattenedArgs = Sequence.EMPTY_SEQUENCE;
        try {
            flattenedArgs = argsToSeq(contextSequence, contextItem);
        } catch (final XPathException xe) {
            LOG.warn(e.getMessage(), xe);
        }
        throw new XPathException(this, ErrorCodes.FODC0002, e.getMessage(), flattenedArgs, e);
    }
    // iterate through all docs and create the node set
    registerUpdateListener();
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", result);
    }
    return result;
}
Also used : LockException(org.exist.util.LockException) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 95 with Collection

use of org.exist.collections.Collection in project exist by eXist-db.

the class DOMIndexerTest method store.

@Test
public void store() throws PermissionDeniedException, IOException, EXistException, SAXException, LockException, AuthenticationException {
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final TransactionManager txnMgr = pool.getTransactionManager();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().authenticate("admin", "")));
        final Txn txn = txnMgr.beginTransaction()) {
        try (final Collection collection = broker.getOrCreateCollection(txn, TestConstants.TEST_COLLECTION_URI)) {
            broker.storeDocument(txn, TestConstants.TEST_XML_URI, new StringInputSource(XML), MimeType.XML_TYPE, collection);
            broker.flush();
            broker.saveCollection(txn, collection);
        }
        txnMgr.commit(txn);
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) StringInputSource(org.exist.util.StringInputSource) TransactionManager(org.exist.storage.txn.TransactionManager) Collection(org.exist.collections.Collection) Txn(org.exist.storage.txn.Txn) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Aggregations

Collection (org.exist.collections.Collection)297 Txn (org.exist.storage.txn.Txn)160 XmldbURI (org.exist.xmldb.XmldbURI)99 DBBroker (org.exist.storage.DBBroker)89 TransactionManager (org.exist.storage.txn.TransactionManager)86 BrokerPool (org.exist.storage.BrokerPool)69 StringInputSource (org.exist.util.StringInputSource)57 Test (org.junit.Test)57 EXistException (org.exist.EXistException)43 PermissionDeniedException (org.exist.security.PermissionDeniedException)43 DocumentImpl (org.exist.dom.persistent.DocumentImpl)42 IOException (java.io.IOException)33 LockedDocument (org.exist.dom.persistent.LockedDocument)31 SAXException (org.xml.sax.SAXException)26 InputStream (java.io.InputStream)19 Path (java.nio.file.Path)19 Permission (org.exist.security.Permission)19 LockException (org.exist.util.LockException)16 TriggerException (org.exist.collections.triggers.TriggerException)15 BinaryDocument (org.exist.dom.persistent.BinaryDocument)15