if((pool == null) || (xqueryresource == null) || (user == null)) {
abort("BrokerPool or XQueryResource or User was null!");
}
DBBroker broker = null;
DocumentImpl resource = null;
Source source = null;
XQueryPool xqPool = null;
CompiledXQuery compiled = null;
XQueryContext context = null;
try {
//get the xquery
broker = pool.get(user);
if(xqueryresource.indexOf(':') > 0) {
source = SourceFactory.getSource(broker, "", xqueryresource, true);
} else {
final XmldbURI pathUri = XmldbURI.create(xqueryresource);
resource = broker.getXMLResource(pathUri, Lock.READ_LOCK);
if(resource != null) {
source = new DBSource(broker, (BinaryDocument)resource, true);
}
}
if(source != null) {
//execute the xquery
final XQuery xquery = broker.getXQueryService();
xqPool = xquery.getXQueryPool();
//try and get a pre-compiled query from the pool
compiled = xqPool.borrowCompiledXQuery(broker, source);
if(compiled == null) {
context = xquery.newContext(AccessContext.REST); //TODO should probably have its own AccessContext.SCHEDULER
} else {
context = compiled.getContext();
}
//TODO: don't hardcode this?
if(resource != null) {
context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI.append(resource.getCollection().getURI()).toString());
context.setStaticallyKnownDocuments(new XmldbURI[] {
resource.getCollection().getURI()
});
}
if(compiled == null) {
try {
compiled = xquery.compile(context, source);
}
catch(final IOException e) {
abort("Failed to read query from " + xqueryresource);
}
}
//declare any parameters as external variables
if(params != null) {
String bindingPrefix = params.getProperty("bindingPrefix");
if(bindingPrefix == null) {
bindingPrefix = "local";
}
for(final Entry param : params.entrySet()) {
final String key = (String)param.getKey();
final String value = (String)param.getValue();
context.declareVariable( bindingPrefix + ":" + key, new StringValue(value));
}
}
xquery.execute(compiled, null);
} else {
LOG.warn("XQuery User Job not found: " + xqueryresource + ", job not scheduled");
}
} catch(final EXistException ee) {
abort("Could not get DBBroker!");
} catch(final PermissionDeniedException pde) {
abort("Permission denied for the scheduling user: " + user.getName() + "!");
} catch(final XPathException xpe) {
abort("XPathException in the Job: " + xpe.getMessage() + "!", unschedule);
} catch(final MalformedURLException e) {
abort("Could not load XQuery: " + e.getMessage());
} catch(final IOException e) {
abort("Could not load XQuery: " + e.getMessage());
} finally {
if(context != null) {
context.runCleanupTasks();
}
//return the compiled query to the pool
if(xqPool != null && source != null && compiled != null) {
xqPool.returnCompiledXQuery(source, compiled);
}
//release the lock on the xquery resource
if(resource != null) {
resource.getUpdateLock().release(Lock.READ_LOCK);
}
// Release the DBBroker
if(pool != null && broker != null) {
pool.release(broker);