Search in sources :

Example 86 with XmldbURI

use of org.exist.xmldb.XmldbURI in project exist by eXist-db.

the class XmldbBinariesTest method storeBinaryFile.

@Override
protected void storeBinaryFile(final XmldbURI filePath, byte[] content) throws Exception {
    Collection colRoot = null;
    try {
        colRoot = DatabaseManager.getCollection(getBaseUri() + "/db", ADMIN_DB_USER, ADMIN_DB_PWD);
        final XmldbURI[] collectionNames = filePath.removeLastSegment().getPathSegments();
        final Deque<Collection> cols = new ArrayDeque<>();
        try {
            Collection current = colRoot;
            for (int i = 1; i < collectionNames.length; i++) {
                final Collection child = getOrCreateCollection(current, collectionNames[i].toString());
                cols.push(child);
                current = child;
            }
            final String fileName = filePath.lastSegment().toString();
            final Resource resource = current.createResource(fileName, BinaryResource.RESOURCE_TYPE);
            resource.setContent(content);
            current.storeResource(resource);
        } finally {
            while (!cols.isEmpty()) {
                try {
                    cols.pop().close();
                } catch (XMLDBException e) {
                }
            }
        }
    } finally {
        if (colRoot != null) {
            colRoot.close();
        }
    }
}
Also used : BinaryResource(org.xmldb.api.modules.BinaryResource) XmldbURI(org.exist.xmldb.XmldbURI) ArrayDeque(java.util.ArrayDeque)

Example 87 with XmldbURI

use of org.exist.xmldb.XmldbURI 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 88 with XmldbURI

use of org.exist.xmldb.XmldbURI in project exist by eXist-db.

the class AbstractCompressFunction method compressCollection.

/**
 * Adds a Collection and its child collections and resources recursively to
 * a archive
 *
 * @param os
 *            The Output Stream to add the document to
 * @param col
 *            The Collection to add to the archive
 * @param useHierarchy
 *            Whether to use a folder hierarchy in the archive file that
 *            reflects the collection hierarchy
 */
private void compressCollection(OutputStream os, Collection col, boolean useHierarchy, String stripOffset) throws IOException, SAXException, LockException, PermissionDeniedException {
    // iterate over child documents
    final DBBroker broker = context.getBroker();
    final LockManager lockManager = broker.getBrokerPool().getLockManager();
    final MutableDocumentSet childDocs = new DefaultDocumentSet();
    col.getDocuments(broker, childDocs);
    for (final Iterator<DocumentImpl> itChildDocs = childDocs.getDocumentIterator(); itChildDocs.hasNext(); ) {
        DocumentImpl childDoc = itChildDocs.next();
        try (final ManagedDocumentLock updateLock = lockManager.acquireDocumentReadLock(childDoc.getURI())) {
            compressResource(os, childDoc, useHierarchy, stripOffset, "", null);
        }
    }
    // iterate over child collections
    for (final Iterator<XmldbURI> itChildCols = col.collectionIterator(broker); itChildCols.hasNext(); ) {
        // get the child collection
        XmldbURI childColURI = itChildCols.next();
        Collection childCol = broker.getCollection(col.getURI().append(childColURI));
        // recurse
        compressCollection(os, childCol, useHierarchy, stripOffset);
    }
}
Also used : LockManager(org.exist.storage.lock.LockManager) DBBroker(org.exist.storage.DBBroker) ManagedDocumentLock(org.exist.storage.lock.ManagedDocumentLock) Collection(org.exist.collections.Collection) XmldbURI(org.exist.xmldb.XmldbURI)

Example 89 with XmldbURI

use of org.exist.xmldb.XmldbURI 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 90 with XmldbURI

use of org.exist.xmldb.XmldbURI 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)

Aggregations

XmldbURI (org.exist.xmldb.XmldbURI)260 Collection (org.exist.collections.Collection)100 PermissionDeniedException (org.exist.security.PermissionDeniedException)69 Test (org.junit.Test)56 Txn (org.exist.storage.txn.Txn)55 EXistException (org.exist.EXistException)42 URISyntaxException (java.net.URISyntaxException)39 LockedDocument (org.exist.dom.persistent.LockedDocument)39 IOException (java.io.IOException)38 DBBroker (org.exist.storage.DBBroker)38 DocumentImpl (org.exist.dom.persistent.DocumentImpl)34 SAXException (org.xml.sax.SAXException)33 Permission (org.exist.security.Permission)30 LockException (org.exist.util.LockException)27 Path (java.nio.file.Path)22 XPathException (org.exist.xquery.XPathException)22 BrokerPool (org.exist.storage.BrokerPool)21 TransactionManager (org.exist.storage.txn.TransactionManager)20 Subject (org.exist.security.Subject)19 StringInputSource (org.exist.util.StringInputSource)17