### Travis CI Installation and Setup Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/integration-testing/listings/travis-4.txt Defines the steps to be executed before the main script, including pulling and creating Docker containers, and installing dependencies. ```yaml before_install: - docker pull $img - docker create --name exist-ci -p 8080:8080 $img install: - ant develop ``` -------------------------------- ### Docker Setup and eXist-DB Deployment Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/integration-testing/listings/travis-2.txt Commands to pull the eXist-DB Docker image, create a container, copy the XAR artifact, start the database, and wait for it to become available. ```bash # Download exist into the test VM before_install: - docker pull $img - docker create --name exist-ci -p 8080:8080 $img install: - ant develop # take the .xar created above and install and deploy in a clean eXist-db instance. before_script: - docker cp ./build/*-dev.xar exist-ci:exist/autodeploy - docker start exist-ci # exist needs time - sleep 30 - docker ps ``` -------------------------------- ### Call Example Module Function Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/xquery/listings/listing-23.txt Imports and calls the 'echo' function from the example module. Ensure the module is correctly configured and accessible. ```XQuery xquery version "1.0"; import module namespace example="http://exist-db.org/xquery/examples" at "java:org.exist.examples.xquery.ExampleModule"; example:echo(("Hello", "World!")) ``` -------------------------------- ### Check Java Version Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/basic-installation/listings/listing-1.txt Verify that Java is installed and check its version before proceeding with the installation. ```bash java -version ``` -------------------------------- ### Run Integration Tests with Cypress Source: https://github.com/exist-db/documentation/blob/master/README.md Execute integration tests using Cypress. This requires Node.js and the installation of Cypress.js via `npm i`. Ensure a running instance of eXist-db with the documentation app installed is accessible at localhost:8080 and has an empty admin password. ```bash npm run cypress ``` -------------------------------- ### Build Stage: Install Apache Ant Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/docker/listings/listing-5.txt Installs Apache Ant from a tarball, configures its home directory, and adds it to the PATH. This stage is used to build the application's XAR file. ```dockerfile FROM openjdk:8-jdk-slim as builder USER root ENV ANT_VERSION 1.10.5 ENV ANT_HOME /etc/ant-${ANT_VERSION} WORKDIR /tmp RUN wget http://www-us.apache.org/dist/ant/binaries/apache-ant-${ANT_VERSION}-bin.tar.gz \ && mkdir ant-${ANT_VERSION} \ && tar -zxvf apache-ant-${ANT_VERSION}-bin.tar.gz \ && mv apache-ant-${ANT_VERSION} ${ANT_HOME} \ && rm apache-ant-${ANT_VERSION}-bin.tar.gz \ && rm -rf ant-${ANT_VERSION} \ && rm -rf ${ANT_HOME}/manual \ && unset ANT_VERSION ENV PATH ${PATH}:${ANT_HOME}/bin WORKDIR /home/my-app COPY . . RUN apk add --no-cache --virtual .build-deps \ nodejs \ nodejs-npm \ git \ && npm i npm@latest -g \ && ant ``` -------------------------------- ### Running eXist-DB with Docker Source: https://context7.com/exist-db/documentation/llms.txt Deploy eXist-DB using official distroless Docker images. This example shows how to pull, run, and manage the container, including data persistence and application deployment. ```Bash # Pull the latest stable release image docker pull existdb/existdb:release # Run eXist-db, exposing HTTP and HTTPS ports, with a named volume for persistence docker run -it -d \ -p 8080:8080 \ -p 8443:8443 \ --name exist \ -v exist-data:/exist/data \ existdb/existdb:release # Verify it is running curl http://localhost:8080/exist/rest/db # Copy a .xar app package into the running container and install it docker cp myapp-1.0.xar exist:/exist/autodeploy/ # Execute an XQuery directly inside the container docker exec exist \ java -jar /exist/start.jar client \ --no-gui --xpath "count(collection('/db')//element())" # Stop and remove the container (data volume persists) docker stop exist docker rm exist ``` -------------------------------- ### Handling Start Element Events Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-113.txt This method is called when an XML element starts. It manages deferred elements and forwards the event to the superclass. ```Java public void startElement(Txn transaction, ElementImpl element, NodePath path) { if (isDocumentGMLAware) { //Release the deferred element if any if (deferredElement != null) processDeferredElement(); //Retain this element deferredElement = element; } //Forward the event to the next listener super.startElement(transaction, element, path); } ``` -------------------------------- ### Retrieve Document or Execute XQuery via GET Source: https://context7.com/exist-db/documentation/llms.txt Use GET requests to retrieve XML documents by their database path or execute XQuery queries on the fly. Supports query parameters for filtering, pagination, and indentation. Results can be wrapped in an element. ```bash # Retrieve a stored XML document curl -u admin:secret http://localhost:8080/exist/rest/db/shakespeare/plays/hamlet.xml ``` ```bash # Execute an inline XQuery via GET parameters # Find SPEECH elements where SPEAKER is JULIET, return 5 results starting at position 3 curl -u admin:secret \ "http://localhost:8080/exist/rest/db/shakespeare?_query=//SPEECH[SPEAKER=%22JULIET%22]&_start=3&_howmany=5&_indent=yes&_wrap=yes" ``` ```bash # Cache query results in a server session curl -u admin:secret \ "http://localhost:8080/exist/rest/db/collection?_query=//item&_cache=yes" # Returns X-Session-Id header; reuse with: curl -u admin:secret \ "http://localhost:8080/exist/rest/db/collection?_session=0&_start=11&_howmany=10" ``` ```bash # Release the session curl -u admin:secret \ "http://localhost:8080/exist/rest/db?_release=0" ``` -------------------------------- ### Run JavaScript/XQSuite Unit Tests Source: https://github.com/exist-db/documentation/blob/master/README.md Execute JavaScript or XQSuite unit tests using Maven. Ensure a running instance of eXist-db with the documentation app installed is accessible at localhost:8080 and has an empty admin password. ```bash mvn test ``` -------------------------------- ### Java Transaction Handling Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_codereview/listings/listing-1.txt Demonstrates basic transaction management including starting, committing, and rolling back a transaction. Ensure proper exception handling and null checks. ```java Transaction trx = new Transaction(); try { trx.start(); // do something if (trx != null ) trx.commit; trx = null; } catch ( Exception e ) { // processing exception } if( trx != null ) { trx.rollback(); } ``` -------------------------------- ### Runtime Stage: Deploy Application Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/docker/listings/listing-5.txt Uses the official eXist-db image and copies the built XAR file from the builder stage into the eXist-db autodeploy directory. Exposes the default eXist-db ports and sets the command to start eXist-db. ```dockerfile FROM existdb/existdb:release COPY --from=builder /home/my-app/build/*.xar /exist/autodeploy EXPOSE 8080 8443 CMD [ "java", "org.exist.start.Main", "jetty" ] ``` -------------------------------- ### Travis CI Pre-script and Execution Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/integration-testing/listings/travis-4.txt Details the actions taken before the script runs, such as copying build artifacts into the Docker container, starting the container, and waiting for eXist-DB to initialize. It also includes the main testing commands. ```yaml before_script: - docker cp ./build/*-dev.xar exist-ci:exist/autodeploy - docker start exist-ci # exist needs time - sleep 30 - docker ps script: - ant test - npx cypress run ``` -------------------------------- ### Forwarding Requests from /libs/ Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/urlrewrite/listings/listing-12.txt Use this rule to forward requests starting with '/libs/' to a new URL, stripping the '/libs/' prefix. This is useful for mapping external URLs to internal resources. ```XQuery if (starts-with($exist:path, "/libs/")) then ``` -------------------------------- ### Create 'exist' group Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/production_good_practice/listings/listing-2.txt Creates a new system group named 'exist' for the eXist-db installation. This is a prerequisite for creating the dedicated user. ```bash $ pfexec groupadd exist ``` -------------------------------- ### Deploy XAR Package to eXist-DB Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/docker/listings/listing-4.txt This command downloads and adds a XAR (eXist Archive) package to the eXist-DB auto-deploy directory. The package will be deployed automatically when the eXist-DB service starts. ```dockerfile ADD https://github.com/eXist-db/documentation/releases/download/4.0.4/exist-documentation-4.0.4.xar /exist/autodeploy ``` -------------------------------- ### Check Java Version on eXist-DB Docker Instance Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/docker/listings/listing-1.txt Verify the Java Development Kit (JDK) version installed within the eXist-DB Docker container. This is useful for compatibility checks. ```bash docker exec exist java -version ``` -------------------------------- ### Perl Script for XML-RPC Query Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_xmlrpc/listings/listing-2.txt This Perl script demonstrates how to connect to eXist-db via XML-RPC, send a query, and process the response. Ensure the RPC::XML module is installed. ```perl #!/usr/bin/perl use RPC::XML; use RPC::XML::Client; $query = <<'END'; for $speech in //SPEECH[LINE &= 'tear*'] order by $speech/SPEAKER[1] return $speech END $URL = "http://guest:guest\@localhost:8080/exist/xmlrpc"; print "connecting to $URL...\n"; $client = new RPC::XML::Client $URL; # Output options $options = RPC::XML::struct->new( 'indent' => 'yes', 'encoding' => 'UTF-8', 'highlight-matches' => 'none'); $req = RPC::XML::request->new("query", $query, 20, 1, $options); $response = $client->send_request($req); if($response->is_fault) { die "An error occurred: " . $response->string . "\n"; } print $response->value; ``` -------------------------------- ### Scan Collections and Set Permissions Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/incompatibilities/listings/listing-1.txt Use `dbutil:scan-collections` to traverse collections starting from a specified path. A callback function can be used to apply specific permissions to each collection encountered. ```xquery xquery version "3.0"; import module namespace dbutil="http://exist-db.org/xquery/dbutil"; dbutil:scan-collections(xs:anyURI("/db"), function($collection) { sm:chmod($collection, "rwxr-xr-x") }) ``` -------------------------------- ### Build eXist-db Documentation Application Source: https://github.com/exist-db/documentation/blob/master/README.md Build the documentation application using Maven. This command cleans the project, packages it, and skips running tests. The compiled .xar file will be in the /target directory. ```bash cd documentation $ mvn clean package -DskipTests ``` -------------------------------- ### Import Module and Set Serialization Options in XQuery Source: https://context7.com/exist-db/documentation/llms.txt Demonstrates how to import a custom XQuery module from the database and configure output serialization to JSON with a specific media type. Includes options for query timeout and output size limits. ```xquery import module namespace my="http://example.org/my-module" at "xmldb:exist:///db/modules/my-module.xqm"; declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "json"; declare option output:media-type "application/json"; declare option exist:timeout "30000"; (: 30 seconds :) declare option exist:output-size-limit "50000"; (: max 50,000 nodes :) ``` -------------------------------- ### List Files and Directories Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/xquery/listings/listing-19.txt Use this snippet to list all files and subdirectories within the current directory. It distinguishes between files and directories, outputting their names and file sizes. ```XQuery declare namespace file="java:java.io.File"; { for $f in file:list-files( file:new(".") ) let $n := file:get-name($f) order by $n return if (file:is-directory($f)) then else } ``` -------------------------------- ### Get Mode in Java Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-86.txt Retrieves the current integer mode. Assumes the mode has been previously set. ```java public int getMode() { return currentMode; } ``` -------------------------------- ### Initialize Database Connection and GML Index Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-80.txt Sets HSQLDB properties, establishes a JDBC connection, and creates a GML index table if it does not exist. Ensure the necessary database driver is available and the data directory is accessible. ```Java private void initializeConnection() throws SQLException { System.setProperty("hsqldb.cache_scale", "11"); System.setProperty("hsqldb.cache_size_scale", "12"); System.setProperty("hsqldb.default_table_type", "cached"); //Get a connection to the DB... and keep it this.conn = DriverManager.getConnection("jdbc:hsqldb:" + getDataDir() + "/" + db_file_name_prefix, "sa", ""); try { ResultSet rs = this.conn.getMetaData().getTables(null, null, TABLE_NAME, new String[] { "TABLE" }); rs.last(); if (rs.getRow() == 1) { if (LOG.isDebugEnabled()) LOG.debug("Opened GML index: " + getDataDir() + "/" + db_file_name_prefix); //Create the data structure if it doesn't exist } else if (rs.getRow() == 0) { Statement stmt = conn.createStatement(); stmt.executeUpdate("CREATE TABLE " + TABLE_NAME + "(" + /*1*/ "DOCUMENT_URI VARCHAR, " + /*2*/ "NODE_ID_UNITS INTEGER, " + /*3*/ "NODE_ID BINARY, " + ... /*26*/ "IS_VALID BOOLEAN, " + //Enforce uniqueness "UNIQUE (" + "DOCUMENT_URI, NODE_ID_UNITS, NODE_ID" + ")" + ")" ); stmt.executeUpdate("CREATE INDEX DOCUMENT_URI ON " + TABLE_NAME + " (DOCUMENT_URI);"); ... stmt.close(); if (LOG.isDebugEnabled()) LOG.debug("Created GML index: " + getDataDir() + "/" + db_file_name_prefix); } else { throw new SQLException("2 tables with the same name ?"); } } finally { if (rs != null) rs.close(); } } ``` -------------------------------- ### Get Document in Java Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-86.txt Retrieves the current DocumentImpl object. Assumes the object has been previously set. ```java public DocumentImpl getDocument() { return currentDoc; } ``` -------------------------------- ### Get UserManagementService Instance Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_xmldb/listings/listing-9.txt Retrieve an instance of the UserManagementService from a collection. Ensure the service and version are correctly specified. ```java UserManagementService service = (UserManagementService)collection.getService("UserManagementService", "1.0"); ``` -------------------------------- ### Initialize and Register eXist-DB Database Instances Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_xmldb/listings/listing-10.txt Use this code to initialize and register multiple eXist-DB database instances with different configurations. Ensure the driver class is correctly specified and properties like 'create-database', 'configuration', and 'database-id' are set appropriately for each instance. ```Java String driver = "org.exist.xmldb.DatabaseImpl"; Class cl = Class.forName(driver); Database database1 = (Database)cl.newInstance(); database1.setProperty("create-database", "true"); database1.setProperty("configuration", "/home/exist/test/conf.xml"); database1.setProperty("database-id", "test"); DatabaseManager.registerDatabase(database1); Database database2 = (Database)cl.newInstance(); database2.setProperty("create-database", "true"); database2.setProperty("configuration", "/home/exist/production/conf.xml"); database2.setProperty("database-id", "exist"); DatabaseManager.registerDatabase(database1); ``` -------------------------------- ### Generate Release Notes with Maven Source: https://github.com/exist-db/documentation/blob/master/RELEASE.md Generate site documentation, including release notes, by running the 'mvn site' command. This will create a 'github-report.html' file in the 'target/site' directory. ```bash $ mvn site ``` -------------------------------- ### Get Document History Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/versioning/listings/listing-3.txt Retrieves the revision history for a given XML document. Ensure the versioning module is imported. ```XQuery import module namespace v="http://exist-db.org/versioning"; v:history(doc("/db/shakespeare/plays/hamlet.xml")) ``` -------------------------------- ### Debug Logging Example Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_codereview/listings/listing-5.txt Use this pattern to log debug messages conditionally. Ensure the logger is configured for debug level. ```Java if (getLogger().isDebugEnabled() { getLogger().debug("Entering - method - argList"); getLogger().debug("Arg1 :"+ theArgValue1); getLogger().debug("Arg2 :"+ theArgValue2); } ``` -------------------------------- ### Get Log4j Logger Instance Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_log4j/listings/listing-19.txt Obtain a Log4j Logger instance by its name. This is typically done once per class or component. ```java import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; // ... private Logger logger = LogManager.getLogger("xx.method.server.httpgw"); ``` -------------------------------- ### Import XQuery Module Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/xquery/listings/listing-12.txt Use this syntax to import an XQuery module. Ensure the module URI and path are correct. ```xquery import module namespace status="http://exist-db.org/xquery/admin-interface/status" at "http://exist-db.org/modules/test.xqm"; ``` -------------------------------- ### Get StreamListener Instance Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-87.txt Retrieves the StreamListener instance. Returns null if the current document is null or if the mode is set to REMOVE_ALL_NODES. ```Java public StreamListener getListener() { if (currentDoc == null || currentMode == StreamListener.REMOVE_ALL_NODES) return null; return gmlStreamListener; } ``` -------------------------------- ### Manage Users, Groups, and Permissions with Security Manager Source: https://context7.com/exist-db/documentation/llms.txt Use the sm: module for creating accounts, changing passwords, creating groups, setting Unix permissions, changing ownership, and managing Access Control Entries (ACEs). ```xquery import module namespace sm = "http://exist-db.org/xquery/securitymanager"; (: === Create a user account === :) sm:create-account("alice", "s3cr3t!", "editors", ("editors", "users")) (: === Change a password === :) sm:passwd("alice", "newP@ssword!") (: === Create a group === :) sm:create-group("reviewers", "alice", "Review team") (: === Set Unix permissions (owner=rwx, group=r-x, world=---) === :) sm:chmod(xs:anyURI("/db/secure-docs"), "rwxr-x---") (: === Change ownership === :) sm:chown(xs:anyURI("/db/secure-docs/report.xml"), "alice") sm:chgrp(xs:anyURI("/db/secure-docs/report.xml"), "editors") (: === Add an ACL entry: deny bob read+write regardless of group membership === :) sm:add-ace( xs:anyURI("/db/secure-docs/report.xml"), true(), (: is user (not group) ACE :) "bob", false(), (: DENY :) "rw" ) (: === Add an ACL entry: allow reviewers to read === :) sm:add-ace( xs:anyURI("/db/secure-docs/report.xml"), false(), (: is group ACE :) "reviewers", true(), (: ALLOW :) "r" ) (: === Check current permissions === :) sm:get-permissions(xs:anyURI("/db/secure-docs/report.xml")) (: Returns: ... :) ``` -------------------------------- ### Forward Query Execution Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/urlrewrite/listings/listing-11.txt Forwards requests starting with '/eXide/execute' to XQueryServlet for query execution. Results are stored in an attribute and errors are reported. ```xquery if (starts-with($path, "/eXide/execute")) then let $query := request:get-parameter("qu", ()) let $startTime := util:system-time() return else if (starts-with($path, "/sandbox/results/")) then (: Retrieve an item from the query results stored in the HTTP session. The format of the URL will be /sandbox/results/X, where X is the number of the item in the result set :) ``` -------------------------------- ### Backup eXist-db using SSL Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/backup/listings/listing-12.txt Use this command to perform a backup of the eXist-db database over SSL. Ensure you provide valid credentials and the correct URI for your eXist-db instance. ```bash bin/backup.sh -u admin -p admin-pass --use-ssl -ouri=xmldb:exist://example.org:443/exist/xmlrpc -b /db ``` -------------------------------- ### Backup eXist-DB with Script Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/backup/listings/listing-10.txt Use this script to perform a backup of your eXist-DB instance. Ensure you provide valid user credentials and a path for the backup file. ```bash bin/backup.sh -u admin -p admin-pass -P backup-pass -r /var/backup/hd060501/db/__contents__.xml ``` -------------------------------- ### Get a single book by ID Source: https://context7.com/exist-db/documentation/llms.txt This endpoint retrieves a specific book by its ID. If the book is not found, it returns a 404 Not Found response. ```APIDOC ## GET /api/books/{id} ### Description Retrieves a single book by its ID. Returns a 404 status if the book is not found. ### Method GET ### Endpoint /api/books/{id} ### Parameters #### Path Parameters - **id** (xs:string) - Required - The unique identifier of the book to retrieve. ### Response #### Success Response (200) - **map** - A JSON object representing the book, containing id, title, and author. #### Error Response (404) - **rest:response** - Contains an http:response element with status 404 and message "Not Found". ### Response Example ```json { "id": "1", "title": "The Hitchhiker's Guide to the Galaxy", "author": "Douglas Adams" } ``` ``` -------------------------------- ### Get Request Parameters in XQuery Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/templating/listings/listing-1.txt Use `request:get-parameter` to retrieve values for specified parameters. Provide a default value if the parameter is not present. ```XQuery let $query := request:get-parameter("query", ()) let $field := request:get-parameter("field", ()) ``` -------------------------------- ### Clone eXist-db Documentation Repository Source: https://github.com/exist-db/documentation/blob/master/README.md Clone the official eXist-db documentation repository to your local system using Git. ```bash $ git clone https://github.com/eXist-db/documentation.git ``` -------------------------------- ### Get or Create IndexWorker Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-77.txt Retrieves an existing GMLHSQLIndexWorker for a DBBroker or creates a new one if it doesn't exist. The worker is then stored for future use. ```java public IndexWorker getWorker(DBBroker broker) { GMLHSQLIndexWorker worker = (GMLHSQLIndexWorker)workers.get(broker); if (worker == null) { worker = new GMLHSQLIndexWorker(this, broker); workers.put(broker, worker); } return worker; } ``` -------------------------------- ### XQuery Module and Function Definition Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/xqsuite/listings/minimal-example.txt Defines an XQuery module with a namespace and a test function. Use this for basic XQuery module setup and testing. ```xquery xquery version "3.1"; module namespace t="http://exist-db.org/xquery/test/xqsuite"; declare namespace test="http://exist-db.org/xquery/xqsuite"; declare %test:assertTrue function t:test-type() as xs:boolean? { t:assert-is-foo(()) }; (: will only return true :) declare function t:assert-is-foo($actual as item()*) as xs:boolean? { $actual eq "foo" or test:fail("Is not foo", $actual, "foo") }; ``` -------------------------------- ### Create and Perform Maven Release Source: https://github.com/exist-db/documentation/blob/master/RELEASE.md Execute the Maven release process by first preparing the release and then performing it. Ensure the version number mirrors the major version of the current eXist-db release. ```bash $ mvn release:prepare $ mvn release:perform ``` -------------------------------- ### Get Boundary of a Geometry Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-119.txt Calculates the boundary of a given geometry. It first attempts to retrieve the geometry from an index and falls back to building it from the node if necessary. ```Java if (args[0].isEmpty()) result = Sequence.EMPTY_SEQUENCE; else { NodeValue geometryNode = (NodeValue) args[0].itemAt(0); //Try to get the geometry from the index if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) { targetSRS = indexWorker.getGeometricPropertyForNode(context.getBroker(), (NodeProxy)geometryNode, "SRS_NAME").getStringValue(); geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy)geometryNode, false); hasUsedIndex = true; } //Otherwise, build it if (geometry == null) { targetSRS = ((Element)geometryNode.getNode()).getAttribute("srsName").trim(); geometry = indexWorker.streamNodeToGeometry(context, geometryNode); } if (geometry == null) throw new XPathException("Unable to get a geometry from the node"); geometry = geometry.getBoundary(); ``` -------------------------------- ### Get Reindex Root Node in Java Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-89.txt This method identifies the highest ancestor node that has a GML namespace. It is used in reindexing operations where namespace awareness is required. ```java public StoredNode getReindexRoot(StoredNode node, NodePath path, boolean includeSelf) { if (!isDocumentGMLAware) //Not concerned return null; StoredNode topMost = node; StoredNode currentNode = node; for (int i = path.length() ; i > 0; i--) { currentNode = (StoredNode)currentNode.getParentNode(); if (GML_NS.equals(currentNode.getNamespaceURI())) topMost = currentNode; } return topMost; } ``` -------------------------------- ### Update exist.version in pom.xml Source: https://github.com/exist-db/documentation/blob/master/RELEASE.md Set the 'exist.version' property in your pom.xml file to the desired version. This ensures users of older eXist releases do not install the wrong documentation locally. ```xml 4.1.0 ``` -------------------------------- ### Constructor for AbstractGMLJDBCIndex Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-73.txt Initializes a new instance of the AbstractGMLJDBCIndex class. ```java public AbstractGMLJDBCIndex() { } ``` -------------------------------- ### List GPG Keys Source: https://github.com/exist-db/documentation/blob/master/RELEASE.md Use this command to check your available GPG keys, which are required by Maven for publishing releases. ```bash gpg --list-keys ``` -------------------------------- ### Perform Full-Text Search with XQuery and Lucene Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/lucene/listings/listing-38.txt Use the `ft:query()` function to execute a Lucene-based full-text search. This example searches for documents containing both 'nation' and 'miserable'. ```XQuery let $query := nationmiserable return //SPEECH[ft:query(., $query)] ``` -------------------------------- ### Serialize XML with eXist-specific Options Source: https://context7.com/exist-db/documentation/llms.txt Demonstrates using fn:serialize with a map of options, including eXist-specific ones like 'exist:highlight-matches' and 'exist:expand-xincludes'. ```xquery fn:serialize( , map { "method": "xml", "indent": true(), "exist:highlight-matches": "both", "exist:expand-xincludes": false() } ) ``` -------------------------------- ### Render XSL-FO to PDF using XQuery Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/fo-render/listings/listing-16.txt This snippet demonstrates how to render an XSL-FO document to PDF. It requires the 'xslfo' and 'file' modules. Ensure the XSL-FO document exists at '/db/test-fo.xml' and the configuration file at 'eXist-db-home/renderx/xep.xml'. ```xquery xquery version "3.0"; declare namespace file = "http://exist-db.org/xquery/file"; declare namespace system = "http://exist-db.org/xquery/system"; declare namespace xslfo = "http://exist-db.org/xquery/xslfo"; let $config := fn:parse-xml(file:read(system:get-exist-home() || "/renderx/xep.xml")) return let $fo := fn:doc('/db/test-fo.xml') let $pdf := xslfo:render($fo, "application/pdf", (), $config) return file:serialize-binary($pdf, "/tmp/fop.pdf") ``` -------------------------------- ### Dockerfile for eXist-DB Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/docker/listings/listing-3.txt Defines the steps to build a Docker image for eXist-DB. It specifies the base image and copies application resources to the deployment directory. ```dockerfile FROM existdb/existdb:5.0.0 COPY build/*.xar /exist/autodeploy ``` -------------------------------- ### Create 'exist' user Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/production_good_practice/listings/listing-2.txt Creates a new system user named 'exist' with a descriptive comment, home directory, and assigns it to the 'exist' group. This user will own the eXist-db processes. ```bash $ pfexec useradd -c "eXist Native XML Database" -d /home/exist -g exist -m exist ``` -------------------------------- ### Find Resources by MIME Type and Set Permissions Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/incompatibilities/listings/listing-1.txt Use `dbutil:find-by-mimetype` to locate resources with a specific MIME type within a given path. A callback function can be provided to modify permissions for each found resource. ```xquery xquery version "3.0"; import module namespace dbutil="http://exist-db.org/xquery/dbutil"; dbutil:find-by-mimetype(xs:anyURI("/db"), "application/xquery", function($resource) { sm:chmod($resource, "rwxr-xr-x") }) ``` -------------------------------- ### Register eXist-db Database Instance Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/deployment/listings/listing-24.txt Use this Java code to dynamically load and register an eXist-db database instance. Ensure the 'create-database' property is set to 'true' if you need to create a new database. ```java Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); Database database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); ``` -------------------------------- ### XQuery Full-Text Search with ft:query Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/lucene/listings/listing-47.txt Use the ft:query function to perform full-text searches on XML content. This example demonstrates a proximity search for 'bubble' and 'fillet'. ```XQuery let $query := bubblefillet return //SPEECH[ft:query(., $query)] ``` -------------------------------- ### Apache VirtualHost for Web Proxying Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/production_web_proxying/listings/listing-2.txt Configure Apache's VirtualHost to proxy requests to an eXist-DB application. This setup handles domain mapping and reverse proxying for seamless integration. ```apache ProxyRequests off ServerName www.mywebsite.com ServerAlias *.mywebsite.com ProxyPass / http://localhost:8088/exist/apps/mywebsite.com ProxyPassReverse / http://localhost:8088/exist/apps/mywebsite.com ProxyPassReverseCookieDomain localhost mywebsite.com ProxyPassReverseCookiePath /exist / RewriteEngine on RewriteRule ^/(.*)$ /$1 [PT] ``` -------------------------------- ### Initialize and Configure Server Logger Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_log4j/listings/listing-3.txt Instantiates a logger for server-side messages and sets its level to ALL if VERBOSE_SERVER is true. Ensure VERBOSE_SERVER declaration and static block are placed before this code. ```java import org.apache.log4j.Level; import org.apache.log4j.Logger; // place VERBOSE_SERVER declaration and static block from above here private static final Logger serverLogger = Logger.getLogger( "xx.method.server" ); static { if ( VERBOSE_SERVER ) serverLogger.setLevel( Level.ALL ); } ``` -------------------------------- ### Constructing a Full-Text Query Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/lucene/listings/listing-39.txt Define a full-text query expression using a combination of exact terms and wildcards. This query targets documents containing the term 'nation' and words starting with 'miser'. ```XQuery let $query := nationmiser* return //SPEECH[ft:query(., $query)] ``` -------------------------------- ### Clean and Repair eXist-DB Repository Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/backup/listings/listing-11.txt Imports the repair module and executes functions to clean and repair the repository. Ensure the module is correctly imported before use. ```xquery xquery version "3.0"; import module namespace repair="http://exist-db.org/xquery/repo/repair" at "resource:org/exist/xquery/modules/expathrepo/repair.xql"; repair:clean-all(), repair:repair() ``` -------------------------------- ### Full-Text Search with Facet Options Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/lucene/listings/listing-571.txt Use ft:query with a map of options to enable indexing and facet generation for specific fields. This example configures facets for 'keyword' and 'date' fields. ```xquery let $options := map { "facets": map { "keyword": ("indexing", "facets"), "date": [("2018", "06"), ("2018", "05")] } } return collection("/db/articles")//db:article[ft:query(., "xml", $options)] ``` -------------------------------- ### Configure AbstractGMLJDBCIndex Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-73.txt Configures the index with a broker pool, data directory, and configuration element. Handles potential ClassNotFoundException or SQLException during database checks. ```java public void configure(BrokerPool pool, String dataDir, Element config) throws DatabaseConfigurationException { super.configure(pool, dataDir, config); try { checkDatabase(); } catch (ClassNotFoundException e) { throw new DatabaseConfigurationException(e.getMessage()); } catch (SQLException e) { throw new DatabaseConfigurationException(e.getMessage()); } } ``` -------------------------------- ### Get Geometry and SRS from Node Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-119.txt Retrieves geometry and its SRS name from a node, prioritizing indexed data. If indexed data is unavailable, it builds the geometry from the node's attributes and content. ```Java if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) { targetSRS = indexWorker.getGeometricPropertyForNode(context.getBroker(), (NodeProxy)geometryNode, "SRS_NAME").getStringValue(); geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy)geometryNode, false); hasUsedIndex = true; } //Otherwise, build it if (geometry == null) { targetSRS = ((Element)geometryNode.getNode()).getAttribute("srsName").trim(); geometry = indexWorker.streamNodeToGeometry(context, geometryNode); } if (geometry == null) throw new XPathException("Unable to get a geometry from the node"); geometry = geometry.convexHull(); ``` -------------------------------- ### Maven Dry-Run Release Prepare Source: https://github.com/exist-db/documentation/blob/master/RELEASE.md Perform a dry-run of the release preparation process using Maven. This helps to identify potential issues without creating actual release files. ```bash $ mvn -DdryRun=true release:prepare ``` -------------------------------- ### Set eXist-db directory ownership Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/production_good_practice/listings/listing-2.txt Recursively changes the owner and group of the eXist-db installation directory to the 'exist' user and group. This ensures that the eXist-db processes have the necessary permissions to read and write to their own files. ```bash $ pfexec chown -R exist:exist /opt/eXist ``` -------------------------------- ### Execute XPath Query with Java on eXist-DB Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/docker/listings/listing-1.txt Use this command to execute an XPath query on a running eXist-DB instance via Docker. Ensure the 'exist' container is running and accessible. ```bash docker exec exist java org.exist.start.Main client --no-gui --xpath "system:get-version()" ``` -------------------------------- ### Login to eXist-DB Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/beginners-guide-to-xrx-v4/listings/listing-7.txt Use `xmldb:login` to establish a connection to a specific database path with provided credentials. Ensure the path and credentials are correct. ```xquery xmldb:login('/db/apps/terms/data', 'admin', 'myadminpassword') ``` -------------------------------- ### eXist-DB Dispatch Configuration for Listings Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/urlrewrite/listings/listing-1.txt Defines how eXist-DB dispatches requests for listing resources. It forwards requests to a transformation module, passing the resource name as a parameter. ```xml xquery version "3.1"; declare namespace exist="http://exist.sourceforge.net/NS/exist"; declare variable $exist:path external; declare variable $exist:resource external; declare variable $exist:controller external; declare variable $exist:prefix external; declare variable $exist:root external; ``` -------------------------------- ### Retrieve a Document or Execute a Query Source: https://context7.com/exist-db/documentation/llms.txt The REST interface allows for retrieving documents by their path or executing XQuery queries on the fly using GET parameters. It supports caching query results and managing server sessions. ```APIDOC ## GET /exist/rest/ ### Description Retrieve a stored XML document or execute an inline XQuery via GET parameters. Supports caching and session management. ### Method GET ### Endpoint `http://localhost:8080/exist/rest/db/[path/to/document]` ### Parameters #### Query Parameters - **_query** (string) - Optional - The XQuery expression to execute. - **_start** (integer) - Optional - The starting position for query results. - **_howmany** (integer) - Optional - The number of results to return. - **_indent** (boolean) - Optional - Whether to indent the XML output. - **_wrap** (boolean) - Optional - Whether to wrap results in ``. - **_cache** (boolean) - Optional - Whether to cache query results. - **_session** (integer) - Optional - The session ID to use for cached queries. - **_release** (integer) - Optional - The session ID to release. ### Request Example ```bash # Retrieve a stored XML document curl -u admin:secret http://localhost:8080/exist/rest/db/shakespeare/plays/hamlet.xml # Execute an inline XQuery via GET parameters curl -u admin:secret \ "http://localhost:8080/exist/rest/db/shakespeare?_query=//SPEECH[SPEAKER=%22JULIET%22]&_start=3&_howmany=5&_indent=yes&_wrap=yes" ``` ### Response #### Success Response (200) - **XML Document** or **``** containing query results. #### Response Example ```xml ... ... ``` ``` -------------------------------- ### Inspect Module Functions with XQSuite Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/xqsuite/listings/listing-7.txt Use this snippet to test and inspect all functions exported by a given XQuery module using the XQSuite framework. Ensure the 'xqsuite.xql' module is imported. ```xquery xquery version "3.0"; import module namespace test="http://exist-db.org/xquery/xqsuite" at "resource:org/exist/xquery/lib/xqsuite/xqsuite.xql"; test:suite( inspect:module-functions(xs:anyURI("math.xql")) ) ``` -------------------------------- ### Implement a Custom eXist-db Java Job Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/scheduler/listings/listing-2.txt Extend the UserJavaJob class to create a custom job. Implement the execute method to define the job's logic. This example shows a job that prints a message and increments a static counter. ```java package com.example; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.exist.storage.BrokerPool; public class MyJob extends UserJavaJob { private static final AtomicInteger COUNTER = new AtomicInteger(); private String jobName = "MyJob"; public void execute(final BrokerPool brokerpool, final Map params) throws JobException { System.out.println("****** My Job count=" + COUNTER.incrementAndGet()); } public String getName() { return jobName; } public void setName(final String name) { this.jobName = name; } } ``` -------------------------------- ### Build Authenticated URL in Java Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_codereview/listings/listing-3.txt Use this method to construct an authenticated URL for system actions. Ensure all required parameters are correctly formatted, especially the WfProcess Oid. ```java public static String buildAuthURL ( String action, String cls, WfProcess wfprocess, String rolevalue, String nextAction ) throws Exception { ReferenceFactory rf = new ReferenceFactory(); Properties urlProperties = new Properties(); urlProperties.put( "action", action ); urlProperties.put( "class", cls ); urlProperties.put( "wfprocess", rf.getReferenceString( wfprocess ) ); // WfProcess Oid urlProperties.put( "role", rolevalue ); urlProperties.put( "nextAction", nextAction ); //urlProperties.put("Users", getRoleMapUsers(wfprocess, rolevalue)); String url = GatewayURL.buildAuthenticatedURL( "XX.enterprise.URLProcessor", "generateForm", urlProperties ).toExternalForm(); url = url.substring( ( XXProperties.getLocalProperties().getProperty( "XX.server.codebase" ) ).length() - 10 ); return url; } ``` -------------------------------- ### Process Deferred Element Attributes and SRS Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/devguide_indexes/listings/listing-114.txt This Java code collects attributes from a deferred XML element, pushes SRS names onto a stack, and starts the element using a SAX handler. It handles potential exceptions during the SAX event. ```java private void processDeferredElement() { //We need to collect the deferred element's attributes in order to feed the SAX handler AttributesImpl attList = new AttributesImpl(); NamedNodeMap attrs = deferredElement.getAttributes(); String whatToPush = null; for (int i = 0; i < attrs.getLength() ; i++) { AttrImpl attrib = (AttrImpl)attrs.item(i); //Store the srs if (GML_NS.equals(deferredElement.getNamespaceURI())) { //Maybe we could assume a configurable default value here if (attrib.getName().equals("srsName")) { whatToPush = attrib.getValue(); } srsNamesStack.push(whatToPush); } attList.addAttribute(attrib.getNamespaceURI(), attrib.getLocalName(), attrib.getQName().getStringValue(), Integer.toString(attrib.getType()), attrib.getValue()); } srsNamesStack.push(whatToPush); try { geometryDocument.startElement(deferredElement.getNamespaceURI(), deferredElement.getLocalName(), deferredElement.getQName().getStringValue(), attList); } catch (Exception e) { e.printStackTrace(); LOG.error(e); } finally { deferredElement = null; } } ``` -------------------------------- ### Render XSL-FO to PDF and Store Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/fo-render/listings/listing-4.txt This snippet demonstrates how to render an XSL-FO document to PDF and store it in the database. Ensure the XSL-FO document is correctly formatted and accessible. ```xquery xquery version "1.0"; declare namespace file = "http://exist-db.org/xquery/file"; declare namespace xmldb = "http://exist-db.org/xquery/xmldb"; declare namespace xslfo = "http://exist-db.org/xquery/xslfo"; let $fo := fn:doc('/db/test-fo.xml') let $pdf := xslfo:render($fo, "application/pdf", (), ()) return xmldb:store("/db", "result.pdf", $pdf, "application/pdf") ``` -------------------------------- ### XQuery Full-Text Search Example Source: https://github.com/exist-db/documentation/blob/master/src/main/xar-resources/data/tuning/listings/listing-25.txt This XQuery snippet demonstrates how to search for a specific term ('king') within SPEECH elements using the ft:query function. It then retrieves distinct speaker names and their corresponding speeches, ordered by speaker name. ```XQuery xquery version "3.0"; let $query := "king" let $speeches := //SPEECH[ft:query(., $query)] for $speaker in distinct-values($speeches/SPEAKER) let $speechBySpeaker := $speeches[SPEAKER = $speaker] order by $speaker return { $speechBySpeaker } ```