Return-Path: X-Original-To: apmail-sling-commits-archive@www.apache.org Delivered-To: apmail-sling-commits-archive@www.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 1BEEBDA31 for ; Wed, 12 Dec 2012 09:16:15 +0000 (UTC) Received: (qmail 37116 invoked by uid 500); 12 Dec 2012 09:16:14 -0000 Delivered-To: apmail-sling-commits-archive@sling.apache.org Received: (qmail 37067 invoked by uid 500); 12 Dec 2012 09:16:14 -0000 Mailing-List: contact commits-help@sling.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@sling.apache.org Delivered-To: mailing list commits@sling.apache.org Received: (qmail 37060 invoked by uid 99); 12 Dec 2012 09:16:14 -0000 Received: from nike.apache.org (HELO nike.apache.org) (192.87.106.230) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 12 Dec 2012 09:16:14 +0000 X-ASF-Spam-Status: No, hits=-2000.0 required=5.0 tests=ALL_TRUSTED,T_FILL_THIS_FORM_SHORT X-Spam-Check-By: apache.org Received: from [140.211.11.4] (HELO eris.apache.org) (140.211.11.4) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 12 Dec 2012 09:16:02 +0000 Received: from eris.apache.org (localhost [127.0.0.1]) by eris.apache.org (Postfix) with ESMTP id 0F46D2388C7C; Wed, 12 Dec 2012 09:15:07 +0000 (UTC) Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: svn commit: r1420577 [11/30] - in /sling/site/trunk/content/site: ./ 46-line-blog.data/ authentication.data/ documentation.data/ first-steps.data/ getting-and-building-sling.data/ how-to-manage-events-in-sling.data/ index.data/ links.data/ manipulating... Date: Wed, 12 Dec 2012 09:14:44 -0000 To: commits@sling.apache.org From: cziegeler@apache.org X-Mailer: svnmailer-1.0.8-patched Message-Id: <20121212091507.0F46D2388C7C@eris.apache.org> X-Virus-Checked: Checked by ClamAV on apache.org Added: sling/site/trunk/content/site/form-based-authenticationhandler.html URL: http://svn.apache.org/viewvc/sling/site/trunk/content/site/form-based-authenticationhandler.html?rev=1420577&view=auto ============================================================================== --- sling/site/trunk/content/site/form-based-authenticationhandler.html (added) +++ sling/site/trunk/content/site/form-based-authenticationhandler.html Wed Dec 12 09:13:50 2012 @@ -0,0 +1,274 @@ + + + + + Apache Sling - Form Based AuthenticationHandler + + + + + +
+ +
+ + Apache + +
+
+ +
+ +

Form Based AuthenticationHandler

+ + + +

The Form Based AuthenticationHandler has two authentication phases: The first phase is presenting a login form to the user and passing the entered user name and password to the server. The second phase is storing successful authentication in a Cookie or an HTTP Session.

+ +

The implementation of the Form Based Authentication Handler follows the guidelines of the Servlet API 2.4 specification for Form Based Authentication in section SRV.12.5.3. Specifically the following requirements are implemented:

+ +
    +
  • For the initial form submission, the request URL must end with /j_security_check and the user name and password names must be j_username and j_password, resp.
  • +
  • The authentication type as returned by HttpServletRequest.getAuthType() is set to HttpServletRequest.FORM_AUTH.
  • +
+ + +

The Form Based Authentication Handler is maintained in the Sling SVN

+ + +

AuthenticationHandler implementation

+ + +
    +
  • extractCredentials – Prepares credentials for the form entered data or from the Cookie or HTTP Session attribute. Returns null if neither data is provided in the request
  • +
  • requestCredentials – Redirects the client (browser) to the login form
  • +
  • dropCredentials – Remove the Cookie or remove the HTTP Session attribute
  • +
+ + + +

AuthenticationFeedbackHandler implementation

+ +
    +
  • authenticationFailed – Remove the Cookie or remove the HTTP Session attribute
  • +
  • authenticationSucceeded – Set (or update) the Cookie or HTTP Session attribute
  • +
+ + + +

Phase 1: Form Submission

+ + +

The login form submitted in phase 1 to validate the user name and password must be provided in an HTTP POST request to an URL whose last segment is j_security_check. The request is ignored as a form submission if either the method is not POST or the last segment is no j_security_check.

+ +

The form is rendered by redirecting the client to the URL indicated by the form.login.form configuration parameter. This redirection request may accompanyied by the following parameters:

+ +
    +
  • resource – The resource to which the user should be redirected after successful login. This request parameter should be submitted back to the server as the resource parameter.
  • +
  • j_reason – This parameter indicates the reason for rendering the login form. If this parameter is set, it is set to INVALID_CREDENTIALS indicating a previous form submission presented invalid username and password or TIMEOUT indicating a login session has timed out. The login form servlet/script can present the user with an appropriate message.
  • +
+ + +

The Form Based Authentication Handlers supports the following request parameters submitted by the HTML form:

+ +
    +
  • j_username – Name of the user to authenticate
  • +
  • j_password – Password to authenticate the user
  • +
  • j_validate – Flag indicating whether to just validate the credentials
  • +
  • resource – The location to go to on successful login
  • +
  • sling.auth.redirect – The location to redirect to on successful login
  • +
+ + +

The j_username and j_password parameters are used to create a JCR SimpleCredentials object to log into the JCR Repository.

+ +

The j_validate parameter may be used to implement login form submission using AJAX. If this parameter is set to true (case-insensitive) the credentials are used to login and after success or failure to return a status code:

+ +
+ + + + + + + + + + + + + +
Status Description
200 OK Authentication succeeded; credentials are valid for login; the Cookie or HTTP Session attribute is now set
403 FORBIDDEN Authentication failed; credentials are invalid for login; the Cookie or HTTP Session attribute is not set (if it was set, it is now cleared)
+
+ + +

If the j_validate parameter is not set or is set to any value other than true, the request processing depends on authentication success or failure:

+ +
+ + + + + + + + + + + + + +
Authentication Description
Success Client is redirected to the authenticated resource; the Cookie or HTTP Session attribute is now set.
Failure The request is redirected to the login form again; the Cookie or HTTP Session attribute is not set (if it was set, it is now cleared)
+
+ + +

The resource and sling.auth.redirect parameters provide similar functionality but with differing historical backgrounds. The resource parameter is based on the resource request attribute which is set by the login servlet to indicate the original target resource the client desired when it was forced to authenticate. The sling.auth.redirect parameter can be used by clients (applications like cURL or plain HTML forms) to request being redirected after successful login. If both parameters are set, the sling.auth.redirect parameter takes precedence.

+ +

The Form Based Authentication Handler contains a default form servlet and HTML form template from.

+ + +

Phase 2: Authenticated Requests

+ + +

After the successful authentication of the user in phase 1, the authentication state is stored in a Cookie or an HTTP Session. The stored value is a security token with the following contents:

+ +
+
+HmacSHA1(securetoken, <securetokennumber><expirytime>@<userID>)@<securetokennumber><expirytime>@<userID>
+
+
+ +

The securetoken and securetokennumber are related in that an table of secure tokens is maintained where the securetoken is an entry in the table and the securetokennumber is the index in of the token in the table.

+ +

The secure tokens are refreshed periodically causing the authentication state stored in the Cookie or the HTTP Session to be updated peridocally. This periodic update has two advantages:

+ +
    +
  • Login sessions time out after some period of inactivity: If a request is handled for an authentication state whose expiry time has passed, the request is considered unauthenticated.
  • +
  • If a Cookie would be stolen or an HTTP Session be hijacked, the authentication state expires within a reasonable amount of time to try to prevent stealing the authentication.
  • +
+ + +

The authentication state may be transmitted with a Cookie which is configured as follows:

+ +
    +
  • Cookie Path – Set to the servlet context path
  • +
  • Domain – See below
  • +
  • Age – Set to -1 to indicate a session Cookie
  • +
  • Secure – Set to the value returned by the ServletRequest.isSecure() method
  • +
+ + +

If the authentication state is kept in an HTTP Session the setup of the session ID cookie is maintained by the servlet container and is outside of the control of the Form Based AuthenticationHandler.

+ + +

Configuration

+ +

The Form Based Authentication Handler is configured with configuration provided by the OSGi Configuration Admin Service using the org.apache.sling.formauth.FormAuthenticationHandler service PID.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Parameter Default Description
form.login.form /system/sling/form/login The URL (without any context path prefix) to redirect the client to to present the login form.
form.auth.storage cookie The type of storage used to provide the authentication state. Valid values are cookie and session. The default value also applies if any setting other than the supported values is configured.
form.auth.name sling.formauth The name of the Cookie or HTTP Session attribute providing the authentication state.
form.auth.timeout 30 The number of minutes after which a login session times out. This value is used as the expiry time set in the authentication data.
form.credentials.name sling.formauth The name of the SimpleCredentials attribute used to provide the authentication data to the LoginModulePlugin.
form.token.file cookie-tokens.bin The name of the file used to persist the security tokens.
form.default.cookie.domain   The domain on which cookies will be set, unless overridden in the AuthenticationInfo object.
+
+ + +

Note: The form.token.file parameter currently refers to a file stored in the file system. If the path is a relative path, the file is either stored in the Authentication Handler bundle private data area or – if not possible – below the location indicated by the sling.home framework property or – if sling.home is not set – the current working directory. In the future this file may be store in the JCR Repository to support clustering scenarios.

+ + +

Security Considerations

+ +

Form Based Authentication has some limitations in terms of security:

+ +
    +
  1. User name and password are transmitted in plain text in the initial form submission.
  2. +
  3. The Cookie used to provide the authentication state or the HTTP Session ID may be stolen.
  4. +
+ + +

To prevent eavesdroppers from sniffing the credentials or stealing the Cookie a secure transport layer should be used such as TLS/SSL, VPN or IPSec.

+
+Last modified by fmeschbe on 2011-05-25 10:04:53.0 +
+
+Apache Sling, Sling, Apache, the Apache feather logo, and the Apache Sling project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners. +
+
+ + + Propchange: sling/site/trunk/content/site/form-based-authenticationhandler.html ------------------------------------------------------------------------------ svn:eol-style = native Propchange: sling/site/trunk/content/site/form-based-authenticationhandler.html ------------------------------------------------------------------------------ svn:keywords = Id Propchange: sling/site/trunk/content/site/form-based-authenticationhandler.html ------------------------------------------------------------------------------ svn:mime-type = text/plain Added: sling/site/trunk/content/site/getting-and-building-sling.data/test.sh URL: http://svn.apache.org/viewvc/sling/site/trunk/content/site/getting-and-building-sling.data/test.sh?rev=1420577&view=auto ============================================================================== --- sling/site/trunk/content/site/getting-and-building-sling.data/test.sh (added) +++ sling/site/trunk/content/site/getting-and-building-sling.data/test.sh Wed Dec 12 09:13:50 2012 @@ -0,0 +1,40 @@ +#!/bin/sh +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +JAVA_HOME=${JAVA_HOME:=/usr/java/jdk1.5.0_11} +JAVA=${JAVA_HOME}/bin/java +JAVA_DEBUG="-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=30503,server=y,suspend=n" +SLING_HOME=sling.test +SLING_LOG_FILE= +SLING_DEFS="-Dsling.install.20= -Dorg.osgi.service.http.port=8080" +SLING_JAR="target/org.apache.sling.launcher.app-2.0.0-incubator-SNAPSHOT.jar" + +## Append command line arguments (not actually correct, but suffices it) +SLING_DEFS="${SLING_DEFS} $@" + +## Enable this for JAAS LDAP Auth +# SLING_DEFS="${SLING_DEFS} -Djava.security.auth.login.config=${PWD}/ldap_login.conf" + +## Enable this for JVMTI profiling +# SLING_DEFS="${SLING_DEFS} -agentlib:yjpagent" + +export JAVA JAVA_DEBUG SLING_HOME SLING_LOG_FILE SLING_DEFS + +${JAVA} ${JAVA_DEBUG} -Dsling.home=${SLING_HOME} -Dorg.apache.sling.osgi.log.file=${SLING_LOG_FILE} ${SLING_DEFS} -jar ${SLING_JAR} Propchange: sling/site/trunk/content/site/getting-and-building-sling.data/test.sh ------------------------------------------------------------------------------ svn:eol-style = native Propchange: sling/site/trunk/content/site/getting-and-building-sling.data/test.sh ------------------------------------------------------------------------------ svn:executable = * Propchange: sling/site/trunk/content/site/getting-and-building-sling.data/test.sh ------------------------------------------------------------------------------ svn:keywords = Id Added: sling/site/trunk/content/site/getting-and-building-sling.html URL: http://svn.apache.org/viewvc/sling/site/trunk/content/site/getting-and-building-sling.html?rev=1420577&view=auto ============================================================================== --- sling/site/trunk/content/site/getting-and-building-sling.html (added) +++ sling/site/trunk/content/site/getting-and-building-sling.html Wed Dec 12 09:13:50 2012 @@ -0,0 +1,320 @@ + + + + + Apache Sling - Getting and Building Sling + + + + + +
+ +
+ + Apache + +
+
+ +
+ +

Getting and Building Sling

+

A quick guide for getting the Sling source, then building and running the resulting Sling instance; either without or with Eclipse.

+ +

Sling can easily be built:

+
    +
  • from the command line (using SVN and the Maven command line tool)
  • +
  • or using Eclipse
  • +
+ + +

Note that you don't have to build Sling yourself, if you don't need the bleeding-edge stuff you can get prebuilt binaries from the Downloads page.

+ +

A full build of Sling takes 5-10 minutes on a recent computer once your local Maven repository is up to date. The first build may take much longer than that if you start with an empty local Maven repository, as Maven will then download its plugins and all the required dependencies.

+ +

Prerequisites

+ +

Before you begin, you need to have the following tools installed on your system:

+
    +
  • Java 5 or higher; Java 6 recommended
  • +
  • Maven 3.0.2 or later; enforced by the Sling parent pom
  • +
+ + +

If you want to set up Eclipse (not required to build Sling) you'll also need the following installed:

+
    +
  • Eclipse (tested with 3.4.2 and 3.5.x on Win XP, SP3, 3.6.x on Win7, 3.7 on MacOS X 10.6); just a plain installation of the platform runtime binary and the JDT will be adequate (you can install the IDE for Java Developers for convenience)
  • +
  • M2Eclipse plugin for Eclipse (sonatype) -> instructions
  • +
  • Subversive plugin or Subclipse-plugin for Eclipse
  • +
+ + +

Environment Setup

+ +

The full build process requires quite a lot of resources, so you may run into limits. The following hints should show you what to setup before building Sling.

+ + +

Java Heap Space

+ +
    +
  • Problem - Build aborts with reports of java.lang.OutOfMemoryError: Java heap space. Alternatively the build may randomly fail during the integration tests.
  • +
  • Platforms - This happens on all platforms
  • +
  • Fix - Increase the values of the maximum heap and perm space for the build by setting or extending the MAVEN_OPTS environment variable.
  • +
+ + +

For 32bit platforms you should use

+
+
MAVEN_OPTS="-Xmx256M -XX:MaxPermSize=256m"
+
+
+ +

For 64bit platforms, you should use

+
+
MAVEN_OPTS="-Xmx512M -XX:MaxPermSize=512m"
+
+
+ +

For more information see SLING-443 and SLING-1782.

+ + +

Environment Variable Space

+ +
    +
  • Problem - Build aborts when trying to launch the integration tests with the message +
    +
    [INFO] Error while executing forked tests.; nested exception is org.apache.maven.surefire.booter.shade.org.codehaus.plexus.util.cli.CommandLineException: Error setting up environmental variables
    +
    +error=12, Not enough space
    +
    +
    +

    This problem is caused by insufficient swap space. When running the integration tests in the launchpad/testing modules, a process is launched by calling the exec system call. This copies the process (copy-on-write, though) and thus allocates as much virtual memory as is owned by the parent process. This may fail if swap space is exhausted.

  • +
  • Platform - OpenSolaris
  • +
  • Fix - If this issue persists you will need to check your system requirements and configuration with regard to swap, before taking action - if necessary.
  • +
+ + +

Configuring Maven

+ +

See MavenTipsAndTricks.

+ + +

Getting the Sling Source

+ + +

With SVN

+ +
    +
  1. Checkout Sling from the Repository. +
    +
    $ svn checkout http://svn.apache.org/repos/asf/sling/trunk sling
    +
    +
  2. +
+ + +

With Eclipse Subversive or Subclipse

+

First note how simple the above SVN instructions are...but if you really want to do this, read on.

+ +

If you use the Subversive plugin make sure you have installed the "Subversive Integration for M2Eclipse Project" which can be found under the following Eclipse update site: http://community.polarion.com/projects/subversive/download/integrations/update-site/.

+ +

Also, make sure that you have installed either the "Maven SCM handler for Subclipse" or the "Maven SCM handler for Subversive".

+ +

Create a new workspace

+ +

It's best to create a new workspace for the sling project:

+
    +
  1. Menu: File->Switch Workspace->Other...
  2. +
  3. Enter a path for the new workspace and click OK
  4. +
  5. When Eclipse has restarted it's time to adjust some configs
  6. +
  7. Turn off automatic build (Menu: Project->Build Automatically)
  8. +
  9. Go to menu: Eclipse->Preferences, in the preferences dialog select Java -> Compiler -> Errors/Warnings
  10. +
  11. Expand the "Deprecated and restricted API" and change "Forbidden references (access rules)" from "Error" to "Warning"
  12. +
  13. Click OK
  14. +
+ + +

Checkout the Sling source

+ +
    +
  1. Menu: File->Import
  2. +
  3. In the Import wizard select Maven->"Check out Maven Projects from SCM"
  4. +
  5. Click next
  6. +
  7. In the "SCM URL" field pick "SVN" and enter the url "http://svn.apache.org/repos/asf/sling/trunk"
  8. +
  9. Click Finish
  10. +
+ + +

Eclipse will now start to download the source and import the Maven projects. You might encounter some "Problem Occured" dialogs about "An internal error...", but just click OK on those and let Eclipse continue with the import. Be warned: This could take some time (it was 30 minutes on my laptop)!

+ +

Possibly something in sling-builder might get a bit messed up (I didn't experience that problem, but Pontus reported it) then you can simply fix it with revert:

+
    +
  1. In the Project Explorer right-click on the "sling-builder" project and select the Team->Revert... menu
  2. +
  3. A couple of changes will be displayed
  4. +
  5. Click OK
  6. +
+ + +

Building Sling

+ + +

With the Maven command line tool

+ +
    +
  1. Enter the directory, then do a full build and local install (below are unix/linux commands, slightly different under windows) +
    +
    $ cd sling
    +$ export MAVEN_OPTS="-Xmx256m -XX:MaxPermSize=128m"
    +$ mvn -s /dev/null clean install
    +
    +
    +

    Note: On windows just leave out /dev/null and make sure you have an empty settings.xml file for maven (located in your user directory under .m2).

  2. +
  3. Enter the launchpad/builder directory and launch Sling for the first time +
    +
    $ cd launchpad/builder
    +$ java -jar target/org.apache.sling.launchpad-*-standalone.jar -c test -f -
    +
    +
  4. +
+ + +
When starting Sling inside the launchpad/builder folder you should not use the default Sling Home folder name sling because this folder is removed when running mvn clean.
+ +

Messages should now be printed to the console which is being used as the "log file"; the -f command line option is set to -, indicating the use of standard output as the log file. The -c sling command line option instructs Sling to use the sling directory in the current directory for its data store, which is the Apache Felix bundle archive, the Jackrabbit repository data and configuration. You may also specify another directory here, either a relative or absolute path name (See also Configuration for more information).
+Use the -h option to see the list of flags and options.
+After all messages have been printed you should be able to open the Sling Management Console by pointing your web browser at http://localhost:8080/system/console. You will be prompted for a user name and password. Enter admin for both the user name and the password (this may be set on the Configuration page later). From this console, you can manage the installed bundles, modify configuration objects, dump a configuration status and see some system information.
+To stop Sling, just hit Ctrl-C in the console or click the Stop button on the System Information page of the Sling Management Console.

+ +

With M2Eclipse

+ +
    +
  1. Make sure you're in the Java perspective (Menu: Window->Open Perspective)
  2. +
  3. Menu: Run->Run Configurations...
  4. +
  5. In the Run Configurationa dialog right-click on "Maven Build" and select "New"
  6. +
  7. Change Name to "Build Sling"
  8. +
  9. Click "Browse Workspace..." and select "sling-builder"
  10. +
  11. Enter "clean install" in Goals
  12. +
  13. Click on the JRE tab
  14. +
  15. Enter "-Xmx256m -XX:MaxPermSize=128m" in "VM arguments"
  16. +
  17. Click Apply
  18. +
  19. Click Run
  20. +
+ + +

Alternative setup in Eclipse without M2Eclipse plugin

+ +

In the case that you do not want to use the M2Eclipse plugin there's another setup that lets you have the automatic build turned on:

+
    +
  1. Checkout the whole sling trunk (with subversive or the subclipse plugin) from SVN to a single project
  2. +
  3. Then manually add all src/main/java and src/test/java of the bundles to the project as source folders
  4. +
  5. Add all required libraries to the build path
  6. +
  7. Now you can build either in Eclipse or even better use "mvn clean install" on the command line
  8. +
+ + +

If you use "mvn clean install" to build Sling be sure you have set MAVEN_OPTS to "-Xmx384m -XX:PermSize=256m" otherwise you will probably get OutOfmemory errors.

+ +

Congratulations ! You should now have a running Sling instance, that you can start playing around with.

+ +

Further Tips and Tricks

+ + +

Debug Sling in Eclipse

+ +

You can use remote debugging to debug Sling in Eclipse, here's a little How-To

+
    +
  1. start Sling from the command line with +
    +
    java -Xmx384M -agentlib:jdwp=transport=dt_socket,address=30303,server=y,suspend=n -jar org.apache.sling.launchpad.app-6-SNAPSHOT.jar
    +
    +
  2. +
  3. Open Menu Run-> Debug configurations
  4. +
  5. Right-click on "Remote Java Applications"
  6. +
  7. Choose "New"
  8. +
  9. In the "Connect" tab choose the Eclipse Sling Project for the field "Project" with the browse button
  10. +
  11. Let the Connection type be "Standard (Socket Attach)"
  12. +
  13. The host should be localhost
  14. +
  15. Set the Port to 30303
  16. +
  17. On the source tab click the "Add" button
  18. +
  19. Select "Java Project"
  20. +
  21. Select all Sling projects and click OK
  22. +
  23. Click "Debug"
  24. +
+ + +

Now you should be able to set breakpoints, evaluate properties, and so on as usual.

+ +

Debug Maven Tests in Eclipse

+ +

In the same way as you can debug the sling app, you are also able to debug a maven test. Just run the maven tests like this

+
+
mvn -Dmaven.surefire.debug test
+
+
+ +

The tests will automatically pause and await a remote debugger on port 5005. You can then attach to the running tests using Eclipse. You can setup a "Remote Java Application" launch configuration via the menu command "Run" > "Open Debug Dialog..." (see above).
+For more information on this see the Maven Surefire Docu.

+ + +

Simple way to develop new bundle in Eclipse for Sling

+ +

The easiest way that I found is to create a new folder in the existing Eclipse workspace. After that you can follow these steps:

+
    +
  • Start by copying and adapting an existing Sling pom.xml (eg. the pom.xml from the espblog sample)
  • +
  • Generate the Eclipse project files using mvn eclipse:eclipse
  • +
  • Choose File/Import in Eclipse and select "Existing projects into workspace"
  • +
  • Now you can create, edit and compile the files in Eclipse
  • +
  • To create the bundle jar and install it, just use the command line "mvn clean install" in the project directory
  • +
  • If you have a running Sling app you can install the bundle from the command line with "mvn -P autoInstallBundle clean install -Dsling.url=http://localhost:8080/system/console"
  • +
+ + +

If adding dependencies to the poms, run mvn eclipse:eclipse again and refresh the project in Eclipse. Debugging works as described above.

+
+Last modified by cziegeler@apache.org on Thu Nov 15 08:40:16 EST 2012 +
+
+Apache Sling, Sling, Apache, the Apache feather logo, and the Apache Sling project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners. +
+
+ + + Propchange: sling/site/trunk/content/site/getting-and-building-sling.html ------------------------------------------------------------------------------ svn:eol-style = native Propchange: sling/site/trunk/content/site/getting-and-building-sling.html ------------------------------------------------------------------------------ svn:keywords = Id Propchange: sling/site/trunk/content/site/getting-and-building-sling.html ------------------------------------------------------------------------------ svn:mime-type = text/plain Added: sling/site/trunk/content/site/getting-resources-and-properties-in-sling.html URL: http://svn.apache.org/viewvc/sling/site/trunk/content/site/getting-resources-and-properties-in-sling.html?rev=1420577&view=auto ============================================================================== --- sling/site/trunk/content/site/getting-resources-and-properties-in-sling.html (added) +++ sling/site/trunk/content/site/getting-resources-and-properties-in-sling.html Wed Dec 12 09:13:50 2012 @@ -0,0 +1,178 @@ + + + + + Apache Sling - Getting Resources and Properties in Sling + + + + + +
+ +
+ + Apache + +
+
+ +
+ +

Getting Resources and Properties in Sling

+ +

The Resource is one of the central parts of Sling. Extending from JCR's Everything is Content, Sling assumes Everthing is a Resource. Thus Sling is maintaining a virtual tree of resources, which is a merger of the actual contents in the JCR Repository and resources provided by so called resource providers. By doing this Sling fits very well in the paradigm of the REST architecture.

+ +

In this article we will explore a few ways to programmatically map a resource path (String) to a resource object (Resource) and its properties in Sling, from within an OSGI service, a servlet and a JSP.

+ +

The whole game consists in first getting a ResourceResolver and then getting the Resource itself.

+ +

Within an OSGI Service/Compoment

+ +

You can access a resource through the ResourceResolverFactory service:

+ +
+
+/** @scr.reference */
+private ResourceResolverFactory resolverFactory;
+
+public void myMethod() {
+    try {
+	String resourcePath = "path/to/resource";
+    	ResourceResolver resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
+	Resource res = resourceResolver.getResource(resourcePath);
+	// do something with the resource
+	// when done, close the ResourceResolver
+	resourceResolver.close();
+    } catch (LoginException e) {
+    	// log the error
+    }
+}
+
+
+ + +

Within a Servlet

+ +

You can access the resource defined by the request URL through the SlingHttpServletRequest:

+ +
+
+Resource res = req.getResource();
+// req is the SlingHttpServletRequest
+
+
+ +

You can access any resource by first accessing the ResourceResolver:

+ +
+
+String resourcePath = "path/to/resource";
+ResourceResolver resourceResolver = req.getResourceResolver();
+// req is the SlingHttpServletRequest
+Resource res = resourceResolver.getResource(resourcePath);
+
+
+ +

Within a JSP file

+ +

When you use the <sling:defineObjects> tag in a JSP file, you have access to a few handy objects, one of them is resource, the resource that is resolved from the URL. Another one is resourceResolver, the ResourceResolver defined through the SlingHttpServletRequest.

+ +

To access a resource:

+ +
+
+<sling:defineObjects>
+<%
+String resourcePath = "path/to/resource";
+Resource res = resourceResolver.getResource(resourcePath);
+%>
+
+
+ +

If needed you can adapt a Sling Resource to a JCR Node:

+ +
+
+Node node = resource.adaptTo(Node.class);
+
+
+ +

Note: resource.adaptTo(Node.class) may return null if the resource is not backed by a JCR node. This is particularly the case for NonExistingResource resources or resource provided by a non-JCR resource provider.

+ +

Accessing a Property

+ +

The ValueMap is an easy way to access properties of a resource. With most resources you can use Adaptable.adaptTo(Class) to adapt the resource to a value map:

+ +
+
+ValueMap properties = res.adaptTo(ValueMap.class);
+// res is the Resource
+
+
+ +

You can also access the properties through the ResourceUtil utility class:

+ +
+
+ValueMap properties = ResourceUtil.getValueMap(res);
+// res is the Resource
+
+
+ +

Then, to access a specific String property called propName:

+ +
+
+String rule = properties.get(propName, (String) null);
+
+
+ +

For more details about resources and how to access them in Sling, you can refer to the Sling documentation about Resources.

+
+Last modified by jck on 2010-12-15 04:25:52.0 +
+
+Apache Sling, Sling, Apache, the Apache feather logo, and the Apache Sling project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners. +
+
+ + + Propchange: sling/site/trunk/content/site/getting-resources-and-properties-in-sling.html ------------------------------------------------------------------------------ svn:eol-style = native Propchange: sling/site/trunk/content/site/getting-resources-and-properties-in-sling.html ------------------------------------------------------------------------------ svn:keywords = Id Propchange: sling/site/trunk/content/site/getting-resources-and-properties-in-sling.html ------------------------------------------------------------------------------ svn:mime-type = text/plain Added: sling/site/trunk/content/site/getting-started.html URL: http://svn.apache.org/viewvc/sling/site/trunk/content/site/getting-started.html?rev=1420577&view=auto ============================================================================== --- sling/site/trunk/content/site/getting-started.html (added) +++ sling/site/trunk/content/site/getting-started.html Wed Dec 12 09:13:50 2012 @@ -0,0 +1,91 @@ + + + + + Apache Sling - Getting Started + + + + + +
+ +
+ + Apache + +
+
+ +
+ +

Getting Started

+ +

We're on the way to update the documentation to make it more easy to get in touch with Sling. At the moment we can give you the following starting points:

+ + + +

Where to head from here

+ +

We recommend you read through following topics to get as fast as possible into Sling:

+ + + + +
+Last modified by mykee on 2009-09-01 13:51:58.0 +
+
+Apache Sling, Sling, Apache, the Apache feather logo, and the Apache Sling project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners. +
+
+ + + Propchange: sling/site/trunk/content/site/getting-started.html ------------------------------------------------------------------------------ svn:eol-style = native Propchange: sling/site/trunk/content/site/getting-started.html ------------------------------------------------------------------------------ svn:keywords = Id Propchange: sling/site/trunk/content/site/getting-started.html ------------------------------------------------------------------------------ svn:mime-type = text/plain Added: sling/site/trunk/content/site/groovy-support.html URL: http://svn.apache.org/viewvc/sling/site/trunk/content/site/groovy-support.html?rev=1420577&view=auto ============================================================================== --- sling/site/trunk/content/site/groovy-support.html (added) +++ sling/site/trunk/content/site/groovy-support.html Wed Dec 12 09:13:50 2012 @@ -0,0 +1,142 @@ + + + + + Apache Sling - Groovy Support + + + + + +
+ +
+ + Apache + +
+
+ +
+ + + +

After meeting Paul King of the Groovy Team at Apache Con US 08 in New Orleans, I set out to take a stab at SLING-315 again to add Groovy support to Sling. It turned out, that the current Groovy 1.6 branch already contains the required setup to build the groovy-all.jar as an OSGi Bundle, which is directly usable with Sling by just installing that bundle.

+ +

Currently the Groovy team is working hard towards the 1.6 release and many things are in flux, which is really great.

+ +

So, on 11. Dec. 2008 Paul King of the Groovy Team has deployed a first RC1 Snapshot of Groovy 1.6 which contains all the required OSGi bundle manifest headers as well das the JSR-233 ScriptEngine to use the groovy-all.jar unmodified with Sling. So just go ahead, grab the Groovy-All 1.6 RC 1 SNAPSHOT deploy it into your Sling instance and enjoy the fun of Groovy.

+ +

If you want to be on verge of development, you might want to go for Groovy 1.7: The second SNAPSHOT of beta-1 also contains the required headers and classes and may as well be used unmodified in Sling. You may download it here: groovy-all-1.7-beta-1-20081210.120632-2.jar.

+ + +

To deploy the bundle go to the Bundles page, for example at http://localhost:8888/system/console/bundles of the Apache Felix Web Console select the bundle file to upload, check the Start check box and click Install or Update button.

+ +

You may check, whether the Groovy ScriptEngine has been "accepted" by Sling, by going to the Script Engines page of the Apache Felix Web Console. You should see the entry for Groovy there, somthing like this:

+ +
+
Groovy Scripting Engine, 2.0
+  Language      Groovy,
+  Extensions    groovy
+  MIME Types    application/x-groovy
+  Names         groovy, Groovy
+
+
+ + +

Testing

+ +

To test create a simple Groovy script, for example

+ +
+
+response.setContentType("text/plain");
+response.setCharacterEncoding("UTF-8");
+
+println "Hello World !"
+println "This is Groovy Speaking"
+println "You requested the Resource ${resource} (yes, this is a GString)"
+
+
+ +

and upload it to the repository as /apps/nt/folder/GET.groovy using your favourite WebDAV client or use curl to upload the file (assuming Sling is running on localhost:8888) :

+ +
+
$ curl -u admin:admin -FGET.groovy=@GET.groovy -F../../nt/jcr:primaryType=sling:Folder http:host:8888/apps/nt/folder
+
+
+ +

To test it create a /sample nt:Folder node using your favourite WebDAV client or use curl again:

+ +
+
$ curl -u admin:admin -Fjcr:primaryType=nt:folder http://localhost:8888/
+
+
+ + +

Finally, request the /sample node using your favourite Browser or use curl again:

+ +
+
$ curl http://localhost:8888/sample
+Hello World !
+This is Groovy Speaking
+You requested Resource JcrNodeResource, type=nt:folder, path=/sample (yes, this is a GString)
+
+
+ + +

References

+ +
    +
  • SLING-315 – The initial Sling issue proposing the addition of a Groovy ScriptEngine to Sling.
  • +
  • Groovy Support in Apache Sling – A short thread on turning the Groovy groovy-all.jar into an OSGi Bundle.
  • +
  • Groovy in Apache Sling – Thread on adding the DynamicImport-Package header to the Groovy bundle manifest.
  • +
+ +
+Last modified by fmeschbe on 2008-12-12 02:11:51.0 +
+
+Apache Sling, Sling, Apache, the Apache feather logo, and the Apache Sling project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners. +
+
+ + + Propchange: sling/site/trunk/content/site/groovy-support.html ------------------------------------------------------------------------------ svn:eol-style = native Propchange: sling/site/trunk/content/site/groovy-support.html ------------------------------------------------------------------------------ svn:keywords = Id Propchange: sling/site/trunk/content/site/groovy-support.html ------------------------------------------------------------------------------ svn:mime-type = text/plain Added: sling/site/trunk/content/site/guides.html URL: http://svn.apache.org/viewvc/sling/site/trunk/content/site/guides.html?rev=1420577&view=auto ============================================================================== --- sling/site/trunk/content/site/guides.html (added) +++ sling/site/trunk/content/site/guides.html Wed Dec 12 09:13:50 2012 @@ -0,0 +1,97 @@ + + + + + Apache Sling - Guides + + + + + +
+ +
+ + Apache + +
+
+ +
+ +

These pages contain further information in a more informal way.

+ + + + +
    +
  • Resources – Presents the Resource as the object around which Sling is built
  • +
  • Servlet Resolution – How Sling resolves the servlet or script responsible for rendering a Resource.
  • +
  • Request Parameters – Explains how Sling provides request parameters to servlets, scripts and filters.
  • +
  • Repository Based Development – Shows how WebDAV is supported by Sling.
  • +
+ + +
    +
  • Bundle Management – Explains how to install, upgrade and uninstall Bundles using the Sling Management console.
  • +
+ + + +

These pages refer to the old Component API and launcher, and remain referred to here until more up to date documentation has been prepared:

+ +
    +
  • Getting and Building Sling – A short recount on the first step for getting a running Sling instance after checking out the source from the SVN repository
  • +
  • Default Mapping and Rendering – Explains default mapping of repository nodes to Content instances and selection of a default Component.
  • +
  • Dispatching Requests – Explains how a Component may dispatch requests to include further content renderings in the response to the client's request
  • +
+ +
+Last modified by fmeschbe on 2008-02-13 07:38:21.0 +
+
+Apache Sling, Sling, Apache, the Apache feather logo, and the Apache Sling project logo are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners. +
+
+ + + Propchange: sling/site/trunk/content/site/guides.html ------------------------------------------------------------------------------ svn:eol-style = native Propchange: sling/site/trunk/content/site/guides.html ------------------------------------------------------------------------------ svn:keywords = Id Propchange: sling/site/trunk/content/site/guides.html ------------------------------------------------------------------------------ svn:mime-type = text/plain Added: sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxEventHandler.java URL: http://svn.apache.org/viewvc/sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxEventHandler.java?rev=1420577&view=auto ============================================================================== --- sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxEventHandler.java (added) +++ sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxEventHandler.java Wed Dec 12 09:13:50 2012 @@ -0,0 +1,92 @@ + +package mypackage; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import org.apache.sling.api.resource.Resource; +import org.apache.sling.api.resource.ResourceResolver; +import org.apache.sling.api.resource.ResourceUtil; +import org.apache.sling.event.EventUtil; +import org.apache.sling.event.JobProcessor; +import org.apache.sling.jcr.api.SlingRepository; +import org.apache.sling.jcr.resource.JcrResourceResolverFactory; +import org.osgi.service.event.Event; +import org.osgi.service.event.EventHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The DropBoxEventHandler moves files posted to /tmp/dropbox to the appropriate locations: + * images (MIME type: image/png) to /dropbox/images/ + * music (MIME type: audio/mpeg) to /dropbox/music/ + * movies (MIME type: video/x-msvideo) to /dropbox/movies/ + * otherwise to /dropbox/other/ + * + * @scr.component immediate="true" + * @scr.service interface="org.osgi.service.event.EventHandler" + * @scr.property name="event.topics" valueRef="mypackage.DropBoxService.JOB_TOPIC" + */ + +public class DropBoxEventHandler implements JobProcessor, EventHandler { + + /** Default log. */ + protected final Logger log = LoggerFactory.getLogger(this.getClass()); + + /** @scr.reference */ + private SlingRepository repository; + + /** + * @scr.reference + */ + private JcrResourceResolverFactory resolverFactory; + + private final static String IMAGES_PATH = "/dropbox/images/"; + private final static String MUSIC_PATH = "/dropbox/music/"; + private final static String MOVIES_PATH = "/dropbox/movies/"; + private final static String OTHER_PATH = "/dropbox/other/"; + + public void handleEvent(Event event) { + if (EventUtil.isLocal(event)) { + EventUtil.processJob(event, this); + } + } + + public boolean process(Event event) { + Session adminSession = null; + try { + String resourcePath = (String) event.getProperty("resourcePath"); + String resourceName = resourcePath.substring(resourcePath.lastIndexOf("/") + 1); + adminSession = repository.loginAdministrative(null); + ResourceResolver resourceResolver = resolverFactory.getResourceResolver(adminSession); + Resource res = resourceResolver.getResource(resourcePath); + if (ResourceUtil.isA(res, "nt:file")) { + String mimeType = res.getResourceMetadata().getContentType(); + String destDir; + if (mimeType.equals("image/png")) { + destDir = IMAGES_PATH; + } + else if (mimeType.equals("audio/mpeg")) { + destDir = MUSIC_PATH; + } + else if (mimeType.equals("video/x-msvideo")) { + destDir = MOVIES_PATH; + } + else { + destDir = OTHER_PATH; + } + adminSession.move(resourcePath, destDir + resourceName); + adminSession.save(); + log.info("The file {} has been moved to {}", resourceName, destDir); + } + return true; + } catch (RepositoryException e) { + log.error("RepositoryException: " + e); + return false; + } finally { + if (adminSession != null && adminSession.isLive()) { + adminSession.logout(); + adminSession = null; + } + } + } +} Propchange: sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxEventHandler.java ------------------------------------------------------------------------------ svn:eol-style = native Propchange: sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxEventHandler.java ------------------------------------------------------------------------------ svn:keywords = author date id revision rev url Propchange: sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxEventHandler.java ------------------------------------------------------------------------------ svn:mime-type = text/plain Added: sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxService.java URL: http://svn.apache.org/viewvc/sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxService.java?rev=1420577&view=auto ============================================================================== --- sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxService.java (added) +++ sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxService.java Wed Dec 12 09:13:50 2012 @@ -0,0 +1,57 @@ + +package mypackage; + +import java.util.Dictionary; +import java.util.Hashtable; + +import org.apache.sling.api.SlingConstants; +import org.apache.sling.event.EventUtil; +import org.apache.sling.event.JobProcessor; +import org.osgi.service.event.Event; +import org.osgi.service.event.EventAdmin; +import org.osgi.service.event.EventHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The DropBoxService is listening content added to /tmp/dropbox by using OSGI events + * + * @scr.component immediate="true" + * @scr.service interface="org.osgi.service.event.EventHandler" + * @scr.property name="event.topics" valueRef="org.apache.sling.api.SlingConstants.TOPIC_RESOURCE_ADDED" + */ +public class DropBoxService implements JobProcessor, EventHandler { + + /** Default log. */ + protected final Logger log = LoggerFactory.getLogger(this.getClass()); + + /** + * The OSGI event admin used for sending events + * @scr.reference + */ + private EventAdmin eventAdmin; + + /** The job topic for dropbox job events. */ + public static final String JOB_TOPIC = "com/sling/eventing/dropbox/job"; + + public void handleEvent(Event event) { + if (EventUtil.isLocal(event)) { + EventUtil.processJob(event, this); + } + } + + public boolean process(Event event) { + String propPath = (String) event.getProperty(SlingConstants.PROPERTY_PATH); + String propResType = (String) event.getProperty(SlingConstants.PROPERTY_RESOURCE_TYPE); + // an event is sent if a file is added to /tmp/dropbox + if (propPath.startsWith("/tmp/dropbox") && propResType.equals("nt:file")) { + final Dictionary props = new Hashtable(); + props.put(EventUtil.PROPERTY_JOB_TOPIC, JOB_TOPIC); + props.put("resourcePath", propPath); + Event dropboxJobEvent = new Event(EventUtil.TOPIC_JOB, props); + eventAdmin.sendEvent(dropboxJobEvent); + log.info("the dropbox job has been sent: {}", propPath); + } + return true; + } +} Propchange: sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxService.java ------------------------------------------------------------------------------ svn:eol-style = native Propchange: sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxService.java ------------------------------------------------------------------------------ svn:keywords = author date id revision rev url Propchange: sling/site/trunk/content/site/how-to-manage-events-in-sling.data/DropBoxService.java ------------------------------------------------------------------------------ svn:mime-type = text/plain