use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class XmldbBinariesTest method storeBinaryFile.
@Override
protected void storeBinaryFile(final XmldbURI filePath, byte[] content) throws Exception {
Collection colRoot = null;
try {
colRoot = DatabaseManager.getCollection(getBaseUri() + "/db", ADMIN_DB_USER, ADMIN_DB_PWD);
final XmldbURI[] collectionNames = filePath.removeLastSegment().getPathSegments();
final Deque<Collection> cols = new ArrayDeque<>();
try {
Collection current = colRoot;
for (int i = 1; i < collectionNames.length; i++) {
final Collection child = getOrCreateCollection(current, collectionNames[i].toString());
cols.push(child);
current = child;
}
final String fileName = filePath.lastSegment().toString();
final Resource resource = current.createResource(fileName, BinaryResource.RESOURCE_TYPE);
resource.setContent(content);
current.storeResource(resource);
} finally {
while (!cols.isEmpty()) {
try {
cols.pop().close();
} catch (XMLDBException e) {
}
}
}
} finally {
if (colRoot != null) {
colRoot.close();
}
}
}
use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class Deploy method installAndDeployFromDb.
private Optional<String> installAndDeployFromDb(final Txn transaction, final String path, final String repoURI) throws XPathException {
final XmldbURI docPath = XmldbURI.createInternal(path);
try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(docPath, LockMode.READ_LOCK)) {
if (lockedDoc == null) {
throw new XPathException(this, EXPathErrorCode.EXPDY001, path + " no such .xar", new StringValue(path));
}
final DocumentImpl doc = lockedDoc.getDocument();
if (doc.getResourceType() != DocumentImpl.BINARY_FILE) {
throw new XPathException(this, EXPathErrorCode.EXPDY001, path + " is not a valid .xar", new StringValue(path));
}
RepoPackageLoader loader = null;
if (repoURI != null) {
loader = new RepoPackageLoader(repoURI);
}
final XarSource xarSource = new BinaryDocumentXarSource(context.getBroker().getBrokerPool(), transaction, (BinaryDocument) doc);
final Deployment deployment = new Deployment();
return deployment.installAndDeploy(context.getBroker(), transaction, xarSource, loader);
} catch (PackageException | IOException | PermissionDeniedException e) {
LOG.error(e.getMessage(), e);
throw new XPathException(this, EXPathErrorCode.EXPDY007, "Package installation failed: " + e.getMessage(), new StringValue(e.getMessage()));
}
}
use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class AbstractCompressFunction method compressCollection.
/**
* Adds a Collection and its child collections and resources recursively to
* a archive
*
* @param os
* The Output Stream to add the document to
* @param col
* The Collection to add to the archive
* @param useHierarchy
* Whether to use a folder hierarchy in the archive file that
* reflects the collection hierarchy
*/
private void compressCollection(OutputStream os, Collection col, boolean useHierarchy, String stripOffset) throws IOException, SAXException, LockException, PermissionDeniedException {
// iterate over child documents
final DBBroker broker = context.getBroker();
final LockManager lockManager = broker.getBrokerPool().getLockManager();
final MutableDocumentSet childDocs = new DefaultDocumentSet();
col.getDocuments(broker, childDocs);
for (final Iterator<DocumentImpl> itChildDocs = childDocs.getDocumentIterator(); itChildDocs.hasNext(); ) {
DocumentImpl childDoc = itChildDocs.next();
try (final ManagedDocumentLock updateLock = lockManager.acquireDocumentReadLock(childDoc.getURI())) {
compressResource(os, childDoc, useHierarchy, stripOffset, "", null);
}
}
// iterate over child collections
for (final Iterator<XmldbURI> itChildCols = col.collectionIterator(broker); itChildCols.hasNext(); ) {
// get the child collection
XmldbURI childColURI = itChildCols.next();
Collection childCol = broker.getCollection(col.getURI().append(childColURI));
// recurse
compressCollection(os, childCol, useHierarchy, stripOffset);
}
}
use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class EmbeddedInputStream method openStream.
private static Either<IOException, InputStream> openStream(final BrokerPool pool, final XmldbURL url) {
if (LOG.isDebugEnabled()) {
LOG.debug("Begin document download");
}
try {
final XmldbURI path = XmldbURI.create(url.getPath());
try (final DBBroker broker = pool.getBroker()) {
try (final LockedDocument lockedResource = broker.getXMLResource(path, Lock.LockMode.READ_LOCK)) {
if (lockedResource == null) {
// Test for collection
try (final Collection collection = broker.openCollection(path, Lock.LockMode.READ_LOCK)) {
if (collection == null) {
// No collection, no document
return Left(new IOException("Resource " + url.getPath() + " not found."));
} else {
// Collection
return Left(new IOException("Resource " + url.getPath() + " is a collection."));
}
}
} else {
final DocumentImpl resource = lockedResource.getDocument();
if (resource.getResourceType() == DocumentImpl.XML_FILE) {
final Serializer serializer = broker.borrowSerializer();
try {
// Preserve doctype
serializer.setProperty(EXistOutputKeys.OUTPUT_DOCTYPE, "yes");
// serialize the XML to a temporary file
final TemporaryFileManager tempFileManager = TemporaryFileManager.getInstance();
final Path tempFile = tempFileManager.getTemporaryFile();
try (final Writer writer = Files.newBufferedWriter(tempFile, UTF_8, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
serializer.serialize(resource, writer);
}
// NOTE: the temp file will be returned to the manager when the InputStream is closed
return Right(new CloseNotifyingInputStream(Files.newInputStream(tempFile, StandardOpenOption.READ), () -> tempFileManager.returnTemporaryFile(tempFile)));
} finally {
broker.returnSerializer(serializer);
}
} else if (resource.getResourceType() == BinaryDocument.BINARY_FILE) {
return Right(broker.getBinaryResource((BinaryDocument) resource));
} else {
return Left(new IOException("Unknown resource type " + url.getPath() + ": " + resource.getResourceType()));
}
}
} finally {
if (LOG.isDebugEnabled()) {
LOG.debug("End document download");
}
}
}
} catch (final EXistException | PermissionDeniedException | SAXException e) {
LOG.error(e);
return Left(new IOException(e.getMessage(), e));
} catch (final IOException e) {
return Left(e);
}
}
use of org.exist.xmldb.XmldbURI in project exist by eXist-db.
the class Deployment method storeRepoXML.
/**
* Store repo.xml into the db. Adds the time of deployment to the descriptor.
*
* @param repoXML
* @param targetCollection
* @throws XPathException
*/
private void storeRepoXML(final DBBroker broker, final Txn transaction, final DocumentImpl repoXML, final XmldbURI targetCollection, final Optional<RequestedPerms> requestedPerms) throws PackageException, XPathException {
// Store repo.xml
final DateTimeValue time = new DateTimeValue(new Date());
final MemTreeBuilder builder = new MemTreeBuilder();
builder.startDocument();
final UpdatingDocumentReceiver receiver = new UpdatingDocumentReceiver(builder, time.getStringValue());
try {
repoXML.copyTo(broker, receiver);
} catch (final SAXException e) {
throw new PackageException("Error while updating repo.xml in-memory: " + e.getMessage(), e);
}
builder.endDocument();
final DocumentImpl updatedXML = builder.getDocument();
try {
final Collection collection = broker.getOrCreateCollection(transaction, targetCollection);
final XmldbURI name = XmldbURI.createInternal("repo.xml");
final Permission permission = PermissionFactory.getDefaultResourcePermission(broker.getBrokerPool().getSecurityManager());
setPermissions(broker, requestedPerms, false, MimeType.XML_TYPE, permission);
collection.storeDocument(transaction, broker, name, updatedXML, MimeType.XML_TYPE, null, null, permission, null, null);
} catch (final PermissionDeniedException | IOException | SAXException | LockException | EXistException e) {
throw new PackageException("Error while storing updated repo.xml: " + e.getMessage(), e);
}
}
Aggregations