Search in sources :

Example 1 with EXistException

use of org.exist.EXistException 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 EXistException

use of org.exist.EXistException 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 EXistException

use of org.exist.EXistException in project exist by eXist-db.

the class CollectionConfigurationManager method checkCreateCollection.

/**
 * Check if the collection exists below the system collection. If not,
 * create it.
 *
 * @param broker eXist-db broker
 * @param txn according transaction
 * @param uri to the collection to create
 * @throws EXistException if something goes wrong
 */
private void checkCreateCollection(final DBBroker broker, final Txn txn, final XmldbURI uri) throws EXistException {
    try {
        Collection collection = broker.getCollection(uri);
        if (collection == null) {
            collection = broker.getOrCreateCollection(txn, uri);
            SanityCheck.THROW_ASSERT(collection != null);
            broker.saveCollection(txn, collection);
        }
    } catch (final TriggerException | PermissionDeniedException | IOException e) {
        throw new EXistException("Failed to initialize '" + uri + "' : " + e.getMessage());
    }
}
Also used : PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException) EXistException(org.exist.EXistException) TriggerException(org.exist.collections.triggers.TriggerException)

Example 4 with EXistException

use of org.exist.EXistException in project exist by eXist-db.

the class CollectionConfigurationManager method checkRootCollectionConfig.

/**
 * Create a stored default configuration document for the root collection
 *
 * @param broker The broker which will do the operation
 * @throws EXistException if something goes wrong
 * @throws PermissionDeniedException if user does not have sufficient rights
 */
public void checkRootCollectionConfig(DBBroker broker) throws EXistException, PermissionDeniedException {
    // Copied from the legacy conf.xml in order to make the test suite work
    // TODO : backward compatibility could be ensured by copying the
    // relevant parts of conf.xml
    final String configuration = "<collection xmlns=\"http://exist-db.org/collection-config/1.0\">" + "    <index>" + "    </index>" + "</collection>";
    final TransactionManager transact = broker.getDatabase().getTransactionManager();
    try (final Txn txn = transact.beginTransaction()) {
        try (final Collection collection = broker.openCollection(XmldbURI.ROOT_COLLECTION_URI, LockMode.READ_LOCK)) {
            if (collection == null) {
                transact.abort(txn);
                throw new EXistException("collection " + XmldbURI.ROOT_COLLECTION_URI + " not found!");
            }
            final CollectionConfiguration conf = getConfiguration(collection);
            if (conf != null) {
                // it
                if (conf.getDocName() != null) {
                    transact.abort(txn);
                    return;
                }
            }
            // Configure the root collection
            addConfiguration(txn, broker, collection, configuration);
            LOG.info("Configured '{}'", collection.getURI());
        }
        transact.commit(txn);
    } catch (final CollectionConfigurationException e) {
        throw new EXistException(e.getMessage());
    }
}
Also used : TransactionManager(org.exist.storage.txn.TransactionManager) Txn(org.exist.storage.txn.Txn) EXistException(org.exist.EXistException)

Example 5 with EXistException

use of org.exist.EXistException in project exist by eXist-db.

the class ExportGUI method exportDB.

// GEN-LAST:event_btnConfSelectActionPerformed
private void exportDB(final String exportTarget, final List<ErrorReport> errorList) {
    if (!startDB()) {
        return;
    }
    try {
        final SystemExport.StatusCallback callback = new SystemExport.StatusCallback() {

            public void startCollection(final String path) {
                progress.setString(path);
            }

            public void startDocument(final String name, final int current, final int count) {
                progress.setString(name);
                progress.setValue(progress.getValue() + 1);
            }

            public void error(final String message, final Throwable exception) {
                displayMessage(message);
                if (exception != null) {
                    displayMessage(exception.toString());
                }
                displayMessage("---------------------------------------------------");
            }
        };
        progress.setIndeterminate(false);
        progress.setValue(0);
        progress.setStringPainted(true);
        progress.setMinimum(0);
        progress.setMaximum(documentCount);
        Object[] selected = directAccessBtn.getSelectedObjects();
        final boolean directAccess = (selected != null) && (selected[0] != null);
        selected = incrementalBtn.getSelectedObjects();
        final boolean incremental = (selected != null) && (selected[0] != null);
        selected = zipBtn.getSelectedObjects();
        final boolean zip = (selected != null) && (selected[0] != null);
        displayMessage("Starting export ...");
        final long start = System.currentTimeMillis();
        try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
            final Txn transaction = pool.getTransactionManager().beginTransaction()) {
            final SystemExport sysexport = new SystemExport(broker, transaction, callback, null, directAccess);
            final Path file = sysexport.export(exportTarget, incremental, zip, errorList);
            transaction.commit();
            final long end = System.currentTimeMillis();
            displayMessage("Export to " + file.toAbsolutePath().toString() + " completed successfully.");
            displayMessage("Export took " + (end - start) + "ms.");
        } catch (final EXistException e) {
            System.err.println("ERROR: Failed to retrieve database broker: " + e.getMessage());
        }
    } finally {
        progress.setString("");
        progress.setValue(0);
        currentTask.setText(" ");
    }
}
Also used : Path(java.nio.file.Path) Txn(org.exist.storage.txn.Txn) EXistException(org.exist.EXistException) DBBroker(org.exist.storage.DBBroker)

Aggregations

EXistException (org.exist.EXistException)218 PermissionDeniedException (org.exist.security.PermissionDeniedException)80 IOException (java.io.IOException)63 DBBroker (org.exist.storage.DBBroker)58 Txn (org.exist.storage.txn.Txn)46 XmldbURI (org.exist.xmldb.XmldbURI)42 Collection (org.exist.collections.Collection)41 SAXException (org.xml.sax.SAXException)32 LockException (org.exist.util.LockException)31 DocumentImpl (org.exist.dom.persistent.DocumentImpl)28 Subject (org.exist.security.Subject)23 XPathException (org.exist.xquery.XPathException)22 LockedDocument (org.exist.dom.persistent.LockedDocument)21 TriggerException (org.exist.collections.triggers.TriggerException)20 Path (java.nio.file.Path)19 URISyntaxException (java.net.URISyntaxException)18 BrokerPool (org.exist.storage.BrokerPool)18 TransactionManager (org.exist.storage.txn.TransactionManager)18 InputSource (org.xml.sax.InputSource)18 Sequence (org.exist.xquery.value.Sequence)17