### Example .cfg File Content Source: https://sling.apache.org/documentation/bundles/configuration-installer-factory An example of a simple .cfg file demonstrating the key-value pair format with comments. ```properties # default port ftp.port = 21 ``` -------------------------------- ### Install Sling Quickstart Feature on Karaf Source: https://sling.apache.org/documentation/karaf Installs a Sling Quickstart feature, such as 'sling-quickstart-oak-tar' or 'sling-quickstart-oak-mongo'. The latter requires a pre-configured MongoDB instance. This step deploys the core Sling application. ```bash karaf@root()> feature:install sling-quickstart-oak-tar ``` -------------------------------- ### Starting Sling with a Custom Main Feature Source: https://sling.apache.org/documentation/feature-model/howtos/kickstart This example demonstrates how to start an Apache Sling instance using a specific feature model file. It involves navigating to the kickstarter directory, stopping any running instance, cleaning up old configurations, extracting the feature model, and then launching Sling with the --mainFeature option. ```bash cd kickstarter java -jar org.apache.sling.kickstart-0.0.2.jar stop rm -rf conf launcher jar -xf org.apache.sling.kickstart-0.0.2.jar feature-sling12.json java -jar org.apache.sling.kickstart-0.0.2.jar --mainFeature=feature-sling12.json ``` -------------------------------- ### OSGi Configuration JSON Format Example Source: https://sling.apache.org/documentation/bundles/configuration-installer-factory Provides an example of a configuration file in JSON format (.cfg.json), which is the preferred method for specifying configurations. It demonstrates typed values, including integers, and comments. ```json { "key": "val", "some_number": 123, // This is an integer value: "size:Integer" : 500 } ``` -------------------------------- ### Singleton and Factory Configuration Examples Source: https://sling.apache.org/documentation/bundles/configuration-installer-factory Illustrates the naming conventions for singleton and factory configurations. Singleton configurations use the PID directly followed by an extension, while factory configurations include a subname separated by a dash or tilde. ```plaintext com.acme.xyz.cfg // singleton configuration // com.acme.xyz com.acme.abc-default.cfg // factory configuration // creates an instance for com.acme.abc named default ``` -------------------------------- ### Install OSGi Bundle using JCR Installer Source: https://sling.apache.org/documentation/bundles/jcr-installer-provider Installs an OSGi bundle (e.g., `desktop_awt_all-2.0.0.jar`) into the JCR repository under the `/apps/jcrtest/install` directory. JCRInstall automatically detects and installs bundles placed in these designated folders. ```bash curl -T desktop_awt_all-2.0.0.jar \ http://admin:admin@localhost:8080/apps/jcrtest/install/desktop_awt_all-2.0.0.jar ``` -------------------------------- ### Short Form Build and Run Sling Source: https://sling.apache.org/documentation/development/getting-and-building-sling Quick instructions to clone the Sling starter project, build it with Maven, and run the executable JAR with remote debugging enabled. Assumes Git, JDK, and Maven are installed. ```bash git clone https://github.com/apache/sling-org-apache-sling-starter.git cd sling-org-apache-sling-starter mvn --update-snapshots clean install export DBG="-Xmx384M -agentlib:jdwp..." java $DBG -jar target/org.apache.sling.starter... ``` -------------------------------- ### Forward Distribution Usecase Examples Source: https://sling.apache.org/documentation/bundles/distribution Examples demonstrating how to use the distribution API for a 'forward' distribution workflow, typically from author to publish instances. ```APIDOC ## Forward Distribution Usecases ### Description Examples for configuring and executing a 'forward' distribution workflow, which transfers content from an author instance to a publish instance. ### Usecase 1: Create/update content This demonstrates sending an HTTP POST request to add or update content at a specified path. #### Method POST #### Endpoint /libs/sling/distribution/services/agents/publish #### Parameters ##### Query Parameters - **action** (string) - Required - Set to 'ADD' to create or update content. - **path** (string) - Required - The repository path of the content to distribute (e.g., '/content/sample1'). #### Request Example ```bash curl -v -u admin:admin http://localhost:8080/libs/sling/distribution/services/agents/publish -d 'action=ADD' -d 'path=/content/sample1' ``` ### Usecase 2: Delete content This demonstrates sending an HTTP POST request to delete content at a specified path. #### Method POST #### Endpoint /libs/sling/distribution/services/agents/publish #### Parameters ##### Query Parameters - **action** (string) - Required - Set to 'DELETE' to remove content. - **path** (string) - Required - The repository path of the content to delete (e.g., '/content/sample1'). #### Request Example ```bash curl -v -u admin:admin http://localhost:8080/libs/sling/distribution/services/agents/publish -d 'action= DELETE' -d 'path=/content/sample1' ``` ``` -------------------------------- ### Example Agent Verbose Output Source: https://sling.apache.org/documentation/bundles/connection-timeout-agent Shows an example of the output generated when the Connection Timeout Agent is started in verbose mode. This output details the transformation process for different HTTP connection classes. ```text [AGENT] Preparing to install URL transformers. Configured timeouts - connectTimeout : 1000, readTimeout: 1000 [AGENT] All transformers installed [AGENT] JavaNetTimeoutTransformer asked to transform sun/net/www/protocol/https/AbstractDelegateHttpsURLConnection [AGENT] Transformation of sun/net/www/protocol/https/AbstractDelegateHttpsURLConnection complete [AGENT] JavaNetTimeoutTransformer asked to transform sun/net/www/protocol/http/HttpURLConnection [AGENT] Transformation of sun/net/www/protocol/http/HttpURLConnection complete ``` -------------------------------- ### Start Sling Instance with Kickstarter Source: https://sling.apache.org/documentation/feature-model/howtos/kickstart This command starts an Apache Sling instance using the downloaded Kickstarter JAR. It assumes that port 8080 is available. The first launch may take time as it populates the local Maven repository with necessary artifacts. ```bash java -jar org.apache.sling.kickstart-0.0.2.jar ``` -------------------------------- ### Example Pipe Configuration with Output Binding Source: https://sling.apache.org/documentation/bundles/sling-pipes/bindings This example demonstrates a pipe configuration using 'echo', 'children', and 'write' pipes. It shows how to use an output binding named 'example' to access properties from the processed nodes and set them as a 'jcr:description'. ```pipes echo /content/foo | children nt:unstructured @ name example | write jcr:description='this node property prop = ${example.prop}' ``` -------------------------------- ### Property File Inclusion Example Source: https://sling.apache.org/documentation/configuration An example demonstrating how to include other property files within the Sling configuration. This is achieved by defining properties like 'sling.include' or 'sling.include.'. The example shows how to include JRE-specific properties based on the Java version. ```properties sling.include.jre = jre-${java.specification.version}.properties ``` -------------------------------- ### Changing and Removing Artifacts in Maven Provisioning Model Source: https://sling.apache.org/documentation/development/slingstart This example shows how to change artifact versions, start levels, and remove artifacts from a base model. The ':remove' run mode is used for removal, and specific run modes can target removals. ```text [artifacts startLevel=5] commons/library/1.1.0 [artifacts runModes=:remove] my/special/artifact/0.0.0 [artifacts runModes=:remove,test] another/one/0.0.0 ``` -------------------------------- ### Run Sling Executable JAR Source: https://sling.apache.org/documentation/development/getting-and-building-sling Command to start the Sling instance using the executable JAR generated by the org.apache.sling.starter module. It specifies the JAR file and can include options for logging and data storage. ```bash java -jar target/org.apache.sling.starter-*.jar ``` -------------------------------- ### Define Repository Access for Service User (Repoinit) Source: https://sling.apache.org/documentation/bundles/content-package-installer-factory This example uses repoinit syntax to create a service user named 'sling-package-install' and grant it necessary permissions. It allows full JCR access on the repository root and specific management privileges on repository-level definitions. ```repoinit create service user sling-package-install set ACL for sling-package-install allow jcr:all on / allow jcr:namespaceManagement,jcr:nodeTypeDefinitionManagement on :repository end ``` -------------------------------- ### Start Sling with External Logback Configuration Source: https://sling.apache.org/documentation/development/logging This command demonstrates how to start the Apache Sling Starter JAR with an external logback.xml configuration file. The `org.apache.sling.commons.log.configurationFile` system property specifies the path to your custom Logback configuration. ```bash java -jar org.apache.sling.starter-XXX-standalone.jar -Dorg.apache.sling.commons.log.configurationFile=/path/to/logback ``` -------------------------------- ### Get Deepest Page Ancestor with Sling Query Source: https://sling.apache.org/documentation/bundles/sling-query/examples Finds the ancestor cq:Page that is closest to the JCR root. This effectively gets the top-level page ancestor. ```slingquery $(resource).parents("cq:Page").last() ``` -------------------------------- ### Install Sling Configurations on Karaf Source: https://sling.apache.org/documentation/karaf Installs the OSGi configurations for provisioning Sling within Apache Karaf. These configurations are essential for the proper setup and operation of Sling. ```bash karaf@root()> feature:install sling-configs ``` -------------------------------- ### Build a Sling Module with Maven Source: https://sling.apache.org/documentation/development/getting-and-building-sling Command to build any individual Sling module by navigating to its directory and executing a Maven clean install. This command updates snapshots and installs the module. ```bash mvn --update-snapshots clean install ``` -------------------------------- ### Download and Prepare Sling Kickstarter Source: https://sling.apache.org/documentation/feature-model/howtos/kickstart This snippet demonstrates how to download the Sling Kickstarter bundle and set up a working directory. It involves creating a directory and copying the downloaded JAR file into it. Ensure you replace the placeholder path with the actual download location. ```bash $ mkdir kickstarter $ cd kickstarter $ cp /some/download/path/org.apache.sling.kickstart-0.0.2.jar . ``` -------------------------------- ### Get User Details with curl Source: https://sling.apache.org/documentation/bundles/managing-users-and-groups-jackrabbit-usermanager Fetches the properties of a specific user by sending a GET request to /system/userManager/user/. The response format is determined by the Default GET Servlet or resource type handlers. A 404 status is returned if the user does not exist. This example retrieves details for the 'admin' user. ```bash $ curl http://localhost:8080/system/userManager/user/admin.tidy.1.json { "memberOf": [], "declaredMemberOf": [] } ``` -------------------------------- ### Install Starter Content on Karaf Source: https://sling.apache.org/documentation/karaf Installs starter content for Sling, which includes the Composum feature. This provides a basic set of content and functionalities to begin using Sling. ```bash karaf@root()> feature:install sling-starter-content ``` -------------------------------- ### Get First Sibling with Sling Query Source: https://sling.apache.org/documentation/bundles/sling-query/examples Retrieves the first sibling cq:Page of the current resource. ```slingquery $(resource).closest("cq:Page").siblings("cq:Page").first() ``` -------------------------------- ### Basic Server-Side Test with TeleporterRule (Java) Source: https://sling.apache.org/documentation/bundles/org-apache-sling-junit-bundles Demonstrates a basic server-side test using the TeleporterRule to access OSGi services like ConfigurationAdmin. The TeleporterRule handles bundle creation, deployment, execution, and cleanup. ```java public class BasicTeleporterTest { @Rule public final TeleporterRule teleporter = TeleporterRule.forClass(getClass(), "Launchpad"); @Test public void testConfigAdmin() throws IOException { final String pid = "TEST_" + getClass().getName() + UUID.randomUUID(); final ConfigurationAdmin ca = teleporter.getService(ConfigurationAdmin.class); assertNotNull("Teleporter should provide a ConfigurationAdmin", ca); final Configuration cfg = ca.getConfiguration(pid); assertNotNull("Expecting to get a Configuration", cfg); assertEquals("Expecting the correct pid", pid, cfg.getPid()); } } ``` -------------------------------- ### Starting Sling with Control Port Enabled Source: https://sling.apache.org/documentation/the-sling-engine/the-sling-launchpad This command starts the Apache Sling Standalone Application with the control port active. The control port allows for remote management of the Sling instance, such as stopping it or getting thread dumps. The port and address are logged during startup. ```bash java -jar target/org.apache.sling.starter-11.jar start ``` -------------------------------- ### Create OSGi Configuration Node Source: https://sling.apache.org/documentation/bundles/jcr-installer-provider Creates an OSGi configuration node with specified properties (`foo=bar`, `works=yes`) under the `/apps/jcrtest/install` directory. JCRInstall monitors these nodes to deploy configurations. ```bash curl \ -F "jcr:primaryType=sling:OsgiConfig" \ -F foo=bar -F works=yes \ http://admin:admin@localhost:8080/apps/jcrtest/install/some.config.pid ``` -------------------------------- ### List Groups via GET Request (JSON) Source: https://sling.apache.org/documentation/bundles/managing-users-and-groups-jackrabbit-usermanager Retrieves a list of existing groups by sending a GET request to the group resource endpoint. The response format depends on server configuration, with an example showing JSON rendering. ```curl $ curl http://localhost:8080/system/userManager/group.tidy.1.json { "UserAdmin": { "members": [], "declaredMembers": [], "memberOf": [], "declaredMemberOf": [] }, "GroupAdmin": { "members": [], "declaredMembers": [], "memberOf": [], "declaredMemberOf": [] }, "administrators": { "members": [], "declaredMembers": [], "memberOf": [], "declaredMemberOf": [] } } ``` -------------------------------- ### Get Containing Page with Sling Query Source: https://sling.apache.org/documentation/bundles/sling-query/examples Retrieves the closest ancestor resource that is a cq:Page. This is analogous to PageManager#getContainingPage. ```slingquery $(resource).closest("cq:Page") ``` -------------------------------- ### List Users with curl Source: https://sling.apache.org/documentation/bundles/managing-users-and-groups-jackrabbit-usermanager Retrieves a list of existing users by sending a GET request to the /system/userManager/user resource. The output format depends on the Default GET Servlet configuration or specific resource type handlers. This example uses curl with the .tidy.1.json renderer. ```bash $ curl http://localhost:8080/system/userManager/user.tidy.1.json { "admin": { "memberOf": [], "declaredMemberOf": [] }, "anonymous": { "memberOf": [], "declaredMemberOf": [] } } ``` -------------------------------- ### Programmatically Reusing DefaultGetServlet Source: https://sling.apache.org/documentation/bundles/rendering-content-default-get-servlets Demonstrates how to programmatically reuse the DefaultGetServlet from a custom servlet, for example, to stream a binary resource with a different extension. ```APIDOC ## Programmatically Reusing DefaultGetServlet ### Description This section outlines how to programmatically reuse the `DefaultGetServlet` from within a custom servlet. A common scenario is streaming a binary resource using the default servlet but with a different extension than its original path. ### Method N/A (Illustrates Java code) ### Endpoint N/A (Illustrates Java code) ### Parameters None specific to this code example. ### Code Example (Java) ```java import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.sling.api.resource.Resource; import java.io.IOException; public class CustomStreamServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Obtain the resource to render Resource toRender = /* code to obtain resource here */ null; if (toRender != null) { // Forward the request to the DefaultGetServlet with a .res extension request.getRequestDispatcher(toRender.getPath() + ".res").forward(request, response); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found."); } } } ``` ### Notes - The example shows forwarding to a `.res` extension, but the same approach applies to other renderings by adjusting the selector (e.g., `.json`, `.html`). - See SLING-8742 for discussions on providing an API for overriding extensions with `RequestDispatcher`. ``` -------------------------------- ### Create JCR Directory for Bundle Installation Source: https://sling.apache.org/documentation/bundles/jcr-installer-provider Creates the necessary JCR directories (`/apps/jcrtest` and `/apps/jcrtest/install`) required by JCRInstall to pick up bundles. This is a prerequisite for installing bundles. ```bash curl -X MKCOL http://admin:admin@localhost:8080/apps/jcrtest curl -X MKCOL http://admin:admin@localhost:8080/apps/jcrtest/install ``` -------------------------------- ### Get Specific Children with Sling Query Source: https://sling.apache.org/documentation/bundles/sling-query/examples Selects the second child (index 1) of multiple specified resources. Supports selecting children by index. ```slingquery $(resource1, resource2, resource3).children(":eq(1)") ``` -------------------------------- ### Deploy OSGi Bundle with Initial Content (Maven) Source: https://sling.apache.org/documentation/bundles/accessing-filesystem-resources-extensions-fsresource Deploys an OSGi bundle containing initial content from the current Maven project and registers the appropriate file system resource provider mappings. This command leverages the Maven Sling Plugin. ```bash mvn -Dsling.mountByFS=true sling:install ``` -------------------------------- ### Move Resource using Sling API CRUD Source: https://sling.apache.org/documentation/the-sling-engine/sling-api-crud-support This example demonstrates moving a resource to a new location using the Sling API. It involves getting the resource, using the `move` method with the source path and destination, and then committing the changes. The example also includes deleting the original resource, which might be part of a specific move strategy. ```java Resource myResource2 = resourceResolver.getResource("/apps/myresource2"); Resource myResource3 = resourceResolver.move(myResource.getPath(), "/libs", properties); resourceResolver.delete(myResource2); resourceResolver.commit(); ``` -------------------------------- ### Get Parents Until Specific Page with Sling Query Source: https://sling.apache.org/documentation/bundles/sling-query/examples Fetches all ancestor cq:Page resources up to a specified homepage template, mapping them to Page objects. Useful for limiting breadcrumb trails. ```java Iterable breadcrumbs; breadcrumbs = $(resource).parentsUntil("cq:Page[jcr:content/cq:template=/apps/geometrixx/templates/homepage]", "cq:Page").map(Page.class); ``` -------------------------------- ### Base Model for Configuration Management in Maven Source: https://sling.apache.org/documentation/development/slingstart This example defines a base provisioning model with configurations. These configurations can be modified or removed by other models. ```text [configurations] my.special.configuration.b foo="bar" another.special.configuration.a x="y" ``` -------------------------------- ### Get First N Children with Sling Query Source: https://sling.apache.org/documentation/bundles/sling-query/examples Selects the first two children (indices less than 2) of multiple specified resources. Useful for limiting the number of children retrieved. ```slingquery $(resource1, resource2, resource3).children(":lt(2)") ``` -------------------------------- ### Convert JDBC Driver JAR to OSGi Bundle using Bnd Source: https://sling.apache.org/documentation/bundles/datasource-providers This example demonstrates how to convert a JDBC driver JAR (like the PostgreSQL driver) into an OSGi bundle using the Bnd tool. It involves downloading the Bnd JAR, the driver JAR, creating a `bnd.bnd` file with necessary instructions, and executing the Bnd command to generate the OSGi bundle. ```bash $ wget https://github.com/bndtools/bnd/releases/download/2.3.0.REL/biz.aQute.bnd-2.3.0.jar -O bnd.jar $ wget https://jdbc.postgresql.org/download/postgresql-9.3-1101.jdbc41.jar $ cat > bnd.bnd < [options] [command] ``` -------------------------------- ### Register File System Mounts (Maven) Source: https://sling.apache.org/documentation/bundles/accessing-filesystem-resources-extensions-fsresource Registers the appropriate file system resource provider mappings for content defined in the project. This command is used for both INITIAL_CONTENT and FILEVAULT_XML modes. ```bash mvn sling:fsmount ```