use of org.exist.security.PermissionDeniedException in project exist by eXist-db.
the class Sync method pruneCollectionEntries.
private void pruneCollectionEntries(final Collection collection, final String rootTargetAbsPath, final Path targetDir, final List<String> excludes, final MemTreeBuilder output) {
try (final Stream<Path> fileStream = Files.walk(targetDir, 1)) {
fileStream.forEach(path -> {
try {
// guard against deletion of output folder
if (rootTargetAbsPath.startsWith(path.toString())) {
return;
}
if (isExcludedPath(rootTargetAbsPath, path, excludes)) {
return;
}
final String fileName = path.getFileName().toString();
final XmldbURI dbname = XmldbURI.xmldbUriFor(fileName);
final String currentCollection = collection.getURI().getCollectionPath();
if (collection.hasDocument(context.getBroker(), dbname) || collection.hasChildCollection(context.getBroker(), dbname) || currentCollection.endsWith("/" + fileName)) {
return;
}
// handle non-empty directories
if (Files.isDirectory(path)) {
deleteWithExcludes(rootTargetAbsPath, path, excludes, output);
} else {
Files.deleteIfExists(path);
// reporting
output.startElement(FILE_DELETE_ELEMENT, null);
output.addAttribute(FILE_ATTRIBUTE, path.toAbsolutePath().toString());
output.addAttribute(NAME_ATTRIBUTE, fileName);
output.endElement();
}
} catch (final IOException | URISyntaxException | PermissionDeniedException | LockException e) {
reportError(output, e.getMessage());
}
});
} catch (final IOException e) {
reportError(output, e.getMessage());
}
}
use of org.exist.security.PermissionDeniedException in project exist by eXist-db.
the class Sync method startSync.
private Sequence startSync(final String target, final String collectionPath, final Map<String, Sequence> options) throws XPathException {
final Date startDate = options.get(AFTER_OPT).hasOne() ? ((DateTimeValue) options.get(AFTER_OPT)).getDate() : null;
final boolean prune = ((BooleanValue) options.get(PRUNE_OPT)).getValue();
final List<String> excludes = new ArrayList<>(Collections.emptyList());
for (final SequenceIterator si = options.get(EXCLUDES_OPT).iterate(); si.hasNext(); ) {
excludes.add(si.nextItem().getStringValue());
}
final Path p = FileModuleHelper.getFile(target);
context.pushDocumentContext();
final MemTreeBuilder output = context.getDocumentBuilder();
final Path targetDir;
try {
if (p.isAbsolute()) {
targetDir = p;
} else {
final Optional<Path> home = context.getBroker().getConfiguration().getExistHome();
targetDir = FileUtils.resolve(home, target);
}
output.startDocument();
output.startElement(FILE_SYNC_ELEMENT, null);
output.addAttribute(FILE_COLLECTION_ATTRIBUTE, collectionPath);
output.addAttribute(FILE_DIR_ATTRIBUTE, targetDir.toAbsolutePath().toString());
final String rootTargetAbsPath = targetDir.toAbsolutePath().toString();
final String separator = rootTargetAbsPath.endsWith(File.separator) ? "" : File.separator;
syncCollection(XmldbURI.create(collectionPath), rootTargetAbsPath + separator, targetDir, startDate, prune, excludes, output);
output.endElement();
output.endDocument();
} catch (final PermissionDeniedException | LockException e) {
throw new XPathException(this, e);
} finally {
context.popDocumentContext();
}
return output.getDocument();
}
use of org.exist.security.PermissionDeniedException in project exist by eXist-db.
the class GetThumbnailsFunction method eval.
/*
* (non-Javadoc)
*
* @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[],
* org.exist.xquery.value.Sequence)
*/
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
ValueSequence result = new ValueSequence();
// boolean isDatabasePath = false;
boolean isSaveToDataBase = false;
if (args[0].isEmpty()) {
return Sequence.EMPTY_SEQUENCE;
}
AnyURIValue picturePath = (AnyURIValue) args[0].itemAt(0);
if (picturePath.getStringValue().startsWith("xmldb:exist://")) {
picturePath = new AnyURIValue(picturePath.getStringValue().substring(14));
}
AnyURIValue thumbPath = null;
if (args[1].isEmpty()) {
thumbPath = new AnyURIValue(picturePath.toXmldbURI().append(THUMBPATH));
isSaveToDataBase = true;
} else {
thumbPath = (AnyURIValue) args[1].itemAt(0);
if (thumbPath.getStringValue().startsWith("file:")) {
isSaveToDataBase = false;
thumbPath = new AnyURIValue(thumbPath.getStringValue().substring(5));
} else {
isSaveToDataBase = true;
try {
XmldbURI thumbsURI = XmldbURI.xmldbUriFor(thumbPath.getStringValue());
if (!thumbsURI.isAbsolute())
thumbsURI = picturePath.toXmldbURI().append(thumbPath.toString());
thumbPath = new AnyURIValue(thumbsURI.toString());
} catch (URISyntaxException e) {
throw new XPathException(this, e.getMessage());
}
}
}
// result.add(new StringValue(picturePath.getStringValue()));
// result.add(new StringValue(thumbPath.getStringValue() + " isDB?= "
// + isSaveToDataBase));
int maxThumbHeight = MAXTHUMBHEIGHT;
int maxThumbWidth = MAXTHUMBWIDTH;
if (!args[2].isEmpty()) {
maxThumbHeight = ((IntegerValue) args[2].itemAt(0)).getInt();
if (args[2].hasMany())
maxThumbWidth = ((IntegerValue) args[2].itemAt(1)).getInt();
}
String prefix = THUMBPREFIX;
if (!args[3].isEmpty()) {
prefix = args[3].itemAt(0).getStringValue();
}
// result.add(new StringValue("maxThumbHeight = " + maxThumbHeight
// + ", maxThumbWidth = " + maxThumbWidth));
BrokerPool pool = null;
try {
pool = BrokerPool.getInstance();
} catch (Exception e) {
result.add(new StringValue(e.getMessage()));
return result;
}
final DBBroker dbbroker = context.getBroker();
// Start transaction
final TransactionManager transact = pool.getTransactionManager();
try (final Txn transaction = transact.beginTransaction()) {
Collection thumbCollection = null;
Path thumbDir = null;
if (isSaveToDataBase) {
try {
thumbCollection = dbbroker.getOrCreateCollection(transaction, thumbPath.toXmldbURI());
dbbroker.saveCollection(transaction, thumbCollection);
} catch (Exception e) {
throw new XPathException(this, e.getMessage());
}
} else {
thumbDir = Paths.get(thumbPath.toString());
if (!Files.isDirectory(thumbDir))
try {
Files.createDirectories(thumbDir);
} catch (IOException e) {
throw new XPathException(this, e.getMessage());
}
}
Collection allPictures = null;
Collection existingThumbsCol = null;
List<Path> existingThumbsArray = null;
try {
allPictures = dbbroker.getCollection(picturePath.toXmldbURI());
if (allPictures == null) {
return Sequence.EMPTY_SEQUENCE;
}
if (isSaveToDataBase) {
existingThumbsCol = dbbroker.getCollection(thumbPath.toXmldbURI());
} else {
existingThumbsArray = FileUtils.list(thumbDir, path -> {
final String fileName = FileUtils.fileName(path);
return fileName.endsWith(".jpeg") || fileName.endsWith(".jpg");
});
}
} catch (PermissionDeniedException | IOException e) {
throw new XPathException(this, e.getMessage(), e);
}
DocumentImpl docImage = null;
BinaryDocument binImage = null;
@SuppressWarnings("unused") BufferedImage bImage = null;
@SuppressWarnings("unused") byte[] imgData = null;
Image image = null;
UnsynchronizedByteArrayOutputStream os = null;
try {
Iterator<DocumentImpl> i = allPictures.iterator(dbbroker);
while (i.hasNext()) {
docImage = i.next();
// is not already existing??
if (!((fileExist(context.getBroker(), existingThumbsCol, docImage, prefix)) || (fileExist(existingThumbsArray, docImage, prefix)))) {
if (docImage.getResourceType() == DocumentImpl.BINARY_FILE)
// TODO maybe extends for gifs too.
if (docImage.getMimeType().startsWith("image/jpeg")) {
binImage = (BinaryDocument) docImage;
try (final InputStream is = dbbroker.getBinaryResource(transaction, binImage)) {
image = ImageIO.read(is);
} catch (IOException ioe) {
throw new XPathException(this, ioe.getMessage());
}
try {
bImage = ImageModule.createThumb(image, maxThumbHeight, maxThumbWidth);
} catch (Exception e) {
throw new XPathException(this, e.getMessage());
}
if (isSaveToDataBase) {
os = new UnsynchronizedByteArrayOutputStream();
try {
ImageIO.write(bImage, "jpg", os);
} catch (Exception e) {
throw new XPathException(this, e.getMessage());
}
try (final StringInputSource sis = new StringInputSource(os.toByteArray())) {
thumbCollection.storeDocument(transaction, dbbroker, XmldbURI.create(prefix + docImage.getFileURI()), sis, new MimeType("image/jpeg", MimeType.BINARY));
} catch (final Exception e) {
throw new XPathException(this, e.getMessage());
}
// result.add(new
// StringValue(""+docImage.getFileURI()+"|"+thumbCollection.getURI()+THUMBPREFIX
// + docImage.getFileURI()));
} else {
try {
ImageIO.write(bImage, "jpg", Paths.get(thumbPath.toString() + "/" + prefix + docImage.getFileURI()).toFile());
} catch (Exception e) {
throw new XPathException(this, e.getMessage());
}
// result.add(new StringValue(
// thumbPath.toString() + "/"
// + THUMBPREFIX
// + docImage.getFileURI()));
}
}
} else {
// result.add(new StringValue(""+docImage.getURI()+"|"
// + ((existingThumbsCol != null) ? ""
// + existingThumbsCol.getURI() : thumbDir
// .toString()) + "/" + prefix
// + docImage.getFileURI()));
result.add(new StringValue(docImage.getFileURI().toString()));
}
}
} catch (final PermissionDeniedException | LockException e) {
throw new XPathException(this, e.getMessage(), e);
}
try {
transact.commit(transaction);
} catch (Exception e) {
throw new XPathException(this, e.getMessage());
}
}
final Optional<JournalManager> journalManager = pool.getJournalManager();
journalManager.ifPresent(j -> j.flush(true, false));
dbbroker.closeDocument();
return result;
}
use of org.exist.security.PermissionDeniedException 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.security.PermissionDeniedException 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);
}
}
Aggregations