use of org.exist.xquery.value.AnyURIValue 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.xquery.value.AnyURIValue in project exist by eXist-db.
the class FunNamespaceURIForPrefix method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
if (context.getProfiler().isEnabled()) {
context.getProfiler().start(this);
context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
if (contextSequence != null) {
context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
}
}
String prefix;
if (args[0].isEmpty()) {
prefix = "";
} else {
prefix = args[0].itemAt(0).getStringValue();
}
String namespace;
if ("xml".equals(prefix)) {
namespace = Namespaces.XML_NS;
} else {
final Map<String, String> prefixes = FunInScopePrefixes.collectPrefixes(context, (NodeValue) args[1].itemAt(0));
namespace = prefixes.get(prefix);
}
Sequence result;
if (namespace == null) {
result = Sequence.EMPTY_SEQUENCE;
} else {
result = new AnyURIValue(namespace);
}
if (context.getProfiler().isEnabled()) {
context.getProfiler().end(this, "", result);
}
return result;
}
use of org.exist.xquery.value.AnyURIValue in project exist by eXist-db.
the class DocTest method docAvailable_dynamicallyAvailableDocument_relativeUri.
@Test
public void docAvailable_dynamicallyAvailableDocument_relativeUri() throws XPathException, EXistException, PermissionDeniedException, URISyntaxException {
final BrokerPool pool = BrokerPool.getInstance();
final String doc = "<timestamp>" + System.currentTimeMillis() + "</timestamp>";
final String baseUri = "http://from-dynamic-context/";
final String docRelativeUri = "doc1";
final String query = "fn:doc-available('" + docRelativeUri + "')";
try (final DBBroker broker = pool.getBroker()) {
final XQueryContext context = new XQueryContext(pool);
context.setBaseURI(new AnyURIValue(new URI(baseUri)));
context.addDynamicallyAvailableDocument(baseUri + docRelativeUri, (broker2, transaction, uri) -> asInMemoryDocument(doc));
final XQuery xqueryService = pool.getXQueryService();
final CompiledXQuery compiled = xqueryService.compile(context, query);
final Sequence result = xqueryService.execute(broker, compiled, null);
assertFalse(result.isEmpty());
assertEquals(1, result.getItemCount());
assertTrue(result.itemAt(0).toJavaObject(Boolean.class).booleanValue());
}
}
use of org.exist.xquery.value.AnyURIValue in project exist by eXist-db.
the class FunUnparsedTextTest method unparsedTextAvailable_dynamicallyAvailableDocument_relativeUri.
@Test
public void unparsedTextAvailable_dynamicallyAvailableDocument_relativeUri() throws XPathException, EXistException, PermissionDeniedException, URISyntaxException {
final BrokerPool pool = BrokerPool.getInstance();
final String text = "hello, the time is: " + System.currentTimeMillis();
final String baseUri = "http://from-dynamic-context/";
final String textRelativeUri = "doc1";
final String query = "fn:unparsed-text-available('" + textRelativeUri + "')";
try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) {
final XQueryContext context = new XQueryContext(pool);
context.setBaseURI(new AnyURIValue(new URI(baseUri)));
context.addDynamicallyAvailableTextResource(baseUri + textRelativeUri, UTF_8, (broker2, transaction, uri, charset) -> new InputStreamReader(new ByteArrayInputStream(text.getBytes(UTF_8)), charset));
final XQuery xqueryService = pool.getXQueryService();
final CompiledXQuery compiled = xqueryService.compile(context, query);
final Sequence result = xqueryService.execute(broker, compiled, null);
assertFalse(result.isEmpty());
assertEquals(1, result.getItemCount());
assertTrue(result.itemAt(0).toJavaObject(Boolean.class).booleanValue());
}
}
use of org.exist.xquery.value.AnyURIValue in project exist by eXist-db.
the class FunUnparsedTextTest method unparsedText_dynamicallyAvailableDocument_relativeUri.
@Test
public void unparsedText_dynamicallyAvailableDocument_relativeUri() throws XPathException, EXistException, PermissionDeniedException, URISyntaxException {
final BrokerPool pool = BrokerPool.getInstance();
final String text = "hello, the time is: " + System.currentTimeMillis();
final String baseUri = "http://from-dynamic-context/";
final String textRelativeUri = "doc1";
final String query = "fn:unparsed-text('" + textRelativeUri + "')";
try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) {
final XQueryContext context = new XQueryContext(pool);
context.setBaseURI(new AnyURIValue(new URI(baseUri)));
context.addDynamicallyAvailableTextResource(baseUri + textRelativeUri, UTF_8, (broker2, transaction, uri, charset) -> new InputStreamReader(new ByteArrayInputStream(text.getBytes(UTF_8)), charset));
final XQuery xqueryService = pool.getXQueryService();
final CompiledXQuery compiled = xqueryService.compile(context, query);
final Sequence result = xqueryService.execute(broker, compiled, null);
assertFalse(result.isEmpty());
assertEquals(1, result.getItemCount());
assertEquals(Type.STRING, result.itemAt(0).getType());
assertEquals(text, result.itemAt(0).getStringValue());
}
}
Aggregations