use of org.exist.source.Source in project exist by eXist-db.
the class RpcConnection method summary.
public Map<String, Object> summary(final String xpath) throws EXistException, PermissionDeniedException {
final Source source = new StringSource(xpath);
return this.<Map<String, Object>>withDb((broker, transaction) -> {
final long startTime = System.currentTimeMillis();
final Map<String, Object> parameters = new HashMap<>();
try {
final QueryResult qr = this.<QueryResult>compileQuery(broker, transaction, source, parameters).apply(compiledQuery -> doQuery(broker, compiledQuery, null, parameters));
if (qr == null) {
return new HashMap<>();
}
if (qr.hasErrors()) {
throw qr.getException();
}
if (qr.result == null) {
return summaryToMap(qr.queryTime, null, null, null);
}
final Tuple2<java.util.Collection<NodeCount>, java.util.Collection<DoctypeCount>> summary = summarise(qr.result);
return summaryToMap(System.currentTimeMillis() - startTime, qr.result, summary._1, summary._2);
} catch (final XPathException e) {
throw new EXistException(e);
}
});
}
use of org.exist.source.Source in project exist by eXist-db.
the class RpcConnection method printDiagnostics.
@Override
public String printDiagnostics(final String query, final Map<String, Object> parameters) throws EXistException, PermissionDeniedException {
final Source source = new StringSource(query);
return withDb((broker, transaction) -> {
try {
return this.<String>compileQuery(broker, transaction, source, parameters).apply(compiledQuery -> {
final StringWriter writer = new StringWriter();
compiledQuery.dump(writer);
return writer.toString();
});
} catch (final XPathException e) {
throw new EXistException(e);
}
});
}
use of org.exist.source.Source in project exist by eXist-db.
the class Modification method select.
/**
* Evaluate the select expression.
*
* @param docs the documents to evaludate the expression over
*
* @return The selected nodes.
*
* @throws PermissionDeniedException if the caller has insufficient priviledges
* @throws EXistException if the database raises an error
* @throws XPathException if the XPath raises an error
*/
protected NodeList select(DocumentSet docs) throws PermissionDeniedException, EXistException, XPathException {
final XQuery xquery = broker.getBrokerPool().getXQueryService();
final XQueryPool pool = broker.getBrokerPool().getXQueryPool();
final Source source = new StringSource(selectStmt);
CompiledXQuery compiled = pool.borrowCompiledXQuery(broker, source);
XQueryContext context;
if (compiled == null) {
context = new XQueryContext(broker.getBrokerPool());
} else {
context = compiled.getContext();
context.prepareForReuse();
}
context.setStaticallyKnownDocuments(docs);
declareNamespaces(context);
declareVariables(context);
if (compiled == null)
try {
compiled = xquery.compile(context, source);
} catch (final IOException e) {
throw new EXistException("An exception occurred while compiling the query: " + e.getMessage());
}
Sequence resultSeq = null;
try {
resultSeq = xquery.execute(broker, compiled, null);
} finally {
context.runCleanupTasks();
pool.returnCompiledXQuery(source, compiled);
}
if (!(resultSeq.isEmpty() || Type.subTypeOf(resultSeq.getItemType(), Type.NODE))) {
throw new EXistException("select expression should evaluate to a node-set; got " + Type.getTypeName(resultSeq.getItemType()));
}
if (LOG.isDebugEnabled()) {
LOG.debug("found {} for select: {}", resultSeq.getItemCount(), selectStmt);
}
return resultSeq.toNodeSet();
}
use of org.exist.source.Source in project exist by eXist-db.
the class ConnectionIT method getConnectionIsAutomaticallyClosed.
@Test
public void getConnectionIsAutomaticallyClosed() throws EXistException, XPathException, PermissionDeniedException, IOException {
final String mainQuery = "import module namespace sql = \"http://exist-db.org/xquery/sql\";\n" + "sql:get-connection(\"" + h2Database.getDriverClass().getName() + "\", \"" + h2Database.getUrl() + "\", \"" + h2Database.getUser() + "\", \"" + h2Database.getPassword() + "\")";
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
final Source mainQuerySource = new StringSource(mainQuery);
try (final DBBroker broker = pool.getBroker();
final Txn transaction = pool.getTransactionManager().beginTransaction()) {
final XQueryContext escapedMainQueryContext = withCompiledQuery(broker, mainQuerySource, mainCompiledQuery -> {
final XQueryContext mainQueryContext = mainCompiledQuery.getContext();
// execute the query
final Sequence result = executeQuery(broker, mainCompiledQuery);
// check that the handle for the sql connection that was created was valid
assertEquals(1, result.getItemCount());
assertTrue(result.itemAt(0) instanceof IntegerValue);
assertEquals(Type.LONG, result.itemAt(0).getType());
final long connectionHandle = result.itemAt(0).toJavaObject(long.class);
assertFalse(connectionHandle == 0);
// intentionally escape the context from the lambda
return mainQueryContext;
});
// check the connections map is empty
final int connectionsCount = ModuleUtils.readContextMap(escapedMainQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
assertEquals(0, connectionsCount);
transaction.commit();
}
}
use of org.exist.source.Source in project exist by eXist-db.
the class ConnectionIT method getConnectionFromModuleIsAutomaticallyClosed.
@Test
public void getConnectionFromModuleIsAutomaticallyClosed() throws EXistException, XPathException, PermissionDeniedException, IOException, LockException, SAXException {
final String moduleQuery = "module namespace mymodule = \"http://mymodule.com\";\n" + "import module namespace sql = \"http://exist-db.org/xquery/sql\";\n" + "declare function mymodule:get-handle() {\n" + " sql:get-connection(\"" + h2Database.getDriverClass().getName() + "\", \"" + h2Database.getUrl() + "\", \"" + h2Database.getUser() + "\", \"" + h2Database.getPassword() + "\")\n" + "};\n";
final String mainQuery = "import module namespace mymodule = \"http://mymodule.com\" at \"xmldb:exist:///db/mymodule.xqm\";\n" + "mymodule:get-handle()";
final Source mainQuerySource = new StringSource(mainQuery);
final BrokerPool pool = existEmbeddedServer.getBrokerPool();
try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));
final Txn transaction = pool.getTransactionManager().beginTransaction()) {
// store module
try (final Collection collection = broker.openCollection(XmldbURI.create("/db"), Lock.LockMode.WRITE_LOCK)) {
broker.storeDocument(transaction, XmldbURI.create("mymodule.xqm"), new StringInputSource(moduleQuery.getBytes(UTF_8)), MimeType.XQUERY_TYPE, collection);
}
final Tuple2<XQueryContext, ModuleContext> escapedContexts = withCompiledQuery(broker, mainQuerySource, mainCompiledQuery -> {
final XQueryContext mainQueryContext = mainCompiledQuery.getContext();
// get the context of the library module
final Module[] libraryModules = mainQueryContext.getModules("http://mymodule.com");
assertEquals(1, libraryModules.length);
assertTrue(libraryModules[0] instanceof ExternalModule);
final ExternalModule libraryModule = (ExternalModule) libraryModules[0];
final XQueryContext libraryQueryContext = libraryModule.getContext();
assertTrue(libraryQueryContext instanceof ModuleContext);
// execute the query
final Sequence result = executeQuery(broker, mainCompiledQuery);
// check that the handle for the sql connection that was created was valid
assertEquals(1, result.getItemCount());
assertTrue(result.itemAt(0) instanceof IntegerValue);
assertEquals(Type.LONG, result.itemAt(0).getType());
final long connectionHandle = result.itemAt(0).toJavaObject(long.class);
assertFalse(connectionHandle == 0);
// intentionally escape the contexts from the lambda
return Tuple(mainQueryContext, (ModuleContext) libraryQueryContext);
});
final XQueryContext escapedMainQueryContext = escapedContexts._1;
final ModuleContext escapedLibraryQueryContext = escapedContexts._2;
assertTrue(escapedMainQueryContext != escapedLibraryQueryContext);
// check the connections were closed in the main module
final int mainConnectionsCount = ModuleUtils.readContextMap(escapedMainQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
assertEquals(0, mainConnectionsCount);
// check the connections were closed in the library module
final int libraryConnectionsCount = ModuleUtils.readContextMap(escapedLibraryQueryContext, SQLModule.CONNECTIONS_CONTEXTVAR, Map::size);
assertEquals(0, libraryConnectionsCount);
transaction.commit();
}
}
Aggregations