### Start Oak Server (Custom Host and Fixture) Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-run/README.md Starts an Oak server with a specified URI and repository fixture. This example uses the Tar backend. ```bash java -jar oak-run-*.jar server http://localhost:4503 Oak-Segment-Tar --base myOak ``` -------------------------------- ### Complex Access Control Setup Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/authorization/bestpractices.md Illustrates a content design that leads to complex access control setup and potential vulnerabilities. This example highlights issues with mixed content types and broad ACL definitions. ```bash # Content design that results in complex in ac-setup and a vulnerability # ---------------------------------------------------------------------- create path /content create path /content/public create path /content/content2/also_public # extra folder with public information create path /content/sensitive_info # sensitive data mixed with regular non-sentive content set ACL on /content deny everyone jcr:all # most likely redundant allow readers jcr:read allow editors jcr:read, jcr:write deny readers jcr:read restriction(rep:subtrees, /sensitive_info) # what about editors or a subject being both reader and editor? allow everyone jcr:read restriction(rep:subtrees, /public, /also_public) # different public folders?? # ... and what happens with a new node /content/public/abc/sensitive_info? end ``` -------------------------------- ### Example Non-OSGi Security Setup Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/user/authorizableaction.md Demonstrates how to configure and build a repository with a custom AuthorizableActionProvider without using OSGi. ```java Map userParams = new HashMap(); userParams.put(UserConstants.PARAM_AUTHORIZABLE_ACTION_PROVIDER, new MyAuthorizableActionProvider()); ConfigurationParameters config = ConfigurationParameters.of(Map.of(UserConfiguration.NAME, ConfigurationParameters.of(userParams))); SecurityProvider securityProvider = SecurityProviderBuilder.newBuilder().with(config).build(); Repository repo = new Jcr(new Oak()).with(securityProvider).createRepository(); ``` -------------------------------- ### Custom SecurityProvider Implementation Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/introduction.md Example of how to deploy a custom SecurityProvider service in a non-OSGi setup. ```java SecurityProvider sp = new MySecurityProvider(); Repository repository = new Jcr().with(sp).createRepository(); ``` -------------------------------- ### Example Ordered Index Configuration Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/ordered-index-migrate.md This is an example of an existing ordered index configuration. ```json { "declaringNodeTypes" : "nt:unstructured", "direction" : "ascending", "propertyNames" : "foobar", "type" : "ordered" } ``` -------------------------------- ### Start Oak Server (Default) Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-run/README.md Starts an in-memory Oak repository and makes it available at http://localhost:8080/. ```bash java -jar oak-run-*.jar server ``` -------------------------------- ### Query Plan Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/query-troubleshooting.md An example query plan showing a full traversal of nodes under '/etc'. ```sql [nt:base] as [nt:base] /* traverse "/etc//*" where (isdescendantnode([nt:base], [/etc])) and (lower([nt:base].[jcr:title]) like '%coat%') */ ``` -------------------------------- ### Setup Local MongoDB Replica Set Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/setup.txt Instructions to set up a local MongoDB replica set with two replicas and one arbiter. This involves starting multiple mongod instances with the --replSet option and then initiating the replica set configuration. ```shell cd killall mongod rm -rf db1; mkdir db1 rm -rf db2; mkdir db2 rm -rf db3; mkdir db3 ./mongod --replSet test --dbpath db1 --port 27017 > db1/log.txt & ./mongod --replSet test --dbpath db2 --port 27018 > db2/log.txt & ./mongod --replSet test --dbpath db3 --port 27019 > db3/log.txt & while ! nc -vz localhost 27017; do sleep 1; done while ! nc -vz localhost 27018; do sleep 1; done while ! nc -vz localhost 27019; do sleep 1; done ``` ```shell ./mongo --eval "rs.initiate({_id:'test', members:[ {_id:0, host:'localhost:27017'}, {_id:1, host:'localhost:27018'}, {_id:2, host:'localhost:27019', arbiterOnly:true}, ]});" ``` -------------------------------- ### Simple MongoDB Setup Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/setup.txt A minimal setup for running a single MongoDB instance on port 27017. This is useful for development or testing without sharding. ```shell rm -rf db mkdir db ./mongod --dbpath db --port 27017 ``` -------------------------------- ### Non-OSGi Setup for RestrictionProvider Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/authorization/restriction.md Example of how to set up a custom RestrictionProvider in a non-OSGi environment using SecurityProviderBuilder. ```java RestrictionProvider rProvider = CompositeRestrictionProvider.newInstance(new MyRestrictionProvider(), ...); Map authorizMap = Map.of(PARAM_RESTRICTION_PROVIDER, rProvider); ConfigurationParameters config = ConfigurationParameters.of(Map.of(AuthorizationConfiguration.NAME, ConfigurationParameters.of(authorizMap))); SecurityProvider securityProvider = SecurityProviderBuilder.newBuilder().with(config).build(); Repository repo = new Jcr(new Oak()).with(securityProvider).createRepository(); ``` -------------------------------- ### S3DataStore Configuration Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-run/README.md Example configuration for S3DataStore using OSGi configuration admin format. Ensure to replace placeholders with your actual credentials and bucket information. ```bash cat > org.apache.jackrabbit.oak.plugins.S3DataStore.config << EOF accessKey="XXXXXXXXX" secretKey="YYYYYY" s3Bucket="bucket1" s3Region="region1" EOF ``` -------------------------------- ### Concurrency Levels Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-benchmarks/README.md Demonstrates specifying multiple concurrency levels for a benchmark test. The tests will run sequentially for each specified level after suite setup and before suite teardown. ```bash --concurrency 1,4,8 ``` -------------------------------- ### FileDataStore Configuration Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-run/README.md Example configuration for FileDataStore using OSGi configuration admin format. The 'path' property is mandatory and specifies the directory for the data store. ```bash cat > org.apache.jackrabbit.oak.plugins.FileDataStore.config << EOF path="/data/datastore" EOF ``` -------------------------------- ### Run PostgreSQL Docker Container Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/testing.md Starts a PostgreSQL Docker container for testing. Ensure Docker is installed and running. ```bash docker run -p 8080:5432 --name oak-postgres -e POSTGRES_PASSWORD=geheim -e POSTGRES_DB=oak -d postgres:13-alpine ``` -------------------------------- ### Index Node Name Query Examples Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/lucene.md Demonstrates example queries that benefit from enabling 'indexNodeName' for faster evaluation of constraints on node names. ```sql select [jcr:path] from [nt:base] where NAME() = 'kite' select [jcr:path] from [nt:base] where NAME() LIKE 'kite%' /jcr:root//kite /jcr:root//*[jcr:like(fn:name(), 'kite%')] /jcr:root//element(*, app:Asset)[fn:name() = 'kite'] /jcr:root//element(kite, app:Asset) ``` -------------------------------- ### JVM Profiling Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-benchmarks/README.md Example of using JVM options for profiling, specifically with hprof, to analyze benchmark execution time distribution. Includes a command to process the profiling results. ```bash -agentlib:hprof=cpu=samples,depth=100 perl analyze-hprof.pl java.hprof.txt ``` -------------------------------- ### Example Configuration String Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/persistent-cache.md An example of a persistent cache configuration string, specifying the cache directory, maximum file size, and disabling compaction and compression. ```text "cache,size\=2048,-compact,-compress" ``` -------------------------------- ### Start Oak Server (MongoDB Fixture) Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-run/README.md Starts an Oak server with a MongoDB backend, specifying the database name and cluster IDs. ```bash java -jar oak-run-*.jar server http://localhost:4502 Oak-Mongo --db myOak --clusterIds c1,c2,c3 ``` -------------------------------- ### N-Shortest Paths by Weight Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-lucene/src/main/java/org/apache/lucene/util/fst/package.html Shows how to find the N-shortest paths in an FST based on a provided comparator for the output weights. This example finds the 2 shortest paths. ```java Comparator comparator = new Comparator() { public int compare(Long left, Long right) { return left.compareTo(right); } }; Arc firstArc = fst.getFirstArc(new Arc()); MinResult paths[] = Util.shortestPaths(fst, firstArc, comparator, 2); System.out.println(Util.toBytesRef(paths[0].input, scratchBytes).utf8ToString()); // cat System.out.println(paths[0].output); // 5 System.out.println(Util.toBytesRef(paths[1].input, scratchBytes).utf8ToString()); // dog System.out.println(paths[1].output); // 7 ``` -------------------------------- ### Starting Oak Console for DocumentMK/Mongo Repository Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-run/README.md Start the interactive console for a DocumentMK or MongoMK repository using its connection string. ```bash $ java -jar oak-run-*.jar console mongodb://host ``` -------------------------------- ### MySQL RDBDocumentStore Startup Log Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/document/rdb-document-store.md An example INFO level log message from RDBDocumentStore upon startup with a MySQL database, detailing connection parameters, character set, collation, and table schema. ```log 13:40:46.637 INFO [main] RDBDocumentStore.java:1065 RDBDocumentStore (SNAPSHOT) instantiated for database MySQL 8.0.15 (8.0), using driver: MySQL Connector/J mysql-connector-java-8.0.15 (Revision: 79a4336f140499bd22dd07f02b708e163844e3d5) (8.0), connecting to: jdbc:mysql://localhost:3306/oak?serverTimezone=UTC, properties: {character_set_database=utf8mb4, character_set_client=utf8mb4, character_set_connection=utf8mb4, character_set_results=, max_allowed_packet=8388608, collation_database=utf8mb4_unicode_ci, character_set_system=utf8, collation_server=utf8mb4_0900_ai_ci, collation=utf8mb4_unicode_ci, character_set_filesystem=binary, character_set_server=utf8mb4, collation_connection=utf8mb4_0900_ai_ci}, transaction isolation level: TRANSACTION_REPEATABLE_READ (4), .nodes: ID VARBINARY(512), MODIFIED BIGINT(20), HASBINARY SMALLINT(6), DELETEDONCE SMALLINT(6), MODCOUNT BIGINT(20), CMODCOUNT BIGINT(20), DSIZE BIGINT(20), VERSION SMALLINT(6), SDTYPE SMALLINT(6), SDMAXREVTIME BIGINT(20), DATA VARCHAR(16000), BDATA LONGBLOB(2147483647) /* {BIGINT=-5, LONGBLOB=-4, SMALLINT=5, VARBINARY=-3, VARCHAR=12} */ /* unique index oak.PRIMARY on nodes (ID ASC) other (#0, p0), index oak.NODES_MOD on nodes (MODIFIED ASC) other (#0, p0), index oak.NODES_SDM on nodes (SDMAXREVTIME ASC) other (#0, p0), index oak.NODES_SDT on nodes (SDTYPE ASC) other (#0, p0), index oak.NODES_VSN on nodes (VERSION ASC) other (#0, p0) */ ``` -------------------------------- ### DB2 RDBDocumentStore Startup Log Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/document/rdb-document-store.md An example INFO level log message from RDBDocumentStore upon startup with a DB2 database, showing connection details and table schema. ```log 14:47:20.332 INFO [main] RDBDocumentStore.java:1065 RDBDocumentStore (SNAPSHOT) instantiated for database DB2/NT64 SQL11014 (11.1), using driver: IBM Data Server Driver for JDBC and SQLJ 4.19.77 (4.19), connecting to: jdbc:db2://localhost:50276/OAK, properties: {DB2ADMIN.CODEPAGE=1208, DB2ADMIN.COLLATIONSCHEMA=SYSIBM, DB2ADMIN.COLLATIONNAME=IDENTITY}, transaction isolation level: TRANSACTION_READ_COMMITTED (2), DB2ADMIN.NODES: ID VARCHAR(512), MODIFIED BIGINT, HASBINARY SMALLINT, DELETEDONCE SMALLINT, MODCOUNT BIGINT, CMODCOUNT BIGINT, DSIZE BIGINT, VERSION SMALLINT, SDTYPE SMALLINT, SDMAXREVTIME BIGINT, DATA VARCHAR(16384), BDATA BLOB(1073741824) /* {BIGINT=-5, BLOB=2004, SMALLINT=5, VARCHAR=12} */ /* index DB2ADMIN.NODES_MOD on DB2ADMIN.NODES (MODIFIED ASC) other (#0, p0), unique index DB2ADMIN.NODES_PK on DB2ADMIN.NODES (ID ASC) clustered (#0, p0), index DB2ADMIN.NODES_SDM on DB2ADMIN.NODES (SDMAXREVTIME ASC) other (#0, p0), index DB2ADMIN.NODES_SDT on DB2ADMIN.NODES (SDTYPE ASC) other (#0, p0), index DB2ADMIN.NODES_VSN on DB2ADMIN.NODES (VERSION ASC) other (#0, p0) */ ``` -------------------------------- ### Initialize and Start MongoDB Sharded Cluster Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/setup.txt Commands to clean previous data, create directories, start mongod instances as shard servers and a config server, and then start the mongos router. Finally, it connects to mongos, adds shards, creates a database and collections, enables sharding, and shards the collections. ```shell rm -rf db mkdir db mkdir db/shard1 mkdir db/shard2 mkdir db/shard3 mkdir db/config ./mongod --shardsvr --port=10001 --dbpath db/shard1 --fork --logpath db/shard1.log ./mongod --shardsvr --port=10002 --dbpath db/shard2 --fork --logpath db/shard2.log ./mongod --shardsvr --port=10003 --dbpath db/shard3 --fork --logpath db/shard3.log ./mongod --configsvr --port 20001 --dbpath=db/config --fork --logpath db/config.log ./mongos --port 27017 --configdb localhost:20001 --fork --logpath db/mongos.log ``` ```shell ./mongo --host localhost --port 27017 sh.addShard("localhost:10001") sh.addShard("localhost:10002") sh.addShard("localhost:10003") use MongoMKDB db.createCollection("nodes") db.createCollection("blobs") sh.enableSharding("MongoMKDB") sh.shardCollection("MongoMKDB.nodes", { "_id": 1 }, true) sh.shardCollection("MongoMKDB.blobs", { "_id": 1 }, true) exit ``` -------------------------------- ### Example Custom TokenConfiguration Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/authentication/tokenmanagement.md An example Java class demonstrating how to implement a custom TokenConfiguration in an OSGi environment. This class extends ConfigurationBase and implements the TokenConfiguration interface, providing a custom TokenProvider. ```java @Component() @Service({TokenConfiguration.class, SecurityConfiguration.class}) public class MyTokenConfiguration extends ConfigurationBase implements TokenConfiguration { public TokenConfigurationImpl() { super(); } public TokenConfigurationImpl(SecurityProvider securityProvider) { super(securityProvider, securityProvider.getParameters(NAME)); } @Activate private void activate(Map properties) { setParameters(ConfigurationParameters.of(properties)); } //----------------------------------------------< SecurityConfiguration >--- @Nonnull @Override public String getName() { return NAME; } //-------------------------------------------------< TokenConfiguration >--- @Nonnull @Override public TokenProvider getTokenProvider(Root root) { return new MyTokenProvider(root, getParameters()); } } ``` -------------------------------- ### CacheBuilder Usage Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/specs/guava-cache-removal/PLAN.md Demonstrates the fluent API for creating Caffeine-backed caches. This example shows how to configure maximum weight, a custom weigher, a removal listener, and statistics recording. ```java /** * Fluent builder for Caffeine-backed {@link Cache} instances. * *

Usage: *

 * Cache<String, byte[]> cache = CacheBuilder.<String, byte[]>newBuilder()
 *     .maximumWeight(64 * 1024 * 1024)
 *     .weigher((k, v) -> v.length)
 *     .removalListener((k, v, cause) -> LOG.info("evicted {}", k))
 *     .recordStats()
 *     .build();
 * 
*/ public final class CacheBuilder { // --- Builder state --- private String module; private long maximumWeight = -1; private long maximumSize = -1; private int initialCapacity = -1; private Weigher weigher; private EvictionListener removalListener; private boolean recordStats; private Duration expireAfterAccess; private Duration expireAfterWrite; private Duration refreshAfterWrite; // Caffeine-only (loading caches) public static CacheBuilder newBuilder() { ... } public CacheBuilder maximumWeight(long maximumWeight) { ... } public CacheBuilder maximumSize(long maximumSize) { ... } public CacheBuilder initialCapacity(int initialCapacity) { ... } public CacheBuilder weigher(Weigher weigher) { ... } public CacheBuilder removalListener(EvictionListener listener) { ... } public CacheBuilder recordStats() { ... } public CacheBuilder expireAfterAccess(Duration duration) { ... } public CacheBuilder expireAfterWrite(Duration duration) { ... } public CacheBuilder refreshAfterWrite(Duration duration) { ... } public CacheBuilder ticker(Supplier ticker) { ... } public CacheBuilder ticker(Clock clock) { ... } /** * Build a non-loading cache. */ public Cache build() { ... } /** * Build a loading cache with the given loader. * The loader is key-aware and may throw a checked exception (see {@link CacheLoader}). */ public LoadingCache build(CacheLoader loader) { ... } } ``` -------------------------------- ### Example Configuration for MongoDocumentStore Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/osgi_config.md Configuration properties for using MongoDB as the document store. ```properties mongouri=mongodb://localhost:27017 db=oak ``` -------------------------------- ### Worked Example: Query Cost Estimation Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/cost-estimation.md An example demonstrating the calculation of estimated entries for a query with two indexed properties, 'a' and 'b', using the new selectivity model. ```plaintext selectivity_a = 0.10 (MCV hit) selectivity_b = 1/5 = 0.20 (weight fallback) combinedSelectivity = 0.10 × 0.20 = 0.02 selectivityCap = min(1000, 1000) = 1000 estimatedEntries = round(0.02 × 1000) = 20 ``` -------------------------------- ### Non-OSGi Setup for Principal-Based Authorization Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/authorization/principalbased.md Demonstrates how to configure and bind the PrincipalBasedAuthorizationConfiguration in a non-OSGi environment. This setup includes defining a FilterProvider and MountInfoProvider, and then binding them to the SecurityProvider and Oak repository. ```java // setup PrincipalBasedAuthorizationConfiguration FilterProvider filterProvider = TODO: define the filter provider; MountInfoProvider mip = Mounts.defaultMountInfoProvider(); PrincipalBasedAuthorizationConfiguration ac = new PrincipalBasedAuthorizationConfiguration(); ac.bindFilterProvider(filterProvider); ac.bindMountInfoProvider(mip); // optionally set configuration parameters: ranking, enable aggregationfilter // bind it to the security provider ConfigurationParameters securityConfig = ConfigurationParameters.EMPTY; // TODO define security config options SecurityProvider securityProvider = SecurityProviderBuilder.newBuilder().with(securityConfig) .withRootProvider(rootProvider) .withTreeProvider(treeProvider) .build(); SecurityProviderHelper.updateConfig(securityProvider, ac, AuthorizationConfiguration.class); // create the Oak repository (alternatively: create the JCR repository) Oak oak = new Oak() .with(new InitialContent()) // TODO: add all required editors .with(securityProvider); withEditors(oak); ContentRepository contentRepository = oak.createContentRepository(); ``` -------------------------------- ### Non-OSGi CUG Configuration Setup Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/authorization/cug.md Demonstrates how to configure and bind the CugConfiguration in a non-OSGi environment. Ensure the CUG configuration is added before the default configuration in the composite setup. ```java // setup CugConfiguration ConfigurationParameters params = ConfigurationParameters.of(AuthorizationConfiguration.NAME, ConfigurationParameters.of(ConfigurationParameters.of( CugConstants.PARAM_CUG_SUPPORTED_PATHS, "/content", CugConstants.PARAM_CUG_ENABLED, true))); CugConfiguration cug = new CugConfiguration(); cug.setParameters(params); // bind it to the security provider SecurityProvider securityProvider = SecurityProviderBuilder.newBuilder().with(configuration).build(); CompositeConfiguration composite = (CompositeConfiguration) securityProvider .getConfiguration(AuthorizationConfiguration.class); AuthorizationConfiguration defConfig = composite.getDefaultConfig(); cug.setSecurityProvider(securityProvider); cug.setRootProvider(((ConfigurationBase) defConfig).getRootProvider()); cug.setTreeProvider(((ConfigurationBase) defConfig).getTreeProvider()); composite.addConfiguration(cug); composite.addConfiguration(defConfig); // create the Oak repository (alternatively: create the JCR repository) Oak oak = new Oak() .with(new InitialContent()) // TODO: add all required editors .with(securityProvider); withEditors(oak); ContentRepository contentRepository = oak.createContentRepository(); ``` -------------------------------- ### Example AuthorizableActionProvider Implementation Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/user/authorizableaction.md An example OSGi component implementing the AuthorizableActionProvider interface. It defines properties for profile names and initializes the action provider with configuration. ```java @Component() @Service(AuthorizableActionProvider.class) public class MyAuthorizableActionProvider implements AuthorizableActionProvider { private static final String PUBLIC_PROFILE_NAME = "publicProfileName"; private static final String PRIVATE_PROFILE_NAME = "privateProfileName"; private static final String FRIENDS_PROFILE_NAME = "friendsProfileName"; @Property(name = PUBLIC_PROFILE_NAME, value = "publicProfile") private String publicName; @Property(name = PRIVATE_PROFILE_NAME, value = "privateProfile") private String privateName; @Property(name = FRIENDS_PROFILE_NAME, value = "friendsProfile") private String friendsName; private ConfigurationParameters config = ConfigurationParameters.EMPTY; public MyAuthorizableActionProvider() {} public MyAuthorizableActionProvider(ConfigurationParameters config) { this.config = config; } //-----------------------------------------< AuthorizableActionProvider >--- @Override public List getAuthorizableActions(SecurityProvider securityProvider) { AuthorizableAction action = new ProfileAction(publicName, privateName, friendsName); action.init(securityProvider, config); return Collections.singletonList(action); } //----------------------------------------------------< SCR Integration >--- @Activate private void activate(Map properties) { config = ConfigurationParameters.of(properties); } } ``` -------------------------------- ### Example Token Node Properties Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/authentication/token/default.md Shows a detailed example of a 'rep:Token' node, including its primary type, UUID, key, expiration date, and other optional or informal properties. ```json testUser { "jcr:primaryType": "rep:User", ... ".tokens" { "2014-04-10T16.09.07.159+02.00" { "jcr:primaryType": "rep:Token", "jcr:uuid": "30c1f361-35a2-421a-9ebc-c781eb8a08f0", "rep:token.key": "{SHA-256}afaf64dba5d862f9-1000-3e2d4e58ac16189b9f2ac95d8d5b692e61cb06db437bcd9be5c10bdf3792356a", "rep:token.exp": "2014-04-11T04:09:07.159+02:00", ".token.ip": "0:0:0:0:0:0:0:1%0" ".token.otherMandatoryProperty": "expectedValue", "referer": "http://localhost:4502/crx/explorer/login.jsp" "otherInformalProperty": "somevalue" }, "2014-05-07T12.08.57.683+02.00" { "jcr:primaryType": "rep:Token", "jcr:uuid": "c95c91e2-2e08-48ab-93db-6e7c8cdd6469", "rep:token.key": "{SHA-256}b1d268c55abda258-1000-62e4c368972260576d37e6ba14a10f9f02897e42992624890e22c522220f7e54", "rep:token.exp": "2014-05-08T00:08:57.683+02:00" }, ... } } } ``` -------------------------------- ### Example Root Node Structure Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/documentmk.md Illustrates the structure of a root node before any branch commits. ```json { "_deleted" : { "r13fcda88ac0-0-1" : "false", }, "_id" : "0:/", "_lastRev" : { "r0-0-1" : "r13fcda91720-0-1" }, "_modified" : NumberLong(1373544975), "_modCount" : NumberLong(2), "_revisions" : { "r13fcda88ac0-0-1" : "c", "r13fcda91720-0-1" : "c" }, "prop" : { "r13fcda91720-0-1" : "\"foo\"" } } ``` -------------------------------- ### Pre-Authentication Example with Subject Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/authentication/preauthentication.md Demonstrates how to create a `Subject` with principals and `AuthInfo`, then use it for pre-authenticated login via `Java23Compatibility.doAsPrivileged`. ```java String userId = "test"; /** * Retrive valid principals e.g. by using Jackrabbit or Oak API: * - PrincipalManager#getPrincipal and/or #getGroupMembership * - PrincipalProvider#getPrincipals(String userId) */ Set principals = getPrincipals(userId); AuthInfo authInfo = new AuthInfoImpl(userId, Collections.emptyMap(), principals); Subject subject = new Subject(true, principals, Collections.singleton(authInfo), Collections.emptySet()); Session session; try { session = Java23Compatibility.doAsPrivileged(subject, new PrivilegedExceptionAction() { @Override public Session run() throws Exception { return login(null, null); } }, null); } catch (PrivilegedActionException e) { throw new RepositoryException("failed to retrieve session.", e); } ``` -------------------------------- ### Explore Oak Repository with GUI Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-run/README.md Start a desktop GUI browser for read-only browsing of an Oak repository. Optionally skip the size check. ```bash java -jar oak-run-*.jar explore /path/to/oak/repository [--skip-size-check] ``` -------------------------------- ### TarMK GC Sequence Number Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/segment/overview.md All log messages generated during the garbage collection process include a sequence number indicating how many times garbage collection ran since the system started. This example shows the format. ```log TarMK GC #2: ... ``` -------------------------------- ### Run DB2 Docker Container Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/testing.md Starts an IBM DB2 Docker container for testing. This image may require initial setup time. ```bash docker run -h db2server --name db2server --privileged=true -p 50000:50000 baedke/db2-community-oak:11.5.9.0 ``` -------------------------------- ### Custom SecurityProvider Implementation Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/introduction.md Example of a custom SecurityProvider implementing mandatory Authentication and Authorization configurations. This setup is minimal for a functional Oak repository. ```java public class MySecurityProvider implements SecurityProvider { [...] public T getConfiguration(Class configClass) { if (AuthenticationConfiguration.class == configClass) { return (T) new MyAuthentication(); } else if (AuthorizationConfiguration.class == configClass) { return (T) new MyAuthorization(); } else { throw new IllegalArgumentException(); } } private final class MyAuthentication extends SecurityConfiguration.Default implements AuthenticationConfiguration { [...] } private final class MyAuthorization extends SecurityConfiguration.Default implements AuthorizationConfiguration { public AccessControlManager getAccessControlManager(Root root, NamePathMapper namePathMapper) { throw new UnsupportedOperationException(); } public RestrictionProvider getRestrictionProvider() { throw new UnsupportedOperationException(); } public PermissionProvider getPermissionProvider(Root root, String workspaceName, Set principals) { return MyPermissionProvider.getInstance(principals); } } } ``` -------------------------------- ### Build SecurityProvider in Non-OSGi Setup Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/introduction.md Demonstrates how to build and integrate a SecurityProvider in a non-OSGi environment. Configuration parameters can be optionally provided to customize security modules. ```java NodeStore nodeStore = ... ConfigurationParameters params = ... // TODO: provide config options // Optional: set additional/custom implementations of the supported `SecurityConfiguration`s via the params SecurityProvider sp = SecurityProviderBuilder.newBuilder().with(params).build(); Repository repository = new Jcr(nodeStore).with(sp).createRepository(); ``` -------------------------------- ### Oak Impersonation using JCR API Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/authentication/differences.md This example shows how to perform impersonation using the standard JCR API in Oak. Note that building credentials depends on the authentication setup. ```java // Note: build credentials depends on the auth setup ! Credentials impersonationCredentials = new SimpleCredentials("someUserId, new char[0]); Session impersonated = session.impersonate(impersonationCredentials); ``` -------------------------------- ### Extend Default SecurityProvider with Custom PrincipalConfiguration Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/introduction.md This example demonstrates how to extend the default SecurityProvider with a custom PrincipalConfiguration in a non-OSGi setup. It involves building a SecurityProvider, configuring parameters, and adding the custom configuration. ```java MyPrincipalConfiguration pc = new MyPrincipalConfiguration(); ConfigurationParameters params = ConfigurationParameters.EMPTY; pc.setParameters(params); SecurityProvider securityProvider = SecurityProviderBuilder.newBuilder().with(params).build(); CompositeConfiguration composite = (CompositeConfiguration) securityProvider .getConfiguration(PrincipalConfiguration.class); PrincipalConfiguration defConfig = composite.getDefaultConfig(); pc.setSecurityProvider(securityProvider); pc.setRootProvider(((ConfigurationBase) defConfig).getRootProvider()); pc.setTreeProvider(((ConfigurationBase) defConfig).getTreeProvider()); composite.addConfiguration(pc); composite.addConfiguration(defConfig); Repository repo = new Jcr(new Oak()).with(securityProvider).createRepository(); ``` -------------------------------- ### Retrieval by Output Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-lucene/src/main/java/org/apache/lucene/util/fst/package.html Demonstrates retrieving the input key for a given output value. This functionality requires that the outputs themselves are also in sorted order. ```java // Only works because outputs are also in sorted order IntsRef key = Util.getByOutput(fst, 12); System.out.println(Util.toBytesRef(key, scratchBytes).utf8ToString()); // dogs ``` -------------------------------- ### Custom UUID AuthorizableNodeName Implementation (OSGi) Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/user/authorizablenodename.md An example of a custom AuthorizableNodeName implementation that uses a UUID for the authorizable node name. This is suitable for OSGi-based setups where making the service available to the repository is sufficient. ```java @Component @Service(value = {AuthorizableNodeName.class}) /** * Custom implementation of the {@code AuthorizableNodeName} interface * that uses a uuid as authorizable node name. */ final class UUIDNodeName implements AuthorizableNodeName { @Override @Nonnull public String generateNodeName(@Nonnull String authorizableId) { return UUID.randomUUID().toString(); } } ``` -------------------------------- ### Custom LoginModule Configuration in non-OSGi Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/authentication.md Example of configuring a custom LoginModule within a non-OSGi setup by programmatically creating a JAAS Configuration. This allows specifying the order and control flags for custom and default login modules. ```java import javax.security.auth.login.AppConfigurationEntry import javax.security.auth.login.Configuration AppConfigurationEntry[] entries = new AppConfigurationEntry[]{new DefaultEntry(options)}; Configuration c = new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String applicationName) { Map options = [....]; // choose control flag for custom login module (example here: REQUIRED) AppConfigurationEntry.LoginModuleControlFlag flag = LoginModuleControlFlag.SUFFICIENT // create an entry for your custom login module AppConfigurationEntry customEntry = new AppConfigurationEntry("your.org.LoginModuleClassName", flag, options) // additionally use the oak default login module AppConfigurationEntry defaultEntry = new AppConfigurationEntry(("org.apache.jackrabbit.oak.security.authentication.user.LoginModuleImpl", LoginModuleControlFlag.REQUIRED, options) // define array of all entries in the correct order according to your needs return new AppConfigurationEntry[]{customEntry, defaultEntry}; } }; Configuration.setConfiguration(c); ``` -------------------------------- ### RDBDocumentStore Successful Upgrade Log Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/document/rdb-document-store.md This log shows the RDBDocumentStore successfully upgrading the NODES table to DB level 1 and 2 by adding new columns and creating indexes. This occurs when starting up an older database instance with a newer Oak version. ```log 12:05:54.146 INFO [main] RDBDocumentStore.java:1369 Upgraded NODES to DB level 1 using 'alter table NODES add VERSION smallint' 12:05:54.166 INFO [main] RDBDocumentStore.java:1369 Upgraded NODES to DB level 2 using 'alter table NODES add SDMAXREVTIME bigint' 12:05:54.167 INFO [main] RDBDocumentStore.java:1369 Upgraded NODES to DB level 2 using 'create index NODES_VSN on NODES (VERSION)' 12:05:54.167 INFO [main] RDBDocumentStore.java:1369 Upgraded NODES to DB level 2 using 'create index NODES_SDT on NODES (SDTYPE)' 12:05:54.167 INFO [main] RDBDocumentStore.java:1369 Upgraded NODES to DB level 2 using 'create index NODES_SDM on NODES (SDMAXREVTIME)' ``` -------------------------------- ### Explain Query Syntax Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-core/src/test/resources/org/apache/jackrabbit/oak/query/explain_result.txt Demonstrates the syntax for explaining a query and its expected output format. Lines starting with 'explain' are followed by the expected query plan. ```text explain select [jcr:uuid] from [nt:base] [oak]explain select [jcr:uuid] from [nt:base] [oak]explain select [jcr:uuid] from [nt:base] ``` -------------------------------- ### Repository-Level Policy Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/security/accesscontrol/default.md An example of a repository-level access control policy defining permissions for a principal. ```json "": { "jcr:primaryType": "rep:root", "jcr:mixinTypes": "rep:RepoAccessControllable", "rep:repoPolicy": { "jcr:primaryType": "rep:ACL", "allow": { "jcr:primaryType": "rep:GrantACE", "rep:principalName": "elefant", "rep:privileges": ["rep:privilegeManagement"] } } } ``` -------------------------------- ### Initialize RDBDocumentNodeStore with DataSource Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/document/rdb-document-store.md Demonstrates how to create and build a DocumentNodeStore using an RDBDocumentNodeStoreBuilder and a DataSource. Remember to dispose of the store when done. ```java DataSource dataSource = RDBDataSourceFactory.forJdbcUrl(jdbcurl, user, pw); DocumentNodeStore store = RDBDocumentNodeStoreBuilder().newRDBDocumentNodeStoreBuilder() .setRDBConnection(dataSource).build(); // do something with the store NodeState root = store.getRoot(); // dispose it when done store.dispose(); ``` -------------------------------- ### Optimized Query Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/query-troubleshooting.md An example of a more specific query with improved path restrictions and node type constraints. ```sql select * from [acme:Product] where isdescendantnode('/etc/commerce') and lower([jcr:title]) like '%coat%') and [commerceType] = 'product' ``` -------------------------------- ### Bundling Pattern Configuration Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/document/node-bundling.md Example configuration for the bundling pattern using a 'pattern' property to specify which child nodes to bundle. ```text + jcr:system + rep:documentStore + bundlor + nt:file (oak:Unstructured) - pattern = ["jcr:content"] ``` -------------------------------- ### Select Path with LIKE Filter (Starts With) Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-core/src/test/resources/org/apache/jackrabbit/oak/query/sql2.txt Selects jcr:path of nodes where 'name' starts with 'W'. ```sql2 select [jcr:path] from [nt:base] where name like 'W%' ``` -------------------------------- ### XPath with jcr:deref() - Invalid Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-core/src/test/resources/org/apache/jackrabbit/oak/query/xpath.txt Shows an example of an invalid XPath query using jcr:deref(). ```xpath xpath2sql /jcr:root/testroot/people/jcr:deref(@worksfor, '*') invalid: Query: /jcr:root/testroot/people/jcr:deref(@(*)worksfor, '*') ``` -------------------------------- ### Example Lucene Property Index Configuration Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/ordered-index-migrate.md This is the corresponding Lucene property index configuration for the ordered index example. ```json { "jcr:primaryType" : "oak:QueryIndexDefinition", "compatVersion" : 2, "type" : "lucene", "async" : "async", "indexRules" : { "jcr:primaryType" : "nt:unstructured", "nt:unstructured" : { "properties" : { "jcr:primaryType" : "nt:unstructured", "foobar" : { "propertyIndex" : true, "name" : "foobar", "ordered" : true } } } } } ``` -------------------------------- ### Order by Name Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/lucene.md Demonstrates how to order query results by node name using NAME(). ```sql SELECT * FROM [sling:Folder] WHERE ISCHILDNODE('/content') ORDER BY NAME() ``` -------------------------------- ### Unusable Index Definition Example 2 Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/pre-extract-text.md An example of an unusable index definition due to the presence of aggregates and an include path. ```yaml + /oak:index/unUsableIndex2 ... + aggregates ... + nt:file ... + include0 - path="jcr:content" ``` -------------------------------- ### Unusable Index Definition Example 1 Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/pre-extract-text.md An example of an unusable index definition due to the binary property path being relative. ```yaml + /oak:index/unUsableIndex1 ... + indexRules ... + nt:file + properties ... + binary - name="jcr:content/jcr:data" - nodeScopeIndex=true ``` -------------------------------- ### Login and Perform Node Operations Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/construct.md Demonstrates how to log in to a repository using default credentials, access the root node, and perform basic operations like checking for a node, updating a property, or creating a node. Remember to save changes and log out. ```java Session session = repo.login( new SimpleCredentials("admin", "admin".toCharArray())); Node root = session.getRootNode(); if (root.hasNode("hello")) { Node hello = root.getNode("hello"); long count = hello.getProperty("count").getLong(); hello.setProperty("count", count + 1); System.out.println("found the hello node, count = " + count); } else { System.out.println("creating the hello node"); root.addNode("hello").setProperty("count", 1); } session.save(); ``` -------------------------------- ### Install Oak-Doc Railroad Macro Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/README.md Installs the oak-doc railroad macro locally, which is a prerequisite for building the Oak documentation site. ```bash mvn clean install -Pdoc -pl :oak-doc-railroad-macro ``` -------------------------------- ### Facet Query Examples Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/query/lucene.md Examples of SQL2 and XPath queries that utilize the rep:facet function to retrieve facet counts for properties. ```sql SELECT [rep:facet(title)] FROM [app:Asset] or /jcr:root//element(*, app:Asset)/(rep:facet(title)) or SELECT [rep:facet(title)], [rep:facet(tags)] FROM [app:Asset] or /jcr:root//element(*, app:Asset)/(rep:facet(title) | rep:facet(tags)) ``` -------------------------------- ### S3DataStore Configuration Example Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/migration.md Configuration for S3DataStore as a source or destination, including access keys, bucket details, and connection settings. ```properties accessKey=... secretKey=... s3Bucket=... s3Region=eu-west-1 s3EndPoint=s3-eu-west-1.amazonaws.com connectionTimeout=120000 socketTimeout=120000 maxConnections=40 writeThreads=30 maxErrorRetry=10 ``` -------------------------------- ### Segment-Copy with Logback Configuration Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/segment/overview.md Example of running the segment-copy tool with custom Logback logging configuration. This allows for detailed logging of the copy process to the console. ```bash java -Dlogback.configurationFile=logback-segment-copy.xml -jar oak-run.jar segment-copy cloud-prefix:URI some/local/path ``` -------------------------------- ### Start In-Memory Oak Repository Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-http/README.md Starts an in-memory Oak repository using the oak-run jar. The repository will be available at http://localhost:8080/. ```bash java -jar oak-run/target/oak-run-*.jar ``` -------------------------------- ### Compaction Started Log Message Source: https://github.com/apache/jackrabbit-oak/blob/trunk/oak-doc/src/site/markdown/nodestore/segment/overview.md Indicates the start of the compaction phase in garbage collection. It includes the garbage collection options used. ```log TarMK GC #2: compaction started, gc options=SegmentGCOptions{paused=false, estimationDisabled=false, gcSizeDeltaEstimation=1, retryCount=5, forceTimeout=3600, retainedGenerations=2, gcSizeDeltaEstimation=1} ```