Search in sources :

Example 1 with Permission

use of org.exist.security.Permission in project exist by eXist-db.

the class MutableCollection method storeDocument.

@Override
public void storeDocument(final Txn transaction, final DBBroker broker, final XmldbURI name, final InputSource source, @Nullable MimeType mimeType, @Nullable final Date createdDate, @Nullable final Date lastModifiedDate, @Nullable final Permission permission, @Nullable final DocumentType documentType, @Nullable final XMLReader xmlReader) throws EXistException, PermissionDeniedException, SAXException, LockException, IOException {
    if (mimeType == null) {
        mimeType = MimeType.BINARY_TYPE;
    }
    if (mimeType.isXMLType()) {
        // Store XML Document
        final BiConsumer2E<XMLReader, IndexInfo, SAXException, EXistException> validatorFn = (xmlReader1, validateIndexInfo) -> {
            validateIndexInfo.setReader(xmlReader1, null);
            try {
                xmlReader1.parse(source);
            } catch (final SAXException e) {
                throw new SAXException("The XML parser reported a problem: " + e.getMessage(), e);
            } catch (final IOException e) {
                throw new EXistException(e);
            }
        };
        final BiConsumer2E<XMLReader, IndexInfo, SAXException, EXistException> parserFn = (xmlReader1, storeIndexInfo) -> {
            try {
                storeIndexInfo.setReader(xmlReader1, null);
                xmlReader1.parse(source);
            } catch (final IOException e) {
                throw new EXistException(e);
            }
        };
        storeXmlDocument(transaction, broker, name, mimeType, createdDate, lastModifiedDate, permission, documentType, xmlReader, validatorFn, parserFn);
    } else {
        // Store Binary Document
        try (final InputStream is = source.getByteStream()) {
            if (is == null) {
                throw new IOException("storeDocument received a null InputStream when trying to store a Binary Document");
            }
            addBinaryResource(transaction, broker, name, is, mimeType.getName(), -1, createdDate, lastModifiedDate, permission);
        }
    }
}
Also used : CloseShieldReader(org.apache.commons.io.input.CloseShieldReader) java.util(java.util) LockMode(org.exist.storage.lock.Lock.LockMode) Txn(org.exist.storage.txn.Txn) Consumer2E(com.evolvedbinary.j8fu.function.Consumer2E) QName(org.exist.dom.QName) PermissionDeniedException(org.exist.security.PermissionDeniedException) org.exist.dom.persistent(org.exist.dom.persistent) Constants(org.exist.xquery.Constants) VariableByteOutputStream(org.exist.storage.io.VariableByteOutputStream) VALIDATION_SETTING(org.exist.util.XMLReaderObjectFactory.VALIDATION_SETTING) MimeType(org.exist.util.MimeType) Account(org.exist.security.Account) XMLReader(org.xml.sax.XMLReader) org.exist.storage(org.exist.storage) IndexController(org.exist.indexing.IndexController) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream) LockException(org.exist.util.LockException) Subject(org.exist.security.Subject) VariableByteInput(org.exist.storage.io.VariableByteInput) Node(org.w3c.dom.Node) XmldbURI(org.exist.xmldb.XmldbURI) LockType(org.exist.storage.lock.Lock.LockType) BiConsumer2E(com.evolvedbinary.j8fu.function.BiConsumer2E) EXistException(org.exist.EXistException) Indexer(org.exist.Indexer) Permission(org.exist.security.Permission) Nullable(javax.annotation.Nullable) PermissionFactory(org.exist.security.PermissionFactory) InputSource(org.xml.sax.InputSource) Database(org.exist.Database) XMLReaderObjectFactory(org.exist.util.XMLReaderObjectFactory) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) org.exist.storage.lock(org.exist.storage.lock) DOMStreamer(org.exist.util.serializer.DOMStreamer) Sync(org.exist.storage.sync.Sync) NotThreadSafe(net.jcip.annotations.NotThreadSafe) org.exist.collections.triggers(org.exist.collections.triggers) DocumentType(org.w3c.dom.DocumentType) StreamListener(org.exist.indexing.StreamListener) Logger(org.apache.logging.log4j.Logger) java.io(java.io) SAXException(org.xml.sax.SAXException) GuardedBy(net.jcip.annotations.GuardedBy) Configuration(org.exist.util.Configuration) LogManager(org.apache.logging.log4j.LogManager) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) EXistException(org.exist.EXistException) XMLReader(org.xml.sax.XMLReader) SAXException(org.xml.sax.SAXException)

Example 2 with Permission

use of org.exist.security.Permission in project exist by eXist-db.

the class MutableCollection method deserialize.

/**
 * Read collection contents from the stream
 *
 * Counterpart method to {@link #serialize(VariableByteOutputStream)}
 *
 * @param broker The database broker
 * @param path The path of the Collection
 * @param istream The input stream to deserialize the Collection from
 */
private static MutableCollection deserialize(final DBBroker broker, final XmldbURI path, final VariableByteInput istream) throws IOException, PermissionDeniedException, LockException {
    final int collectionId = istream.readInt();
    if (collectionId < 0) {
        throw new IOException("Internal error reading collection: invalid collection id");
    }
    final int collLen = istream.readInt();
    // TODO(AR) should we WRITE_LOCK the Collection to stop it being loaded from disk concurrently? see NativeBroker#openCollection line 1030 - already has READ_LOCK ;-)
    // try(final ManagedCollectionLock collectionLock = lockManager.acquireCollectionWriteLock(path, false)) {
    final LinkedHashSet<XmldbURI> subCollections = new LinkedHashSet<>(Math.max(16, collLen));
    for (int i = 0; i < collLen; i++) {
        subCollections.add(XmldbURI.create(istream.readUTF()));
    }
    final Permission permission = PermissionFactory.getDefaultCollectionPermission(broker.getBrokerPool().getSecurityManager());
    permission.read(istream);
    if (!permission.validate(broker.getCurrentSubject(), Permission.EXECUTE)) {
        throw new PermissionDeniedException("Permission denied to open the Collection " + path);
    }
    final long created = istream.readLong();
    final LinkedHashMap<String, DocumentImpl> documents = new LinkedHashMap<>();
    final MutableCollection collection = new MutableCollection(broker, collectionId, path, permission, created, subCollections, documents);
    broker.getCollectionResources(new InternalAccess() {

        @Override
        public void addDocument(final DocumentImpl doc) throws EXistException {
            doc.setCollection(collection);
            if (doc.getDocId() == DocumentImpl.UNKNOWN_DOCUMENT_ID) {
                LOG.error("Document must have ID. [{}]", doc);
                throw new EXistException("Document must have ID.");
            }
            documents.put(doc.getFileURI().lastSegmentString(), doc);
        }

        @Override
        public int getId() {
            return collectionId;
        }
    });
    return collection;
// }
}
Also used : EXistException(org.exist.EXistException) Permission(org.exist.security.Permission) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 3 with Permission

use of org.exist.security.Permission in project exist by eXist-db.

the class InteractiveClient method getResources.

/**
 * Get list of resources contained in collection.
 *
 * @throws XMLDBException Description of the Exception
 */
protected void getResources() throws XMLDBException {
    if (current == null) {
        return;
    }
    setProperties();
    final UserManagementService mgtService = (UserManagementService) current.getService("UserManagementService", "1.0");
    final String[] childCollections = current.listChildCollections();
    final String[] childResources = current.listResources();
    resources = new String[childCollections.length + childResources.length];
    // Collection child;
    Permission perm;
    // A list of ResourceDescriptor for the GUI
    final List<ResourceDescriptor> tableData = new ArrayList<>(resources.length);
    int i = 0;
    for (; i < childCollections.length; i++) {
        // child = current.getChildCollection(childCollections[i]);
        perm = mgtService.getSubCollectionPermissions(current, childCollections[i]);
        final Date created = mgtService.getSubCollectionCreationTime(current, childCollections[i]);
        if ("true".equals(properties.getProperty(PERMISSIONS))) {
            resources[i] = 'c' + perm.toString() + '\t' + getOwnerName(perm) + '\t' + getGroupName(perm) + '\t' + created.toString() + '\t' + childCollections[i];
        } else {
            resources[i] = childCollections[i];
        }
        if (options.startGUI) {
            try {
                tableData.add(new ResourceDescriptor.Collection(XmldbURI.xmldbUriFor(childCollections[i]), perm, created));
            } catch (final URISyntaxException e) {
                errorln("could not parse collection name into a valid URI: " + e.getMessage());
            }
        }
        completitions.add(childCollections[i]);
    }
    Resource res;
    for (int j = 0; j < childResources.length; i++, j++) {
        res = current.getResource(childResources[j]);
        perm = mgtService.getPermissions(res);
        if (perm == null) {
            // TODO this is not useful!
            System.out.println("null");
        }
        final Date lastModificationTime = ((EXistResource) res).getLastModificationTime();
        if ("true".equals(properties.getProperty(PERMISSIONS))) {
            resources[i] = '-' + perm.toString() + '\t' + getOwnerName(perm) + '\t' + getGroupName(perm) + '\t' + lastModificationTime.toString() + '\t' + childResources[j];
        } else {
            resources[i] = childResources[j];
        }
        if (options.startGUI) {
            try {
                tableData.add(new ResourceDescriptor.Document(XmldbURI.xmldbUriFor(childResources[j]), perm, lastModificationTime));
            } catch (final URISyntaxException e) {
                errorln("could not parse document name into a valid URI: " + e.getMessage());
            }
        }
        completitions.add(childResources[j]);
    }
    if (options.startGUI) {
        frame.setResources(tableData);
    }
}
Also used : ExtendedResource(org.exist.xmldb.ExtendedResource) BinaryResource(org.xmldb.api.modules.BinaryResource) EXistResource(org.exist.xmldb.EXistResource) UserManagementService(org.exist.xmldb.UserManagementService) URISyntaxException(java.net.URISyntaxException) EXistResource(org.exist.xmldb.EXistResource) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission)

Example 4 with Permission

use of org.exist.security.Permission in project exist by eXist-db.

the class EditPropertiesDialog method getUpdatedPermission.

// GEN-LAST:event_miInsertAceAfterActionPerformed
private Permission getUpdatedPermission(final Permission existingMode, final ModeDisplay modeChanges) throws PermissionDeniedException {
    final Permission newMode = existingMode.copy();
    modeChanges.writeToPermission(newMode);
    return newMode;
}
Also used : ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission)

Example 5 with Permission

use of org.exist.security.Permission in project exist by eXist-db.

the class SystemExport method exportDocument.

private void exportDocument(final BackupHandler bh, final BackupWriter output, final Date date, final BackupDescriptor prevBackup, final SAXSerializer serializer, final int docsCount, final int count, final DocumentImpl doc) throws IOException, SAXException, TerminatedException {
    if (callback != null) {
        callback.startDocument(doc.getFileURI().toString(), count, docsCount);
    }
    if ((monitor != null) && !monitor.proceed()) {
        throw (new TerminatedException("system export terminated by db"));
    }
    final boolean needsBackup = (prevBackup == null) || (date.getTime() < doc.getLastModified());
    if (needsBackup) {
        // Note: do not auto-close the output stream or the zip will be closed!
        try {
            final OutputStream os = output.newEntry(Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
            if (doc.getResourceType() == DocumentImpl.BINARY_FILE) {
                broker.readBinaryResource((BinaryDocument) doc, os);
            } else {
                final SAXSerializer contentSerializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
                final Writer writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
                try {
                    // write resource to contentSerializer
                    contentSerializer.setOutput(writer, defaultOutputProperties);
                    final Receiver receiver;
                    if (chainFactory != null) {
                        chainFactory.getLast().setNextInChain(contentSerializer);
                        receiver = chainFactory.getFirst();
                    } else {
                        receiver = contentSerializer;
                    }
                    writeXML(doc, receiver);
                } finally {
                    SerializerPool.getInstance().returnObject(contentSerializer);
                    writer.flush();
                }
            }
        } catch (final Exception e) {
            reportError("A write error occurred while exporting document: '" + doc.getFileURI() + "'. Continuing with next document.", e);
            return;
        } finally {
            output.closeEntry();
        }
    }
    final Permission perms = doc.getPermissions();
    // store permissions
    final AttributesImpl attr = new AttributesImpl();
    attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", (doc.getResourceType() == DocumentImpl.BINARY_FILE) ? "BinaryResource" : "XMLResource");
    attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", doc.getFileURI().toString());
    attr.addAttribute(Namespaces.EXIST_NS, "skip", "skip", "CDATA", (needsBackup ? "no" : "yes"));
    Backup.writeUnixStylePermissionAttributes(attr, perms);
    try {
        final String created = new DateTimeValue(new Date(doc.getCreated())).getStringValue();
        final String modified = new DateTimeValue(new Date(doc.getLastModified())).getStringValue();
        attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", created);
        attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", modified);
    } catch (final XPathException e) {
        LOG.warn(e.getMessage(), e);
    }
    attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
    String mimeType = "application/xml";
    if (doc.getMimeType() != null) {
        mimeType = Backup.encode(doc.getMimeType());
    }
    attr.addAttribute(Namespaces.EXIST_NS, "mimetype", "mimetype", "CDATA", mimeType);
    // output by serializer
    // if( ( doc.getResourceType() == DocumentImpl.XML_FILE ) && ( metadata != null ) && ( doc.getDoctype() != null ) ) {
    // 
    // if( doc.getDoctype().getName() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "namedoctype", "namedoctype", "CDATA", doc.getDoctype().getName() );
    // }
    // 
    // if( doc.getDoctype().getPublicId() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "publicid", "publicid", "CDATA", doc.getDoctype().getPublicId() );
    // }
    // 
    // if( doc.getDoctype().getSystemId() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "systemid", "systemid", "CDATA", doc.getDoctype().getSystemId() );
    // }
    // }
    bh.backup(doc, attr);
    serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr);
    if (perms instanceof ACLPermission) {
        Backup.writeACLPermission(serializer, (ACLPermission) perms);
    }
    bh.backup(doc, serializer);
    serializer.endElement(Namespaces.EXIST_NS, "resource", "resource");
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) ACLPermission(org.exist.security.ACLPermission) Receiver(org.exist.util.serializer.Receiver) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) TerminatedException(org.exist.xquery.TerminatedException) XMLStreamException(javax.xml.stream.XMLStreamException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) SAXSerializer(org.exist.util.serializer.SAXSerializer) TerminatedException(org.exist.xquery.TerminatedException)

Aggregations

Permission (org.exist.security.Permission)49 XmldbURI (org.exist.xmldb.XmldbURI)23 PermissionDeniedException (org.exist.security.PermissionDeniedException)19 ACLPermission (org.exist.security.ACLPermission)18 Collection (org.exist.collections.Collection)17 Test (org.junit.Test)14 IOException (java.io.IOException)11 Subject (org.exist.security.Subject)11 SAXException (org.xml.sax.SAXException)9 EXistException (org.exist.EXistException)7 DocumentImpl (org.exist.dom.persistent.DocumentImpl)7 ACEAider (org.exist.security.internal.aider.ACEAider)7 Txn (org.exist.storage.txn.Txn)6 XMLDBException (org.xmldb.api.base.XMLDBException)6 URISyntaxException (java.net.URISyntaxException)4 XMLStreamException (javax.xml.stream.XMLStreamException)4 Account (org.exist.security.Account)4 TerminatedException (org.exist.xquery.TerminatedException)4 XPathException (org.exist.xquery.XPathException)4 DateTimeValue (org.exist.xquery.value.DateTimeValue)4