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);
}
}
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();
}
}
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();
}
}
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;
}
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);
}
Aggregations