Search in sources :

Example 1 with Collection

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

the class SystemImportHandler method mkcol.

private Collection mkcol(final XmldbURI collPath, final Date created) throws SAXException {
    try (final Txn transaction = beginTransaction()) {
        final Tuple2<Permission, Long> creationAttributes = Tuple(null, created.getTime());
        final Collection col = broker.getOrCreateCollection(transaction, collPath, Optional.of(creationAttributes));
        transaction.commit();
        return col;
    } catch (final Exception e) {
        throw new SAXException(e);
    }
}
Also used : Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) Txn(org.exist.storage.txn.Txn) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) TransactionException(org.exist.storage.txn.TransactionException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) SAXException(org.xml.sax.SAXException)

Example 2 with Collection

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

the class SystemImportHandler method restoreResourceEntry.

private DeferredPermission restoreResourceEntry(final Attributes atts) throws SAXException {
    @Nullable final String skip = atts.getValue("skip");
    // Don't process entries which should be skipped
    if (skip != null && !"no".equals(skip)) {
        return new SkippedEntryDeferredPermission();
    }
    @Nullable final String name = atts.getValue("name");
    if (name == null) {
        throw new SAXException("Resource requires a name attribute");
    }
    final boolean xmlType = Optional.ofNullable(atts.getValue("type")).filter(s -> s.equals("XMLResource")).isPresent();
    final String owner = getAttr(atts, "owner", SecurityManager.SYSTEM);
    final String group = getAttr(atts, "group", SecurityManager.DBA_GROUP);
    final String perms = getAttr(atts, "mode", "644");
    final String filename = getAttr(atts, "filename", name);
    @Nullable final String mimeTypeStr = atts.getValue("mimetype");
    @Nullable final String dateCreatedStr = atts.getValue("created");
    @Nullable final String dateModifiedStr = atts.getValue("modified");
    @Nullable final String publicId = atts.getValue("publicid");
    @Nullable final String systemId = atts.getValue("systemid");
    @Nullable final String nameDocType = atts.getValue("namedoctype");
    MimeType mimeType = null;
    if (mimeTypeStr != null) {
        mimeType = MimeTable.getInstance().getContentType(mimeTypeStr);
    }
    if (mimeType == null) {
        mimeType = xmlType ? MimeType.XML_TYPE : MimeType.BINARY_TYPE;
    }
    Date dateCreated = null;
    if (dateCreatedStr != null) {
        try {
            dateCreated = new DateTimeValue(dateCreatedStr).getDate();
        } catch (final XPathException xpe) {
            listener.warn("Illegal creation date. Ignoring date...");
        }
    }
    Date dateModified = null;
    if (dateModifiedStr != null) {
        try {
            dateModified = new DateTimeValue(dateModifiedStr).getDate();
        } catch (final XPathException xpe) {
            listener.warn("Illegal modification date. Ignoring date...");
        }
    }
    final DocumentType docType;
    if (publicId != null || systemId != null) {
        docType = new DocumentTypeImpl(nameDocType, publicId, systemId);
    } else {
        docType = null;
    }
    final XmldbURI docUri;
    if (version >= STRICT_URI_VERSION) {
        docUri = XmldbURI.create(name);
    } else {
        try {
            docUri = URIUtils.encodeXmldbUriFor(name);
        } catch (final URISyntaxException e) {
            final String msg = "Could not parse document name into a URI: " + e.getMessage();
            listener.error(msg);
            LOG.error(msg, e);
            return new SkippedEntryDeferredPermission();
        }
    }
    try (final EXistInputSource is = descriptor.getInputSource(filename)) {
        if (is == null) {
            final String msg = "Failed to restore resource '" + name + "'\nfrom file '" + descriptor.getSymbolicPath(name, false) + "'.\nReason: Unable to obtain its EXistInputSource";
            listener.warn(msg);
            throw new RuntimeException(msg);
        }
        try (final Txn transaction = beginTransaction()) {
            broker.storeDocument(transaction, docUri, is, mimeType, dateCreated, dateModified, null, docType, null, currentCollection);
            try (final LockedDocument doc = currentCollection.getDocumentWithLock(broker, docUri, Lock.LockMode.READ_LOCK)) {
                rh.startDocumentRestore(doc.getDocument(), atts);
            }
            transaction.commit();
            final DeferredPermission deferredPermission;
            if (name.startsWith(XmldbURI.SYSTEM_COLLECTION)) {
                // prevents restore of a backup from changing system collection resource ownership
                deferredPermission = new ResourceDeferredPermission(listener, currentCollection.getURI().append(name), SecurityManager.SYSTEM, SecurityManager.DBA_GROUP, Integer.parseInt(perms, 8));
            } else {
                deferredPermission = new ResourceDeferredPermission(listener, currentCollection.getURI().append(name), owner, group, Integer.parseInt(perms, 8));
            }
            try (final LockedDocument doc = currentCollection.getDocumentWithLock(broker, docUri, Lock.LockMode.READ_LOCK)) {
                rh.endDocumentRestore(doc.getDocument());
            }
            listener.restoredResource(name);
            return deferredPermission;
        } catch (final Exception e) {
            throw new IOException(e);
        }
    } catch (final Exception e) {
        listener.warn("Failed to restore resource '" + name + "'\nfrom file '" + descriptor.getSymbolicPath(name, false) + "'.\nReason: " + e.getMessage());
        LOG.error(e.getMessage(), e);
        return new SkippedEntryDeferredPermission();
    }
}
Also used : URIUtils(org.exist.xquery.util.URIUtils) Tuple2(com.evolvedbinary.j8fu.tuple.Tuple2) Txn(org.exist.storage.txn.Txn) java.util(java.util) ACE_TARGET(org.exist.security.ACLPermission.ACE_TARGET) URISyntaxException(java.net.URISyntaxException) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Tuple(com.evolvedbinary.j8fu.tuple.Tuple.Tuple) XMLReader(org.xml.sax.XMLReader) Namespaces(org.exist.Namespaces) Collection(org.exist.collections.Collection) XmldbURI(org.exist.xmldb.XmldbURI) Attributes(org.xml.sax.Attributes) DocumentImpl(org.exist.dom.persistent.DocumentImpl) DateTimeValue(org.exist.xquery.value.DateTimeValue) Lock(org.exist.storage.lock.Lock) Permission(org.exist.security.Permission) Nullable(javax.annotation.Nullable) RestoreListener(org.exist.backup.restore.listener.RestoreListener) LockedDocument(org.exist.dom.persistent.LockedDocument) UTF_8(java.nio.charset.StandardCharsets.UTF_8) IOException(java.io.IOException) TransactionException(org.exist.storage.txn.TransactionException) DocumentType(org.w3c.dom.DocumentType) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SecurityManager(org.exist.security.SecurityManager) SAXParseException(org.xml.sax.SAXParseException) Logger(org.apache.logging.log4j.Logger) BackupDescriptor(org.exist.backup.BackupDescriptor) ACE_ACCESS_TYPE(org.exist.security.ACLPermission.ACE_ACCESS_TYPE) DBBroker(org.exist.storage.DBBroker) SAXException(org.xml.sax.SAXException) org.exist.util(org.exist.util) DocumentTypeImpl(org.exist.dom.persistent.DocumentTypeImpl) LogManager(org.apache.logging.log4j.LogManager) XPathException(org.exist.xquery.XPathException) DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) DocumentTypeImpl(org.exist.dom.persistent.DocumentTypeImpl) DocumentType(org.w3c.dom.DocumentType) URISyntaxException(java.net.URISyntaxException) Txn(org.exist.storage.txn.Txn) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) TransactionException(org.exist.storage.txn.TransactionException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) SAXException(org.xml.sax.SAXException) LockedDocument(org.exist.dom.persistent.LockedDocument) Nullable(javax.annotation.Nullable) XmldbURI(org.exist.xmldb.XmldbURI)

Example 3 with Collection

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

the class ConsistencyCheck method checkCollectionTree.

/**
 * Run some tests on the collection hierarchy, starting at the root collection /db.
 *
 * @param callback callback object
 * @return a list of {@link ErrorReport} instances describing the errors found
 * @throws TerminatedException if a signal was received that operations should be aborted
 * @throws PermissionDeniedException if the current user lacks permissions
 */
public List<ErrorReport> checkCollectionTree(final ProgressCallback callback) throws TerminatedException, PermissionDeniedException {
    AccountImpl.getSecurityProperties().enableCheckPasswords(false);
    try {
        final List<ErrorReport> errors = new ArrayList<>();
        final Collection root = broker.getCollection(XmldbURI.ROOT_COLLECTION_URI);
        checkCollection(root, errors, callback);
        return errors;
    } finally {
        AccountImpl.getSecurityProperties().enableCheckPasswords(true);
    }
}
Also used : Collection(org.exist.collections.Collection)

Example 4 with Collection

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

the class CollectionDeferredPermission method apply.

@Override
public void apply(final DBBroker broker, final Txn transaction) {
    try (final Collection collection = broker.openCollection(getTarget(), Lock.LockMode.WRITE_LOCK)) {
        final Permission permission = collection.getPermissions();
        PermissionFactory.chown(broker, permission, Optional.ofNullable(getOwner()), Optional.ofNullable(getGroup()));
        PermissionFactory.chmod(broker, permission, Optional.of(getMode()), Optional.ofNullable(permission instanceof ACLPermission ? getAces() : null));
        broker.saveCollection(transaction, collection);
    } catch (final PermissionDeniedException | IOException e) {
        final String msg = "ERROR: Failed to set permissions on Collection '" + getTarget() + "'.";
        LOG.error(msg, e);
        getListener().warn(msg);
    }
}
Also used : ACLPermission(org.exist.security.ACLPermission) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException)

Example 5 with Collection

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

the class RestoreHandler method restoreCollectionEntry.

private DeferredPermission restoreCollectionEntry(final Attributes atts) throws SAXException {
    final String name = atts.getValue("name");
    if (name == null) {
        throw new SAXException("Collection requires a name attribute");
    }
    final String owner = getAttr(atts, "owner", SecurityManager.SYSTEM);
    final String group = getAttr(atts, "group", SecurityManager.DBA_GROUP);
    final String mode = getAttr(atts, "mode", "644");
    final String created = atts.getValue("created");
    final String strVersion = atts.getValue("version");
    if (strVersion != null) {
        try {
            this.version = Integer.parseInt(strVersion);
        } catch (final NumberFormatException nfe) {
            final String msg = "Could not parse version number for Collection '" + name + "', defaulting to version 0";
            listener.warn(msg);
            LOG.warn(msg);
            this.version = 0;
        }
    }
    try {
        listener.createdCollection(name);
        final XmldbURI collUri;
        if (version >= STRICT_URI_VERSION) {
            collUri = XmldbURI.create(name);
        } else {
            try {
                collUri = URIUtils.encodeXmldbUriFor(name);
            } catch (final URISyntaxException e) {
                listener.warn("Could not parse document name into a URI: " + e.getMessage());
                return new SkippedEntryDeferredPermission();
            }
        }
        if (version >= BLOB_STORE_VERSION) {
            this.deduplicateBlobs = Boolean.parseBoolean(atts.getValue("deduplicate-blobs"));
        } else {
            this.deduplicateBlobs = false;
        }
        final LockManager lockManager = broker.getBrokerPool().getLockManager();
        try (final Txn transaction = beginTransaction();
            final ManagedCollectionLock colLock = lockManager.acquireCollectionWriteLock(collUri)) {
            Collection collection = broker.getCollection(collUri);
            if (collection == null) {
                final Tuple2<Permission, Long> creationAttributes = Tuple(null, getDateFromXSDateTimeStringForItem(created, name).getTime());
                collection = broker.getOrCreateCollection(transaction, collUri, Optional.of(creationAttributes));
                broker.saveCollection(transaction, collection);
            }
            transaction.commit();
            this.currentCollectionUri = collection.getURI();
        }
        final DeferredPermission deferredPermission;
        if (name.startsWith(XmldbURI.SYSTEM_COLLECTION)) {
            // prevents restore of a backup from changing System collection ownership
            deferredPermission = new CollectionDeferredPermission(listener, currentCollectionUri, SecurityManager.SYSTEM, SecurityManager.DBA_GROUP, Integer.parseInt(mode, 8));
        } else {
            deferredPermission = new CollectionDeferredPermission(listener, currentCollectionUri, owner, group, Integer.parseInt(mode, 8));
        }
        return deferredPermission;
    } catch (final IOException | LockException | TransactionException | PermissionDeniedException e) {
        final String msg = "An unrecoverable error occurred while restoring collection '" + name + "': " + e.getMessage() + ". Aborting restore!";
        LOG.error(msg, e);
        listener.warn(msg);
        throw new SAXException(msg, e);
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) Txn(org.exist.storage.txn.Txn) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) LockManager(org.exist.storage.lock.LockManager) TransactionException(org.exist.storage.txn.TransactionException) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI) ManagedCollectionLock(org.exist.storage.lock.ManagedCollectionLock)

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