Search in sources :

Example 1 with BinaryDocument

use of org.exist.dom.persistent.BinaryDocument in project exist by eXist-db.

the class BinaryDoc method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    final Sequence emptyParamReturnValue = (isCalledAs(FS_BINARY_DOC_NAME) || isCalledAs(FS_BINARY_DOC_CONTENT_DIGEST_NAME)) ? Sequence.EMPTY_SEQUENCE : BooleanValue.FALSE;
    if (args[0].isEmpty()) {
        return emptyParamReturnValue;
    }
    final String path = args[0].getStringValue();
    try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(XmldbURI.xmldbUriFor(path), LockMode.READ_LOCK)) {
        if (lockedDoc == null) {
            return emptyParamReturnValue;
        }
        final DocumentImpl doc = lockedDoc.getDocument();
        if (doc.getResourceType() != DocumentImpl.BINARY_FILE) {
            return emptyParamReturnValue;
        } else if (isCalledAs(FS_BINARY_DOC_NAME)) {
            try (final Txn transaction = context.getBroker().continueOrBeginTransaction()) {
                final BinaryDocument bin = (BinaryDocument) doc;
                final InputStream is = context.getBroker().getBinaryResource(transaction, bin);
                final Base64BinaryDocument b64doc = Base64BinaryDocument.getInstance(context, is);
                b64doc.setUrl(path);
                transaction.commit();
                return b64doc;
            }
        } else if (isCalledAs(FS_BINARY_DOC_CONTENT_DIGEST_NAME)) {
            final String algorithm = args[1].getStringValue();
            final DigestType digestType;
            try {
                digestType = DigestType.forCommonName(algorithm);
            } catch (final IllegalArgumentException e) {
                throw new XPathException(this, "Invalid algorithm: " + algorithm, e);
            }
            try (final Txn transaction = context.getBroker().getBrokerPool().getTransactionManager().beginTransaction()) {
                final BinaryDocument bin = (BinaryDocument) doc;
                final MessageDigest messageDigest = context.getBroker().getBinaryResourceContentDigest(transaction, bin, digestType);
                final InputStream is = new UnsynchronizedByteArrayInputStream(messageDigest.getValue());
                final Sequence result = BinaryValueFromInputStream.getInstance(context, new HexBinaryValueType(), is);
                transaction.commit();
                return result;
            }
        } else {
            return BooleanValue.TRUE;
        }
    } catch (final URISyntaxException e) {
        logger.error("Invalid resource URI", e);
        throw new XPathException(this, "Invalid resource uri", e);
    } catch (final PermissionDeniedException e) {
        logger.error("{}: permission denied to read resource", path, e);
        throw new XPathException(this, path + ": permission denied to read resource");
    } catch (final IOException | TransactionException e) {
        logger.error("{}: I/O error while reading resource", path, e);
        throw new XPathException(this, path + ": I/O error while reading resource", e);
    }
}
Also used : XPathException(org.exist.xquery.XPathException) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) InputStream(java.io.InputStream) Txn(org.exist.storage.txn.Txn) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) BinaryDocument(org.exist.dom.persistent.BinaryDocument) TransactionException(org.exist.storage.txn.TransactionException) DigestType(org.exist.util.crypto.digest.DigestType) LockedDocument(org.exist.dom.persistent.LockedDocument) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) PermissionDeniedException(org.exist.security.PermissionDeniedException) MessageDigest(org.exist.util.crypto.digest.MessageDigest)

Example 2 with BinaryDocument

use of org.exist.dom.persistent.BinaryDocument in project exist by eXist-db.

the class CollectionStoreTest method storeBinary.

private void storeBinary(final PreserveType preserveOnCopy) throws EXistException, PermissionDeniedException, IOException, TriggerException, LockException {
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        try (final Collection col = broker.getOrCreateCollection(transaction, TestConstants.TEST_COLLECTION_URI)) {
            final byte[] bin = TEST_BIN_DOC.getBytes(UTF_8);
            try (final InputStream is = new UnsynchronizedByteArrayInputStream(bin)) {
                final int docId = broker.getNextResourceId(transaction);
                final BinaryDocument binDoc = col.addBinaryResource(transaction, broker, new BinaryDocument(broker.getBrokerPool(), col, docId, TEST_BIN_DOC_URI), is, "text/plain", bin.length, null, null, preserveOnCopy);
                assertNotNull(binDoc);
            }
            broker.saveCollection(transaction, col);
        }
        try (final Collection col = broker.openCollection(TestConstants.TEST_COLLECTION_URI, LockMode.READ_LOCK)) {
            try (final LockedDocument lockedDoc = col.getDocumentWithLock(broker, TEST_BIN_DOC_URI, LockMode.READ_LOCK)) {
                // NOTE: early release of collection lock inline with async locking
                col.close();
                if (lockedDoc != null) {
                    assertTrue(lockedDoc.getDocument() instanceof BinaryDocument);
                    final BinaryDocument doc = (BinaryDocument) lockedDoc.getDocument();
                    final Try<String, IOException> docContent = broker.withBinaryFile(transaction, doc, is -> Try.TaggedTryUnchecked(IOException.class, () -> new String(Files.readAllBytes(is), UTF_8)));
                    assertEquals(TEST_BIN_DOC, docContent.get());
                }
            }
        }
        transaction.commit();
    }
}
Also used : UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) InputStream(java.io.InputStream) Txn(org.exist.storage.txn.Txn) IOException(java.io.IOException) BinaryDocument(org.exist.dom.persistent.BinaryDocument) DBBroker(org.exist.storage.DBBroker) LockedDocument(org.exist.dom.persistent.LockedDocument) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) BrokerPool(org.exist.storage.BrokerPool)

Example 3 with BinaryDocument

use of org.exist.dom.persistent.BinaryDocument in project exist by eXist-db.

the class SystemExportFiltersTest method exportImport.

@Test
public void exportImport() throws Exception {
    Path file;
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        List<String> filters = new ArrayList<>();
        filters.add(FilterForBackup.class.getName());
        broker.getConfiguration().setProperty(SystemExport.CONFIG_FILTERS, filters);
        final Collection test = broker.getCollection(TEST_COLLECTION_URI);
        assertNotNull(test);
        boolean direct = true;
        final SystemExport sysexport = new SystemExport(broker, transaction, null, null, direct);
        final Path backupDir = tempFolder.newFolder().toPath();
        file = sysexport.export(backupDir.toAbsolutePath().toString(), false, false, null);
        transaction.commit();
    }
    TestUtils.cleanupDB();
    final SystemImport restore = new SystemImport(pool);
    final RestoreListener listener = new LogRestoreListener();
    restore.restore(TestUtils.ADMIN_DB_USER, TestUtils.ADMIN_DB_PWD, null, file, listener);
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
        final Txn transaction = pool.getTransactionManager().beginTransaction()) {
        final Collection test = broker.getCollection(TEST_COLLECTION_URI);
        assertNotNull(test);
        DocumentImpl doc = getDoc(broker, test, doc01uri.lastSegment());
        assertEquals(XML1_BACKUP, serializer(broker, doc));
        doc = getDoc(broker, test, doc02uri.lastSegment());
        assertEquals(XML2_PROPER, serializer(broker, doc));
        doc = getDoc(broker, test, doc03uri.lastSegment());
        assertEquals(XML3_PROPER, serializer(broker, doc));
        doc = getDoc(broker, test, doc11uri.lastSegment());
        assertTrue(doc instanceof BinaryDocument);
        try (final InputStream is = broker.getBinaryResource(transaction, ((BinaryDocument) doc))) {
            assertEquals(BINARY, InputStreamUtil.readString(is, UTF_8));
        }
        transaction.commit();
    }
}
Also used : Path(java.nio.file.Path) LogRestoreListener(org.exist.backup.restore.listener.LogRestoreListener) InputStream(java.io.InputStream) Txn(org.exist.storage.txn.Txn) DocumentImpl(org.exist.dom.persistent.DocumentImpl) BinaryDocument(org.exist.dom.persistent.BinaryDocument) DBBroker(org.exist.storage.DBBroker) Collection(org.exist.collections.Collection) LogRestoreListener(org.exist.backup.restore.listener.LogRestoreListener) RestoreListener(org.exist.backup.restore.listener.RestoreListener) BrokerPool(org.exist.storage.BrokerPool)

Example 4 with BinaryDocument

use of org.exist.dom.persistent.BinaryDocument in project exist by eXist-db.

the class DocumentNameOrId method getResourceByAbsoluteId.

private Sequence getResourceByAbsoluteId(final IntegerValue ivAbsoluteId) throws XPathException, PermissionDeniedException, LockException, IOException {
    final BigInteger absoluteId = ivAbsoluteId.toJavaObject(BigInteger.class);
    final Tuple3<Integer, Integer, Byte> decoded = decodeAbsoluteResourceId(absoluteId);
    final DocumentImpl doc = context.getBroker().getResourceById(decoded._1, decoded._3, decoded._2);
    if (doc != null) {
        try (final ManagedDocumentLock docLock = context.getBroker().getBrokerPool().getLockManager().acquireDocumentReadLock(doc.getURI())) {
            if (doc instanceof BinaryDocument) {
                final BinaryDocument bin = (BinaryDocument) doc;
                final InputStream is = context.getBroker().getBinaryResource(bin);
                return Base64BinaryDocument.getInstance(context, is);
            } else {
                return new NodeProxy(doc);
            }
        }
    }
    return Sequence.EMPTY_SEQUENCE;
}
Also used : BigInteger(java.math.BigInteger) BinaryDocument(org.exist.dom.persistent.BinaryDocument) ManagedDocumentLock(org.exist.storage.lock.ManagedDocumentLock) InputStream(java.io.InputStream) BigInteger(java.math.BigInteger) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy)

Example 5 with BinaryDocument

use of org.exist.dom.persistent.BinaryDocument in project exist by eXist-db.

the class SourceFactoryTest method getSourceFromXmldb.

@Test
public void getSourceFromXmldb() throws IOException, PermissionDeniedException {
    final String contextPath = "xmldb:exist:///db";
    final String location = "library.xqm";
    final DBBroker mockBroker = createMock(DBBroker.class);
    final LockedDocument mockLockedDoc = createMock(LockedDocument.class);
    final BinaryDocument mockBinDoc = createMock(BinaryDocument.class);
    expect(mockBroker.getXMLResource(anyObject(), anyObject())).andReturn(mockLockedDoc);
    expect(mockLockedDoc.getDocument()).andReturn(mockBinDoc);
    expect(mockBinDoc.getResourceType()).andReturn(BinaryDocument.BINARY_FILE);
    expect(mockBinDoc.getURI()).andReturn(XmldbURI.create(contextPath).append(location)).times(2);
    expect(mockBinDoc.getLastModified()).andReturn(123456789l);
    /*expect*/
    mockLockedDoc.close();
    replay(mockBroker, mockLockedDoc, mockBinDoc);
    final Source libSource = SourceFactory.getSource(mockBroker, contextPath, location, false);
    assertTrue(libSource instanceof DBSource);
    assertEquals(XmldbURI.create(contextPath).append(location), ((DBSource) libSource).getDocumentPath());
    verify(mockBroker, mockLockedDoc, mockBinDoc);
}
Also used : BinaryDocument(org.exist.dom.persistent.BinaryDocument) DBBroker(org.exist.storage.DBBroker) LockedDocument(org.exist.dom.persistent.LockedDocument) Test(org.junit.Test)

Aggregations

BinaryDocument (org.exist.dom.persistent.BinaryDocument)39 LockedDocument (org.exist.dom.persistent.LockedDocument)18 XmldbURI (org.exist.xmldb.XmldbURI)15 Collection (org.exist.collections.Collection)14 Txn (org.exist.storage.txn.Txn)14 DBBroker (org.exist.storage.DBBroker)13 InputStream (java.io.InputStream)12 IOException (java.io.IOException)11 DocumentImpl (org.exist.dom.persistent.DocumentImpl)11 PermissionDeniedException (org.exist.security.PermissionDeniedException)11 URISyntaxException (java.net.URISyntaxException)9 Path (java.nio.file.Path)8 BrokerPool (org.exist.storage.BrokerPool)7 Test (org.junit.Test)7 DBSource (org.exist.source.DBSource)6 TransactionManager (org.exist.storage.txn.TransactionManager)6 XPathException (org.exist.xquery.XPathException)5 XQueryContext (org.exist.xquery.XQueryContext)5 Sequence (org.exist.xquery.value.Sequence)5 TransactionException (org.exist.storage.txn.TransactionException)4