http://git-wip-us.apache.org/repos/asf/sling-site/blob/53c84cf9/content/documentation/bundles/scripting/scripting-htl.md ---------------------------------------------------------------------- diff --git a/content/documentation/bundles/scripting/scripting-htl.md b/content/documentation/bundles/scripting/scripting-htl.md index 2677a67..d2fb980 100644 --- a/content/documentation/bundles/scripting/scripting-htl.md +++ b/content/documentation/bundles/scripting/scripting-htl.md @@ -1,7 +1,10 @@ -title=HTL Scripting Engine -type=page +title=TODO title for scripting-htl.md +date=1900-01-01 +type=post +tags=blog status=published ~~~~~~ +Title: HTL Scripting Engine The Apache Sling HTL Scripting Engine, [formerly known as Sightly](https://issues.apache.org/jira/browse/SLING-6028), is the reference implementation of the [HTML Template Language](https://github.com/Adobe-Marketing-Cloud/htl-spec). @@ -25,33 +28,33 @@ The [HTML Template Language Specification](https://github.com/Adobe-Marketing-Cl 1. Java Use-API, through POJOs, that may optionally implement an `init` method: -/** -* Initialises the Use bean. -* -* @param bindings All bindings available to the HTL scripts. -**/ -public void init(javax.script.Bindings bindings); + /** + * Initialises the Use bean. + * + * @param bindings All bindings available to the HTL scripts. + **/ + public void init(javax.script.Bindings bindings); 2. JavaScript Use-API, by using a standardised use function -/** -* In the following example '/libs/dep1.js' and 'dep2.js' are optional -* dependencies needed for this script's execution. Dependencies can -* be specified using an absolute path or a relative path to this -* script's own path. -* -* If no dependencies are needed the dependencies array can be omitted. -*/ -use(['dep1.js', 'dep2.js'], function (Dep1, Dep2) { -// implement processing - -// define this Use object's behaviour -return { -propertyName: propertyValue -functionName: function () {} -} -}); + /** + * In the following example '/libs/dep1.js' and 'dep2.js' are optional + * dependencies needed for this script's execution. Dependencies can + * be specified using an absolute path or a relative path to this + * script's own path. + * + * If no dependencies are needed the dependencies array can be omitted. + */ + use(['dep1.js', 'dep2.js'], function (Dep1, Dep2) { + // implement processing + + // define this Use object's behaviour + return { + propertyName: propertyValue + functionName: function () {} + } + }); The HTL implementation from Sling provides the basic POJO support through the [`org.apache.sling.scripting.sightly.pojo.Use`](https://github.com/apache/sling/blob/trunk/bundles/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/pojo/Use.java) interface and the [`JavaUseProvider`](https://github.com/apache/sling/blob/trunk/bundles/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/JavaUseProvider.java), whereas the `use` function is implemented by the `org.apache.sling.scripting.sightly.js.provider` bundle. @@ -75,25 +78,25 @@ The `service.ranking` value of each Use Provider is configurable, allowing for f The following global objects are available to all Use objects, either as a request attribute or as a property made available in the `javax.script.Bindings` map or attached to the `this` context of the `use` function: -currentNode // javax.jcr.Node -currentSession // javax.jcr.Session -log // org.slf4j.Logger -out // java.io.PrintWriter -properties // org.apache.sling.api.resource.ValueMap -reader // java.io.BufferedReader -request // org.apache.sling.api.SlingHttpServletRequest -resolver // org.apache.sling.api.resource.ResourceResolver -resource // org.apache.sling.api.resource.Resource -response // org.apache.sling.api.SlingHttpServletResponse -sling // org.apache.sling.api.scripting.SlingScriptHelper + currentNode // javax.jcr.Node + currentSession // javax.jcr.Session + log // org.slf4j.Logger + out // java.io.PrintWriter + properties // org.apache.sling.api.resource.ValueMap + reader // java.io.BufferedReader + request // org.apache.sling.api.SlingHttpServletRequest + resolver // org.apache.sling.api.resource.ResourceResolver + resource // org.apache.sling.api.resource.Resource + response // org.apache.sling.api.SlingHttpServletResponse + sling // org.apache.sling.api.scripting.SlingScriptHelper ### Sling Models Use Provider Loading a Sling Model can be done with the following code: -<div data-sly-use.model3="org.example.models.Model3"> -${model3.shine} -</div> + <div data-sly-use.model3="org.example.models.Model3"> + ${model3.shine} + </div> Depending on the implementation the above code would either load the implementation with the highest service ranking of `Model3` if `org.example.models.Model3` is an interface, or would load the model `org.example.models.Model3` if this is a concrete implementation. @@ -103,21 +106,21 @@ It's important to note that this use provider will only load models that are ada Passed parameters will be made available to the Sling Model as request attributes. Assuming the following markup: -<div data-sly-use.model3="${'org.example.models.Model3' @ colour='red', path=resource.path}"> -${model3.shine} -</div> + <div data-sly-use.model3="${'org.example.models.Model3' @ colour='red', path=resource.path}"> + ${model3.shine} + </div> the model would retrieve the parameters using the following constructs: -@Model(adaptables=SlingHttpServletRequest.class) -public class Model3 { + @Model(adaptables=SlingHttpServletRequest.class) + public class Model3 { -@Inject -private String colour; + @Inject + private String colour; -@Inject -private String path; -} + @Inject + private String path; + } ### Java Use Provider The Java Use Provider can be used to load OSGi services, objects exported by bundles or backed by a `Resource`. @@ -129,99 +132,99 @@ When objects are backed by `Resources` the Java Use Provider will automatically **Example:** Assuming the following content structure: -âââ apps -âââ my-project -âââ components -âââ page -âââ PageBean.java -âââ page.html + âââ apps + âââ my-project + âââ components + âââ page + âââ PageBean.java + âââ page.html `page.html` could load `PageBean` either like: -<!DOCTYPE html> -<html data-sly-use.page="apps.my_project.components.page.PageBean"> -... -</html> + <!DOCTYPE html> + <html data-sly-use.page="apps.my_project.components.page.PageBean"> + ... + </html> or like: -<!DOCTYPE html> -<html data-sly-use.page="PageBean"> -... -</html> + <!DOCTYPE html> + <html data-sly-use.page="PageBean"> + ... + </html> The advantage of loading a bean using just the simple class name (e.g. `data-sly-use.page="PageBean"`) is that an inheriting component can overlay the `PageBean.java` file and provide a different logic. In this case the package name of the `PageBean` class will automatically be derived from the calling script's parent path (e.g. `apps.my_project.components.page`) - the bean doesn't even have to specify it. However, keep in mind that loading a bean this way is slower than providing the fully qualified class name, since the provider has to check if there is a backing resource. At the same time, loading an object using its fully qualified class name will not allow overriding it by inheriting components. #### Passing parameters Passed parameters will be made available to the Use object as request attributes and, if the object implements the [`org.apache.sling.scripting.sightly.pojo.Use`](https://github.com/apache/sling/blob/trunk/bundles/scripting/sightly/engine/src/main/java/org/apache/sling/scripting/sightly/pojo/Use.java) interface, through the `javax.script.Bindings` passed to the `init` method. Assuming the following markup: -<div data-sly-use.useObject="${'org.example.use.MyUseObject' @ colour='red', year=2016}"> -${useObject.shine} -</div> + <div data-sly-use.useObject="${'org.example.use.MyUseObject' @ colour='red', year=2016}"> + ${useObject.shine} + </div> the object implementing `Use` would be able to retrieve the parameters using the following constructs: -package org.example.use.MyUseObject; + package org.example.use.MyUseObject; -import javax.script.Bindings; + import javax.script.Bindings; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.scripting.sightly.pojo.Use; + import org.apache.sling.commons.osgi.PropertiesUtil; + import org.apache.sling.scripting.sightly.pojo.Use; -public class MyUseObject implements Use { + public class MyUseObject implements Use { -private String colour; -private Integer year; + private String colour; + private Integer year; -public void init(Bindings bindings) { -colour = PropertiesUtil.toString(bindings.get("colour"), ""); -year = PropertiesUtil.toInteger(bindings.get("year"), Calendar.getInstance().get(Calendar.YEAR)); -} -} + public void init(Bindings bindings) { + colour = PropertiesUtil.toString(bindings.get("colour"), ""); + year = PropertiesUtil.toInteger(bindings.get("year"), Calendar.getInstance().get(Calendar.YEAR)); + } + } or, if the object is adaptable from a `SlingHttpServletRequest`, through its `AdapterFactory`: -package org.example.use; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Properties; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.adapter.AdapterFactory; - -@Component -@Service -@Properties({ -@Property( -name = AdapterFactory.ADAPTABLE_CLASSES, -value = { -"org.apache.sling.api.SlingHttpServletRequest" -} -), -@Property( -name = AdapterFactory.ADAPTER_CLASSES, -value = { -"org.example.use.MyUseObject" -} -) -}) -public class RequestAdapterFactory implements AdapterFactory { - -@Override -public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) { -if (type == MyUseObject.class && adaptable instanceof SlingHttpServletRequest) { -SlingHttpServletRequest request = (SlingHttpServletRequest) adaptable; -String colour = PropertiesUtil.toString(request.getAttribute("colour"), ""); -Integer year = PropertiesUtil.toInteger(request.getAttribute("year"), Calendar.getInstance().get(Calendar.YEAR)); -/* -* for the sake of this example we assume that MyUseObject has this constructor -*/ -return (AdapterType) new MyUseObject(colour, year); -} -return null; -} -} + package org.example.use; + + import org.apache.felix.scr.annotations.Component; + import org.apache.felix.scr.annotations.Properties; + import org.apache.felix.scr.annotations.Property; + import org.apache.felix.scr.annotations.Service; + import org.apache.sling.api.SlingHttpServletRequest; + import org.apache.sling.api.adapter.AdapterFactory; + + @Component + @Service + @Properties({ + @Property( + name = AdapterFactory.ADAPTABLE_CLASSES, + value = { + "org.apache.sling.api.SlingHttpServletRequest" + } + ), + @Property( + name = AdapterFactory.ADAPTER_CLASSES, + value = { + "org.example.use.MyUseObject" + } + ) + }) + public class RequestAdapterFactory implements AdapterFactory { + + @Override + public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) { + if (type == MyUseObject.class && adaptable instanceof SlingHttpServletRequest) { + SlingHttpServletRequest request = (SlingHttpServletRequest) adaptable; + String colour = PropertiesUtil.toString(request.getAttribute("colour"), ""); + Integer year = PropertiesUtil.toInteger(request.getAttribute("year"), Calendar.getInstance().get(Calendar.YEAR)); + /* + * for the sake of this example we assume that MyUseObject has this constructor + */ + return (AdapterType) new MyUseObject(colour, year); + } + return null; + } + } ### JavaScript Use Provider The JavaScript Use Provider allows loading objects created through the `use` function, by evaluating scripts passed to `data-sly-use`. The JavaScript files are evaluated server-side by the [Rhino](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino) scripting engine, through the `org.apache.sling.scripting.javascript` implementation bundle. This allows you to mix JavaScript API with the Java API exported by the platform. For more details about how you can access Java APIs from within JavaScript please check the [Rhino Java Scripting guide](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Scripting_Java#Accessing_Java_Packages_and_Classes). @@ -229,63 +232,63 @@ The JavaScript Use Provider allows loading objects created through the `use` fun **Example:** Assuming the following content structure: -âââ apps -âââ my-project -âââ components -âââ page -âââ page.html -âââ page.js + âââ apps + âââ my-project + âââ components + âââ page + âââ page.html + âââ page.js `page.html` could load `page.js` either like: -<!DOCTYPE html> -<html data-sly-use.page="/apps/my-project/components/page/page.js"> -... -</html> + <!DOCTYPE html> + <html data-sly-use.page="/apps/my-project/components/page/page.js"> + ... + </html> or like: -<!DOCTYPE html> -<html data-sly-use.page="page.js"> -... -</html> + <!DOCTYPE html> + <html data-sly-use.page="page.js"> + ... + </html> Similar to the Java Use Provider, loading the script using a relative path allows inheriting components to overlay just the Use script, without having to also overlay the calling HTL script. #### Global Objects Besides the global objects available to all Use Providers, the JavaScript Use Provider also provides the following global objects available in the context of the `use` function: -console // basic wrapper on top of log, but without formatting / throwable support -exports // basic Java implementation of CommonJS - http://requirejs.org/docs/commonjs.html -module // basic Java implementation of CommonJS - http://requirejs.org/docs/commonjs.html -setImmediate // Java implementation of the Node.js setImmediate function -setTimeout // Java implementation of the Node.js setTimeout function -sightly // the namespace object under which the asynchronous Resource-API implemented by -// org.apache.sling.scripting.sightly.js.provider is made available to consumers -use // the use function + console // basic wrapper on top of log, but without formatting / throwable support + exports // basic Java implementation of CommonJS - http://requirejs.org/docs/commonjs.html + module // basic Java implementation of CommonJS - http://requirejs.org/docs/commonjs.html + setImmediate // Java implementation of the Node.js setImmediate function + setTimeout // Java implementation of the Node.js setTimeout function + sightly // the namespace object under which the asynchronous Resource-API implemented by + // org.apache.sling.scripting.sightly.js.provider is made available to consumers + use // the use function With the exception of the `console` and `use` objects, all the other global objects implemented by the JavaScript Use Provider are present in order to support the asynchronous Resource-API implemented by `org.apache.sling.scripting.sightly.js.provider`. However, this was deprecated starting with version 1.0.8 - see [SLING-4964](https://issues.apache.org/jira/browse/SLING-4964). #### Passing parameters Passed parameters will be made available to the Use object as properties of `this`. Assuming the following markup: -<div data-sly-use.logic="${'logic.js' @ colour='red', year=2017}"> -My colour is ${logic.colour ? logic.colour : 'not important'} and I'm from ${logic.year} -</div> + <div data-sly-use.logic="${'logic.js' @ colour='red', year=2017}"> + My colour is ${logic.colour ? logic.colour : 'not important'} and I'm from ${logic.year} + </div> the object would be able to access the parameters like: -use(function() { -'use strict'; + use(function() { + 'use strict'; -var colour = this.colour || ''; -var year = this.year || new Date().getFullYear(); + var colour = this.colour || ''; + var year = this.year || new Date().getFullYear(); -return { -colour: colour, -year: year -} -}); + return { + colour: colour, + year: year + } + }); #### Caveats @@ -293,96 +296,96 @@ Since these scripts are evaluated server-side, by compiling JavaScript to Java, Assuming the following HTL script: -<ol data-sly-use.obj="logic.js" data-sly-list="${obj}"> -<li> -Code <code>${item.code}</code> evaluates to <code>${item.result}</code> -</li> -</ol> + <ol data-sly-use.obj="logic.js" data-sly-list="${obj}"> + <li> + Code <code>${item.code}</code> evaluates to <code>${item.result}</code> + </li> + </ol> and the following JavaScript file: -use(function() { - -return [ -{ -code: 'new java.lang.String("apples") === "apples"', -result: new java.lang.String("apples") === "apples" -}, -{ -code: 'new java.lang.String("apples") == "apples"', -result: new java.lang.String("apples") == "apples" -}, -{ -code: 'new java.lang.String("apples") !== "apples"', -result: new java.lang.String("apples") !== "apples" -}, -{ -code: 'new java.lang.String("apples") != "apples"', -result: new java.lang.String("apples") != "apples" -}, -{ -code: 'new java.lang.Integer(1) === 1', -result: new java.lang.Integer(1) === 1 -}, -{ -code: 'new java.lang.Integer(1) == 1', -result: new java.lang.Integer(1) == 1 -}, -{ -code: 'new java.lang.Integer(1) !== 1', -result: new java.lang.Integer(1) !== 1 -}, -{ -code: 'new java.lang.Integer(1) != 1', -result: new java.lang.Integer(1) != 1 -}, -{ -code: 'java.lang.Boolean.TRUE === true', -result: java.lang.Boolean.TRUE === true -}, -{ -code: 'java.lang.Boolean.TRUE == true', -result: java.lang.Boolean.TRUE == true -}, -{ -code: 'java.lang.Boolean.TRUE !== true', -result: java.lang.Boolean.TRUE !== true -}, -{ -code: 'java.lang.Boolean.TRUE != true', -result: java.lang.Boolean.TRUE != true -} -]; -}); + use(function() { + + return [ + { + code: 'new java.lang.String("apples") === "apples"', + result: new java.lang.String("apples") === "apples" + }, + { + code: 'new java.lang.String("apples") == "apples"', + result: new java.lang.String("apples") == "apples" + }, + { + code: 'new java.lang.String("apples") !== "apples"', + result: new java.lang.String("apples") !== "apples" + }, + { + code: 'new java.lang.String("apples") != "apples"', + result: new java.lang.String("apples") != "apples" + }, + { + code: 'new java.lang.Integer(1) === 1', + result: new java.lang.Integer(1) === 1 + }, + { + code: 'new java.lang.Integer(1) == 1', + result: new java.lang.Integer(1) == 1 + }, + { + code: 'new java.lang.Integer(1) !== 1', + result: new java.lang.Integer(1) !== 1 + }, + { + code: 'new java.lang.Integer(1) != 1', + result: new java.lang.Integer(1) != 1 + }, + { + code: 'java.lang.Boolean.TRUE === true', + result: java.lang.Boolean.TRUE === true + }, + { + code: 'java.lang.Boolean.TRUE == true', + result: java.lang.Boolean.TRUE == true + }, + { + code: 'java.lang.Boolean.TRUE !== true', + result: java.lang.Boolean.TRUE !== true + }, + { + code: 'java.lang.Boolean.TRUE != true', + result: java.lang.Boolean.TRUE != true + } + ]; + }); the output would be: -1. Code new java.lang.String("apples") === "apples" evaluates to false -2. Code new java.lang.String("apples") == "apples" evaluates to true -3. Code new java.lang.String("apples") !== "apples" evaluates to true -4. Code new java.lang.String("apples") != "apples" evaluates to false -5. Code new java.lang.Integer(1) === 1 evaluates to false -6. Code new java.lang.Integer(1) == 1 evaluates to true -7. Code new java.lang.Integer(1) !== 1 evaluates to true -8. Code new java.lang.Integer(1) != 1 evaluates to false -9. Code java.lang.Boolean.TRUE === true evaluates to false -10. Code java.lang.Boolean.TRUE == true evaluates to true -11. Code java.lang.Boolean.TRUE !== true evaluates to true -12. Code java.lang.Boolean.TRUE != true evaluates to false + 1. Code new java.lang.String("apples") === "apples" evaluates to false + 2. Code new java.lang.String("apples") == "apples" evaluates to true + 3. Code new java.lang.String("apples") !== "apples" evaluates to true + 4. Code new java.lang.String("apples") != "apples" evaluates to false + 5. Code new java.lang.Integer(1) === 1 evaluates to false + 6. Code new java.lang.Integer(1) == 1 evaluates to true + 7. Code new java.lang.Integer(1) !== 1 evaluates to true + 8. Code new java.lang.Integer(1) != 1 evaluates to false + 9. Code java.lang.Boolean.TRUE === true evaluates to false + 10. Code java.lang.Boolean.TRUE == true evaluates to true + 11. Code java.lang.Boolean.TRUE !== true evaluates to true + 12. Code java.lang.Boolean.TRUE != true evaluates to false Evaluations of Java objects in JavaScript constructs where the operand is automatically type coerced will work, but Rhino might complain about the Java objects not correctly calling the Rhino helper function `Context.javaToJS()`. In order to avoid these warnings it's better to explicitly perform your comparisons like in the following example: -if (myObject) { -... -} -// should be replaced by -if (myObject != null) { -... -} + if (myObject) { + ... + } + // should be replaced by + if (myObject != null) { + ... + } -myObject ? 'this' : 'that' -//should be replaced by -myObject != null ? 'this' : 'that' + myObject ? 'this' : 'that' + //should be replaced by + myObject != null ? 'this' : 'that' ### Script Use Provider @@ -392,71 +395,71 @@ The Script Use Provider allows loading objects evaluated by other script engines The following table summarises the pros and cons for each Use Provider, with the obvious exception of the Render Unit Use Provider. <table> -<tr> -<th>Use Provider</th> -<th>Advantages</th> -<th>Disadvantages</th> -</tr> -<tr> -<td>Sling Models Use Provider</td> -<td><ul><li>convenient injection annotations for data retrieval</li><li>easy to extend from other Sling Models</li><li>simple setup for unit testing</li></ul></td> -<td><ul><li>lacks flexibility in terms of component overlaying, relying on <code>service.ranking</code> configurations; this was solved for Sling Models 1.3.0 by <a href="https://issues.apache.org/jira/browse/SLING-5992">SLING-5992</a></li></ul></td> -</tr> -<tr> -<td>Java Use Provider</td> -<td> -<p>Use-objects provided through bundles:</p> -<ul> -<li>faster to initialise and execute than Sling Models for similar code</li> -<li>easy to extend from other similar Use-objects</li> -<li>simple setup for unit testing</li> -</ul> -<p>Use-objects backed by <code>Resources</code>:</p> -<ul> -<li>faster to initialise and execute than Sling Models for similar code</li> -<li>easy to override from inheriting components through search path overlay or by using the <code>sling:resourceSuperType</code> property, allowing for greater flexibility</li> -<li>business logic for components sits next to the HTL scripts where the objects are used</li> -</ul> -</td> -<td> -<p>Use-objects provided through bundles:</p> -<ul> -<li>lacks flexibility in terms of component overlaying</li> -</ul> - -<p>Use-objects backed by <code>Resources</code>:</p> -<ul> -<li>cannot extend other Java objects</li> -<li>the Java project might need a different setup to allow running unit tests, since the objects will be deployed like content</li> -</ul> -</td> -</tr> -<tr> -<td>JavaScript Use Provider</td> -<td> -<ul> -<li>allows JavaScript developers to develop component logic</li> -<li>can be reused through the dependency mechanism provided by the <code>use</code> function</li> -</ul> -</td> -<td> -<ul> -<li>harder to test and debug, relying mostly on end-to-end testing and console logging</li> -<li>slower to execute than both Sling Models and Java Use-API objects</li> -</ul> -</td> -</tr> -<tr> -<td>Script Use Provider</td> -<td> -<ul> -<li>allows the usage of Use objects evaluated by other Script Engines available in the platform</li> -</ul> -</td> -<td> -<ul> -<li>like in the case of the JavaScript Use Provider, the performance is influenced by the Script Engine's implementation</li> -</ul> -</td> -</tr> + <tr> + <th>Use Provider</th> + <th>Advantages</th> + <th>Disadvantages</th> + </tr> + <tr> + <td>Sling Models Use Provider</td> + <td><ul><li>convenient injection annotations for data retrieval</li><li>easy to extend from other Sling Models</li><li>simple setup for unit testing</li></ul></td> + <td><ul><li>lacks flexibility in terms of component overlaying, relying on <code>service.ranking</code> configurations; this was solved for Sling Models 1.3.0 by <a href="https://issues.apache.org/jira/browse/SLING-5992">SLING-5992</a></li></ul></td> + </tr> + <tr> + <td>Java Use Provider</td> + <td> + <p>Use-objects provided through bundles:</p> + <ul> + <li>faster to initialise and execute than Sling Models for similar code</li> + <li>easy to extend from other similar Use-objects</li> + <li>simple setup for unit testing</li> + </ul> + <p>Use-objects backed by <code>Resources</code>:</p> + <ul> + <li>faster to initialise and execute than Sling Models for similar code</li> + <li>easy to override from inheriting components through search path overlay or by using the <code>sling:resourceSuperType</code> property, allowing for greater flexibility</li> + <li>business logic for components sits next to the HTL scripts where the objects are used</li> + </ul> + </td> + <td> + <p>Use-objects provided through bundles:</p> + <ul> + <li>lacks flexibility in terms of component overlaying</li> + </ul> + + <p>Use-objects backed by <code>Resources</code>:</p> + <ul> + <li>cannot extend other Java objects</li> + <li>the Java project might need a different setup to allow running unit tests, since the objects will be deployed like content</li> + </ul> + </td> + </tr> + <tr> + <td>JavaScript Use Provider</td> + <td> + <ul> + <li>allows JavaScript developers to develop component logic</li> + <li>can be reused through the dependency mechanism provided by the <code>use</code> function</li> + </ul> + </td> + <td> + <ul> + <li>harder to test and debug, relying mostly on end-to-end testing and console logging</li> + <li>slower to execute than both Sling Models and Java Use-API objects</li> + </ul> + </td> + </tr> + <tr> + <td>Script Use Provider</td> + <td> + <ul> + <li>allows the usage of Use objects evaluated by other Script Engines available in the platform</li> + </ul> + </td> + <td> + <ul> + <li>like in the case of the JavaScript Use Provider, the performance is influenced by the Script Engine's implementation</li> + </ul> + </td> + </tr> </table>
http://git-wip-us.apache.org/repos/asf/sling-site/blob/53c84cf9/content/documentation/bundles/scripting/scripting-jsp.md ---------------------------------------------------------------------- diff --git a/content/documentation/bundles/scripting/scripting-jsp.md b/content/documentation/bundles/scripting/scripting-jsp.md index 5c5bc93..3d4e610 100644 --- a/content/documentation/bundles/scripting/scripting-jsp.md +++ b/content/documentation/bundles/scripting/scripting-jsp.md @@ -1,24 +1,27 @@ -title=JSP Scripting Engine -type=page +title=TODO title for scripting-jsp.md +date=1900-01-01 +type=post +tags=blog status=published ~~~~~~ +Title: JSP Scripting Engine The Apache Sling JSP Scripting Engine is implemented by the [`org.apache.sling.scripting.jsp`](https://github.com/apache/sling/tree/trunk/bundles/scripting/jsp) -bundle, based on the Jasper 2 JSP engine. + bundle, based on the Jasper 2 JSP engine. On top of that Apache Sling also provides its own JSP Taglib, implemented by the -[`org.apache.sling.scripting.jsp.taglib`](https://github.com/apache/sling/tree/trunk/bundles/scripting/jsp-taglib) bundle. + [`org.apache.sling.scripting.jsp.taglib`](https://github.com/apache/sling/tree/trunk/bundles/scripting/jsp-taglib) bundle. The Sling Scripting JSP Taglib supports the use of Sling as an application in JSP pages. The Sling Taglib provides the -ability to invoke JSP scripts, include Resources and interact with the Sling Repository, all with JSP tags and -[Expression Language (EL)](http://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html) functions. + ability to invoke JSP scripts, include Resources and interact with the Sling Repository, all with JSP tags and + [Expression Language (EL)](http://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html) functions. ## Use Using the Sling Taglib in a JSP page is as simple as including the Taglib include in your JSP, with the correct URI for the version of the Sling Taglib installed. -<%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling" %> + <%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling" %> Generally, the prefix to use is `sling`. Often applications include a global JSP file which includes the Sling Taglib and sets up all of the application variables and methods. @@ -51,13 +54,13 @@ Adapts an Adaptable to another class. * Returns: `java.lang.Object` * Accepts: -* `org.apache.sling.api.adapter.Adaptable` - The object to adapt -* `java.lang.String` - The name of the class to which to adapt the adaptable + * `org.apache.sling.api.adapter.Adaptable` - The object to adapt + * `java.lang.String` - The name of the class to which to adapt the adaptable * Since: 1.3 *Example Usage* -<c:set var="myProperties" value="${sling:adaptTo(resource,'org.apache.sling.api.resource.ValueMap')}" /> + <c:set var="myProperties" value="${sling:adaptTo(resource,'org.apache.sling.api.resource.ValueMap')}" /> ### encode @@ -65,13 +68,13 @@ Writes properly Cross Site Scripting (XSS) encoded text to the response using th * Returns: `java.util.String` - An encoded text * Accepts: -* `java.lang.String` - The text to encode -* `java.lang.String` - The encoding mode, one of HTML, HTML_ATTR, XML, XML_ATTR, JS + * `java.lang.String` - The text to encode + * `java.lang.String` - The encoding mode, one of HTML, HTML_ATTR, XML, XML_ATTR, JS * Since: 1.4 *Example Usage* -${sling:encode('<script>alert("Bad Stuff!");</script>','HTML')} + ${sling:encode('<script>alert("Bad Stuff!");</script>','HTML')} ### findResources @@ -79,16 +82,16 @@ Searches for resources using the given query formulated in the given language. * Returns: `java.util.Iterator` - An Iterator of Resource objects matching the query. * Accepts: -* `org.apache.sling.api.resource.ResourceResolver` - The Resource Resolver to use for the query. -* `java.lang.String` - The query string to use to find the resources. -* `java.lang.String` - The language in which the query is formulated. + * `org.apache.sling.api.resource.ResourceResolver` - The Resource Resolver to use for the query. + * `java.lang.String` - The query string to use to find the resources. + * `java.lang.String` - The language in which the query is formulated. * Since: 1.3 *Example Usage* -<c:forEach var="found" items="${sling:findResources(resourceResolver,'/jcr:root//*[jcr:contains(., 'Sling')] order by @jcr:score','xpath')"> -<li>${found.path}</li> -</c:forEach> + <c:forEach var="found" items="${sling:findResources(resourceResolver,'/jcr:root//*[jcr:contains(., 'Sling')] order by @jcr:score','xpath')"> + <li>${found.path}</li> + </c:forEach> ### getRelativeResource @@ -96,13 +99,13 @@ Gets the resource at the relative path to the provided resource. * Returns: `org.apache.sling.api.resource.Resource` - The resource at the relative path. * Accepts: -* `org.apache.sling.api.resource.Resource` - The resource relative to which to find the path. -* `java.lang.String` - The relative path at which to find the resource. + * `org.apache.sling.api.resource.Resource` - The resource relative to which to find the path. + * `java.lang.String` - The relative path at which to find the resource. * Since: 1.3 *Example Usage* -<c:set var="content" value="${sling:getRelativeResource(resource,'jcr:content')}" /> + <c:set var="content" value="${sling:getRelativeResource(resource,'jcr:content')}" /> ### getResource @@ -110,13 +113,13 @@ Method allow for the retrieval of resources. * Returns: `org.apache.sling.api.resource.Resource` - The resource at the path. * Accepts: -* `org.apache.sling.api.resource.ResourceResolver` - The current resource resolver. -* `java.lang.String` - The path at which to find the resource. + * `org.apache.sling.api.resource.ResourceResolver` - The current resource resolver. + * `java.lang.String` - The path at which to find the resource. * Since: 1.3 *Example Usage* -<c:set var="content" value="${sling:getResource(resourceResolver,'/content')}" /> + <c:set var="content" value="${sling:getResource(resourceResolver,'/content')}" /> ### getValue @@ -130,14 +133,14 @@ otherwise, the third parameter is used as the default when retrieving the value * Returns: `java.lang.Object` - The value. * Accepts: -* `org.apache.sling.api.resource.ValueMap` - The ValueMap from which to retrieve the value. -* `java.lang.String` - The key for the value to retrieve -* `java.lang.Object` - Either the default value or the class to which to coerce the value. + * `org.apache.sling.api.resource.ValueMap` - The ValueMap from which to retrieve the value. + * `java.lang.String` - The key for the value to retrieve + * `java.lang.Object` - Either the default value or the class to which to coerce the value. * Since: 1.3 *Example Usage* -<c:set var="content" value="${sling:getValue(properties,'jcr:title',resource.name)}" /> + <c:set var="content" value="${sling:getValue(properties,'jcr:title',resource.name)}" /> ### listChildren @@ -145,14 +148,14 @@ Method for allowing the invocation of the Sling Resource listChildren method. * Returns: `java.util.Iterator` - The children of the resource. * Accepts: -* `org.apache.sling.api.resource.Resource` - The resource of which to list the children. + * `org.apache.sling.api.resource.Resource` - The resource of which to list the children. * Since: 1.3 *Example Usage* -<c:forEach var="child" items="${sling:listChildren(resource)"> -<li>${child.path}</li> -</c:forEach> + <c:forEach var="child" items="${sling:listChildren(resource)"> + <li>${child.path}</li> + </c:forEach> ## Tags @@ -163,28 +166,28 @@ The Sling Taglib includes a number of Tags which can be used to access the repos Adapts adaptables to objects of other types. * Attributes -* adaptable - The adaptable object to adapt. -* adaptTo - The class name to which to adapt the adaptable. -* var - The name of the variable to which to save the adapted object. + * adaptable - The adaptable object to adapt. + * adaptTo - The class name to which to adapt the adaptable. + * var - The name of the variable to which to save the adapted object. * Since: 1.3 *Example Usage* -<sling:adaptTo adaptable="${resource}" adaptTo="org.apache.sling.api.resource.ValueMap" var="myProps" /> + <sling:adaptTo adaptable="${resource}" adaptTo="org.apache.sling.api.resource.ValueMap" var="myProps" /> ### call Execute a script. * Attributes -* flush - Whether to flush the output before including the target. -* script - The script to include. -* ignoreComponentHierarchy - Controls if the component hierarchy should be ignored for script resolution. If true, only the search paths are respected. + * flush - Whether to flush the output before including the target. + * script - The script to include. + * ignoreComponentHierarchy - Controls if the component hierarchy should be ignored for script resolution. If true, only the search paths are respected. * Since: 1.2 *Example Usage* -<sling:call script="myscript.jsp" /> + <sling:call script="myscript.jsp" /> ### defineObjects @@ -204,141 +207,141 @@ See also [Scripting variables in CMS](https://cwiki.apache.org/confluence/displa * Attributes which allow to bind the according variables to other names than the default ones listed above. -* requestName -* responseName -* resourceName -* nodeName -* logName -* resourceResolverName -* slingName + * requestName + * responseName + * resourceName + * nodeName + * logName + * resourceResolverName + * slingName * Since: 1.0 *Example Usage* -<sling:defineObjects /> + <sling:defineObjects /> ### encode Writes properly Cross Site Scripting (XSS) encoded text to the response using the OWASP ESAPI. Supports a number of encoding modes. * Attributes: -* value - The text to encode -* default - a default text to use if the value is null or empty -* mode - The encoding mode, one of HTML, HTML_ATTR, XML, XML_ATTR, JS + * value - The text to encode + * default - a default text to use if the value is null or empty + * mode - The encoding mode, one of HTML, HTML_ATTR, XML, XML_ATTR, JS * Since: 1.4 *Example Usage* -<sling:encode value="<script>alert('Bad Stuff!');</script>" mode="HTML" /> + <sling:encode value="<script>alert('Bad Stuff!');</script>" mode="HTML" /> ### eval Evaluates a script invocation and includes the result in the current page. * Attributes -* flush - Whether to flush the output before including the target. -* script - The path to the script object to include in the current request processing. By default, the current resource is used for script resolving. This behaviour can be changed by specifying either resource, resourceType or ignoreResourceTypeHierarchy. -* resource - The resource object to include in the current request processing. This attribute is optional. If it is specified, resourceType should not be used. If both are used, resource takes precedence. -* resourceType - The resource type of a resource to include. This attribute is optional. If it is specified, resource should not be used. If both are used, resource takes precedence. -* ignoreResourceTypeHierarchy - Prevents using the resource type hierarchy for searching a script. + * flush - Whether to flush the output before including the target. + * script - The path to the script object to include in the current request processing. By default, the current resource is used for script resolving. This behaviour can be changed by specifying either resource, resourceType or ignoreResourceTypeHierarchy. + * resource - The resource object to include in the current request processing. This attribute is optional. If it is specified, resourceType should not be used. If both are used, resource takes precedence. + * resourceType - The resource type of a resource to include. This attribute is optional. If it is specified, resource should not be used. If both are used, resource takes precedence. + * ignoreResourceTypeHierarchy - Prevents using the resource type hierarchy for searching a script. * Since: 1.1 *Example Usage* -<sling:eval script="myscript.jsp" /> + <sling:eval script="myscript.jsp" /> ### findResources Tag for searching for resources using the given query formulated in the given language. * Attributes -* query - The query string to find the resources. -* language - The query language to use. -* var - The name of the variable to which to save the resources. + * query - The query string to find the resources. + * language - The query language to use. + * var - The name of the variable to which to save the resources. * Since: 1.3 *Example Usage* -<sling:findResources query="/jcr:root//*[jcr:contains(., 'Sling')] order by @jcr:score" language="xpath" var="resources" /> + <sling:findResources query="/jcr:root//*[jcr:contains(., 'Sling')] order by @jcr:score" language="xpath" var="resources" /> ### forward Forwards a request to a resource rendering the current page * Attributes -* resource - The resource object to forward the request to. Either resource or path must be specified. If both are specified, the resource takes precedences. -* path - The path to the resource object to forward the request to. If this path is relative it is appended to the path of the current resource whose script is forwarding the given resource. Either resource or path must be specified. If both are specified, the resource takes precedences. -* resourceType - The resource type of a resource to forward. If the resource to be forwarded is specified with the path attribute, which cannot be resolved to a resource, the tag may create a synthetic resource object out of the path and this resource type. If the resource type is set the path must be the exact path to a resource object. That is, adding parameters, selectors and extensions to the path is not supported if the resource type is set. -* replaceSelectors - When dispatching, replace selectors by the value provided by this option. -* addSelectors - When dispatching, add the value provided by this option to the selectors. -* replaceSuffix - When dispatching, replace the suffix by the value provided by this option. + * resource - The resource object to forward the request to. Either resource or path must be specified. If both are specified, the resource takes precedences. + * path - The path to the resource object to forward the request to. If this path is relative it is appended to the path of the current resource whose script is forwarding the given resource. Either resource or path must be specified. If both are specified, the resource takes precedences. + * resourceType - The resource type of a resource to forward. If the resource to be forwarded is specified with the path attribute, which cannot be resolved to a resource, the tag may create a synthetic resource object out of the path and this resource type. If the resource type is set the path must be the exact path to a resource object. That is, adding parameters, selectors and extensions to the path is not supported if the resource type is set. + * replaceSelectors - When dispatching, replace selectors by the value provided by this option. + * addSelectors - When dispatching, add the value provided by this option to the selectors. + * replaceSuffix - When dispatching, replace the suffix by the value provided by this option. * Since: 1.0 *Example Usage* -<sling:forward path="/content/aresource" resourceType="myapp/components/display" /> + <sling:forward path="/content/aresource" resourceType="myapp/components/display" /> ### getProperty Retrieves the value from the ValueMap, allowing for a default value or coercing the return value. * Attributes -* properties - The ValueMap from which to retrieve the value. -* key - The key to retrieve the value from from the ValueMap. -* defaultValue - The default value to return if no value exists for the key. If specified, this takes precedence over returnClass. -* returnClass - The class into which to coerce the returned value. -* var - The name of the variable to which to save the value. + * properties - The ValueMap from which to retrieve the value. + * key - The key to retrieve the value from from the ValueMap. + * defaultValue - The default value to return if no value exists for the key. If specified, this takes precedence over returnClass. + * returnClass - The class into which to coerce the returned value. + * var - The name of the variable to which to save the value. * Since: 1.3 *Example Usage* -<sling:getProperties properties="${properties}" key="jcr:title" defaultValue="${resource.name}" var="title" /> + <sling:getProperties properties="${properties}" key="jcr:title" defaultValue="${resource.name}" var="title" /> ### getResource Retrieves resources based on either an absolute path or a relative path and a base resource. * Attributes -* base - The base resource under which to retrieve the child resource, will only be considered if a relative path is specified. -* path - The path of the resource to retrieve, if relative, the base resource must be specified. -* defaultValue - The default value to return if no value exists for the key. If specified, this takes precedence over returnClass. -* returnClass - The class into which to coerce the returned value. -* var - The name of the variable to which to save the resource. + * base - The base resource under which to retrieve the child resource, will only be considered if a relative path is specified. + * path - The path of the resource to retrieve, if relative, the base resource must be specified. + * defaultValue - The default value to return if no value exists for the key. If specified, this takes precedence over returnClass. + * returnClass - The class into which to coerce the returned value. + * var - The name of the variable to which to save the resource. * Since: 1.3 *Example Usage* -<sling:getResource base="${resource}" path="jcr:content" var="content" /> + <sling:getResource base="${resource}" path="jcr:content" var="content" /> ### include Includes a resource rendering into the current page. * Attributes -* flush - Whether to flush the output before including the target. -* resource - The resource object to include in the current request processing. Either resource or path must be specified. If both are specified, the resource takes precedences. -* path - The path to the resource object to include in the current request processing. If this path is relative it is appended to the path of the current resource whose script is including the given resource. Either resource or path must be specified. If both are specified, the resource takes precedences. -* resourceType - The resource type of a resource to include. If the resource to be included is specified with the path attribute, which cannot be resolved to a resource, the tag may create a synthetic resource object out of the path and this resource type. If the resource type is set the path must be the exact path to a resource object. That is, adding parameters, selectors and extensions to the path is not supported if the resource type is set. -* replaceSelectors - When dispatching, replace selectors by the value provided by this option. -* addSelectors - When dispatching, add the value provided by this option to the selectors. -* replaceSuffix - When dispatching, replace the suffix by the value provided by this option. -* scope - If var is specified, what scope to store the variable in. (Since 1.3) -* var - variable name to store the resulting markup into (Since 1.3) + * flush - Whether to flush the output before including the target. + * resource - The resource object to include in the current request processing. Either resource or path must be specified. If both are specified, the resource takes precedences. + * path - The path to the resource object to include in the current request processing. If this path is relative it is appended to the path of the current resource whose script is including the given resource. Either resource or path must be specified. If both are specified, the resource takes precedences. + * resourceType - The resource type of a resource to include. If the resource to be included is specified with the path attribute, which cannot be resolved to a resource, the tag may create a synthetic resource object out of the path and this resource type. If the resource type is set the path must be the exact path to a resource object. That is, adding parameters, selectors and extensions to the path is not supported if the resource type is set. + * replaceSelectors - When dispatching, replace selectors by the value provided by this option. + * addSelectors - When dispatching, add the value provided by this option to the selectors. + * replaceSuffix - When dispatching, replace the suffix by the value provided by this option. + * scope - If var is specified, what scope to store the variable in. (Since 1.3) + * var - variable name to store the resulting markup into (Since 1.3) * Since: 1.0 *Example Usage* -<sling:include path="/content/aresource" resourceType="myapp/components/display" /> + <sling:include path="/content/aresource" resourceType="myapp/components/display" /> ### listChildren Lists the children of a Sling Resource. * Attributes -* resource - The resource for which to retrieve the children. -* var - The name of the variable to which to save the child resources. + * resource - The resource for which to retrieve the children. + * var - The name of the variable to which to save the child resources. * Since: 1.3 *Example Usage* -<sling:listChildren resource="${resource}" var="children" /> + <sling:listChildren resource="${resource}" var="children" /> http://git-wip-us.apache.org/repos/asf/sling-site/blob/53c84cf9/content/documentation/bundles/scripting/scripting-thymeleaf.md ---------------------------------------------------------------------- diff --git a/content/documentation/bundles/scripting/scripting-thymeleaf.md b/content/documentation/bundles/scripting/scripting-thymeleaf.md index 2ef2280..8074dc9 100644 --- a/content/documentation/bundles/scripting/scripting-thymeleaf.md +++ b/content/documentation/bundles/scripting/scripting-thymeleaf.md @@ -1,7 +1,10 @@ -title=Sling Scripting Thymeleaf -type=page +title=TODO title for scripting-thymeleaf.md +date=1900-01-01 +type=post +tags=blog status=published ~~~~~~ +Title: Sling Scripting Thymeleaf Sling Scripting Thymeleaf is the scripting engine for [_Thymeleaf_](http://www.thymeleaf.org) (3.0) templates. @@ -20,14 +23,14 @@ Sling Scripting Thymeleaf is the scripting engine for [_Thymeleaf_](http://www.t For running Sling Scripting Thymeleaf with Sling's Launchpad some dependencies need to be resolved. This can be achieved by installing the following bundles: -mvn:org.attoparser/attoparser/2.0.2.RELEASE -mvn:org.unbescape/unbescape/1.1.4.RELEASE -mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.ognl/3.2_1 -mvn:org.javassist/javassist/3.20.0-GA + mvn:org.attoparser/attoparser/2.0.2.RELEASE + mvn:org.unbescape/unbescape/1.1.4.RELEASE + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.ognl/3.2_1 + mvn:org.javassist/javassist/3.20.0-GA There is a feature for Karaf: -karaf@root()> feature:install sling-scripting-thymeleaf + karaf@root()> feature:install sling-scripting-thymeleaf **Note:** Sling Scripting Thymeleaf requires an implementation of OSGi Declarative Services 1.3 (e.g. [Apache Felix Service Component Runtime](http://felix.apache.org/documentation/subprojects/apache-felix-service-component-runtime.html) 2.0.0 or greater) http://git-wip-us.apache.org/repos/asf/sling-site/blob/53c84cf9/content/documentation/bundles/servlet-helpers.md ---------------------------------------------------------------------- diff --git a/content/documentation/bundles/servlet-helpers.md b/content/documentation/bundles/servlet-helpers.md index a731f76..f1e6cb9 100644 --- a/content/documentation/bundles/servlet-helpers.md +++ b/content/documentation/bundles/servlet-helpers.md @@ -1,7 +1,10 @@ -title=Sling Servlet Helpers -type=page +title=TODO title for servlet-helpers.md +date=1900-01-01 +type=post +tags=blog status=published ~~~~~~ +Title: Sling Servlet Helpers The Sling Servlet Helpers bundle provides mock implementations of the `SlingHttpServletRequest`, `SlingHttpServletResponse` and related classes. @@ -10,7 +13,7 @@ Those mock implementations are meant to be used in tests and also with services like the `SlingRequestProcessor` when making requests to that service outside of an HTTP request processing context. -See the [automated tests](https://svn.apache.org/repos/asf/sling/trunk/bundles/extensions/servlet-helpers) +See the [automated tests](https://svn.apache.org/repos/asf/sling/trunk/bundles/extensions/servlet-helpers) of the `servlet-helpers` module for more info. @@ -20,64 +23,64 @@ of the `servlet-helpers` module for more info. Example for preparing a sling request with custom request data: -#!java -// prepare sling request -MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(resourceResolver); + #!java + // prepare sling request + MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(resourceResolver); -// simulate query string -request.setQueryString("param1=aaa¶m2=bbb"); + // simulate query string + request.setQueryString("param1=aaa¶m2=bbb"); -// alternative - set query parameters as map -request.setParameterMap(ImmutableMap.<String,Object>builder() -.put("param1", "aaa") -.put("param2", "bbb") -.build()); + // alternative - set query parameters as map + request.setParameterMap(ImmutableMap.<String,Object>builder() + .put("param1", "aaa") + .put("param2", "bbb") + .build()); -// set current resource -request.setResource(resourceResolver.getResource("/content/sample")); + // set current resource + request.setResource(resourceResolver.getResource("/content/sample")); -// set sling request path info properties -MockRequestPathInfo requestPathInfo = (MockRequestPathInfo)request.getRequestPathInfo(); -requestPathInfo.setSelectorString("selector1.selector2"); -requestPathInfo.setExtension("html"); + // set sling request path info properties + MockRequestPathInfo requestPathInfo = (MockRequestPathInfo)request.getRequestPathInfo(); + requestPathInfo.setSelectorString("selector1.selector2"); + requestPathInfo.setExtension("html"); -// set method -request.setMethod(HttpConstants.METHOD_POST); + // set method + request.setMethod(HttpConstants.METHOD_POST); -// set attributes -request.setAttribute("attr1", "value1"); + // set attributes + request.setAttribute("attr1", "value1"); -// set headers -request.addHeader("header1", "value1"); + // set headers + request.addHeader("header1", "value1"); -// set cookies -request.addCookie(new Cookie("cookie1", "value1")); + // set cookies + request.addCookie(new Cookie("cookie1", "value1")); ### SlingHttpServletResponse Example for preparing a sling response which can collect the data that was written to it: -#!java -// prepare sling response -MockSlingHttpServletResponse response = new MockSlingHttpServletResponse(); + #!java + // prepare sling response + MockSlingHttpServletResponse response = new MockSlingHttpServletResponse(); -// execute the code that writes to the response... + // execute the code that writes to the response... -// validate status code -assertEquals(HttpServletResponse.SC_OK, response.getStatus()); + // validate status code + assertEquals(HttpServletResponse.SC_OK, response.getStatus()); -// validate content type and content length -assertEquals("text/plain;charset=UTF-8", response.getContentType()); -assertEquals(CharEncoding.UTF_8, response.getCharacterEncoding()); -assertEquals(55, response.getContentLength()); + // validate content type and content length + assertEquals("text/plain;charset=UTF-8", response.getContentType()); + assertEquals(CharEncoding.UTF_8, response.getCharacterEncoding()); + assertEquals(55, response.getContentLength()); -// validate headers -assertTrue(response.containsHeader("header1")); -assertEquals("5", response.getHeader("header2")); + // validate headers + assertTrue(response.containsHeader("header1")); + assertEquals("5", response.getHeader("header2")); -// validate response body as string -assertEquals(TEST_CONTENT, response.getOutputAsString()); + // validate response body as string + assertEquals(TEST_CONTENT, response.getOutputAsString()); -// validate response body as binary data -assertArrayEquals(TEST_DATA, response.getOutput()); + // validate response body as binary data + assertArrayEquals(TEST_DATA, response.getOutput()); http://git-wip-us.apache.org/repos/asf/sling-site/blob/53c84cf9/content/documentation/bundles/sling-health-check-tool.md ---------------------------------------------------------------------- diff --git a/content/documentation/bundles/sling-health-check-tool.md b/content/documentation/bundles/sling-health-check-tool.md index 710e937..e86e5d7 100644 --- a/content/documentation/bundles/sling-health-check-tool.md +++ b/content/documentation/bundles/sling-health-check-tool.md @@ -1,13 +1,16 @@ -title=Sling Health Check Tools -type=page +title=TODO title for sling-health-check-tool.md +date=1900-01-01 +type=post +tags=blog status=published ~~~~~~ +Title: Sling Health Check Tools -Based on simple `HealthCheck` OSGi services, the Sling Health Check Tools ("hc" in short form) are used to -check the health of live Sling systems, based on inputs like JMX MBean attribute values, OSGi framework +Based on simple `HealthCheck` OSGi services, the Sling Health Check Tools ("hc" in short form) are used to +check the health of live Sling systems, based on inputs like JMX MBean attribute values, OSGi framework information, Sling requests status, etc. -Health checks are easily extensible either by configuring the supplied default `HealthCheck` services, or +Health checks are easily extensible either by configuring the supplied default `HealthCheck` services, or by implementing your own `HealthCheck` services to cater for project specific requirements. However for simple setups, the out of the box health checks are often sufficient. [Executing Health Checks](#executing-health-checks) @@ -27,13 +30,13 @@ Generally health checks have two high level use cases: The strength of Health Checks are to surface internal Sling state for external use: * Verify that performance counters are in range -* Run smoke tests at system startup +* Run smoke tests at system startup * Check that all OSGi bundles are up and running * Check that demo content has been removed from a production system * Check that demo accounts are disabled * Ping external systems and raise alarms if they are down -The health check subsystem uses tags to select which health checks to execute so you can for example execute just the _performance_ or _security_ health +The health check subsystem uses tags to select which health checks to execute so you can for example execute just the _performance_ or _security_ health checks once they are configured with the corresponding tags. The out of the box health check services also allow for using them as JMX aggregators and processors, which take JMX @@ -43,60 +46,60 @@ attribute values as input and make the results accessible via JMX MBeans. A `HealthCheck` is just an OSGi service that returns a `Result`. -public interface HealthCheck { - -/** Execute this health check and return a {@link Result} -* This is meant to execute quickly, access to external -* systems, for example, should be managed asynchronously. -*/ -public Result execute(); -} - + public interface HealthCheck { + + /** Execute this health check and return a {@link Result} + * This is meant to execute quickly, access to external + * systems, for example, should be managed asynchronously. + */ + public Result execute(); + } + Where `Result` is a simple immutable class that provides a `Status` (OK, WARN, CRITICAL etc.) and one or more log-like messages that can provide more info about what, if anything, went wrong. -public class Result implements Iterable <ResultLog.Entry> { - -public boolean isOk() { -return getStatus().equals(Status.OK); -} - -public Status getStatus() { -return resultLog.getAggregateStatus(); -} - -@Override -public Iterator<ResultLog.Entry> iterator() { -return resultLog.iterator(); -} - -... details omitted -} + public class Result implements Iterable <ResultLog.Entry> { + + public boolean isOk() { + return getStatus().equals(Status.OK); + } + + public Status getStatus() { + return resultLog.getAggregateStatus(); + } + + @Override + public Iterator<ResultLog.Entry> iterator() { + return resultLog.iterator(); + } + + ... details omitted + } ### SlingHealthCheck annotation The `SlingHealthCheck` annotation makes it easier to specify the required `HealthCheck` service properties. Here's an example from the `samples` module - see the `annotations` module for more details. -@SlingHealthCheck( -name="Annotated Health Check Sample", -mbeanName="annotatedHC", -description="Sample Health Check defined by a java annotation", -tags={"sample","annotation"}) + @SlingHealthCheck( + name="Annotated Health Check Sample", + mbeanName="annotatedHC", + description="Sample Health Check defined by a java annotation", + tags={"sample","annotation"}) + + public class AnnotatedHealthCheckSample implements HealthCheck { -public class AnnotatedHealthCheckSample implements HealthCheck { - -@Override -public Result execute() { -...health check code -} -} + @Override + public Result execute() { + ...health check code + } + } ## Executing Health Checks -Health Checks can be executed via a [webconsole plugin](#webconsole-plugin), the [health check servlet](#health-check-servlet) or via [JMX](#jmx-access-to-health-checks). `HealthCheck` services can be selected for execution based on their `hc.tags` multi-value service property. +Health Checks can be executed via a [webconsole plugin](#webconsole-plugin), the [health check servlet](#health-check-servlet) or via [JMX](#jmx-access-to-health-checks). `HealthCheck` services can be selected for execution based on their `hc.tags` multi-value service property. -The `HealthCheckFilter` utility accepts positive and negative tag parameters, so that `-security,sling` +The `HealthCheckFilter` utility accepts positive and negative tag parameters, so that `-security,sling` selects all `HealthCheck` having the `sling` tag but not the `security` tag, for example. For advanced use cases it is also possible to use the API directly by using the interface `org.apache.sling.hc.api.execution.HealthCheckExecutor`. @@ -109,27 +112,27 @@ The Health Check subsystem consists of the following bundles: * `org.apache.sling.hc.webconsole` provides the Webconsole plugin described below. * `org.apache.sling.junit.healthcheck` provides a `HealthCheck` service that executes JUnit tests in the server-side OSGi context. * `org.apache.sling.hc.samples` provides sample OSGi configurations and `HealthCheck` services. The sample configurations are provided as Sling content, so the Sling Installer is required to activate them. -* `org.apache.sling.hc.junit.bridge` makes selected Health Checks available as server-side JUnit tests. See below for more info. +* `org.apache.sling.hc.junit.bridge` makes selected Health Checks available as server-side JUnit tests. See below for more info. ## Out-of-the-box `HealthCheck` services -The following default `HealthCheck` services are provided by the `org.apache.sling.hc.core` bundle: +The following default `HealthCheck` services are provided by the `org.apache.sling.hc.core` bundle: The `org.apache.sling.hc.samples` bundle provides OSGi configurations that demonstrate them. -* `JmxAttributeHealthCheck` checks the value of a single JMX attribute and supports ranges like _between 12 and 42_. -* `ScriptableHealthCheck` evaluates an expression written in any scripting language that Sling supports, and provides bindings to access JMX attributes. -* `CompositeHealthCheck` executes a set of `HealthCheck` selected by tags, useful for creating higher-level checks. + * `JmxAttributeHealthCheck` checks the value of a single JMX attribute and supports ranges like _between 12 and 42_. + * `ScriptableHealthCheck` evaluates an expression written in any scripting language that Sling supports, and provides bindings to access JMX attributes. + * `CompositeHealthCheck` executes a set of `HealthCheck` selected by tags, useful for creating higher-level checks. A few more Sling-specific ones are provided by the `org.apache.sling.hc.support` bundle: - -* `SlingRequestStatusHealthCheck` checks the HTTP status of Sling requests. -* `DefaultLoginsHealthCheck` can be used to verify that the default Sling logins fail. -* `ThreadUsageHealthCheck` can be used to monitor for deadlocks using JRE ThreadMXBean (see [SLING-6698](https://issues.apache.org/jira/browse/SLING-6698) ) - -A bridge to server-side OSGi-aware JUnit tests is provided by the `JUnitHealthCheck`, from + + * `SlingRequestStatusHealthCheck` checks the HTTP status of Sling requests. + * `DefaultLoginsHealthCheck` can be used to verify that the default Sling logins fail. + * `ThreadUsageHealthCheck` can be used to monitor for deadlocks using JRE ThreadMXBean (see [SLING-6698](https://issues.apache.org/jira/browse/SLING-6698) ) + +A bridge to server-side OSGi-aware JUnit tests is provided by the `JUnitHealthCheck`, from the `org.apache.sling.junit.healthcheck` bundle. - + The `org.apache.sling.hc.samples` bundle provides an example `OsgiScriptBindingsProvider` for the default `ScriptableHealthCheck`, which provides OSGi-related information to health check script expressions. @@ -138,38 +141,38 @@ which provides OSGi-related information to health check script expressions. The following generic Health Check properties may be used for all checks: -Property | Type | Description +Property | Type | Description ----------- | -------- | ------------ hc.name | String | The name of the health check as shown in UI hc.tags | String[] | List of tags: Both Felix Console Plugin and Health Check servlet support selecting relevant checks by providing a list of tags hc.mbean.name | String | Makes the HC result available via given MBean name. If not provided no MBean is created for that `HealthCheck` -hc.async.cronExpression | String | Used to schedule the execution of a `HealthCheck` at regular intervals, using a cron expression as specified by the [Sling Scheduler](/documentation/bundles/scheduler-service-commons-scheduler.html) module. +hc.async.cronExpression | String | Used to schedule the execution of a `HealthCheck` at regular intervals, using a cron expression as specified by the [Sling Scheduler](/documentation/bundles/scheduler-service-commons-scheduler.html) module. hc.resultCacheTtlInMs | Long | Overrides the global default TTL as configured in health check executor for health check responses (since v1.2.6 of core) All service properties are optional. As an example, here's a `ScriptableHealthCheck` configuration provided by the `org.apache.sling.hc.samples` bundle: -Factory PID = org.apache.sling.hc.ScriptableHealthCheck -"hc.name" : "LoadedClassCount and ManagementSpecVersion are in range" -"hc.mbean.name" : "LoadedClassCount and ManagementSpecVersion" -"hc.tags" : [jvm, script] -"expression" : "jmx.attribute('java.lang:type=ClassLoading', 'LoadedClassCount') > 10 && jmx.attribute('java.lang:type=Runtime', 'ManagementSpecVersion') > 1" -"language.extension" : "ecma" - -The service properties starting with the `hc.` prefix in this example should be provided by all `HealthCheck` services. + Factory PID = org.apache.sling.hc.ScriptableHealthCheck + "hc.name" : "LoadedClassCount and ManagementSpecVersion are in range" + "hc.mbean.name" : "LoadedClassCount and ManagementSpecVersion" + "hc.tags" : [jvm, script] + "expression" : "jmx.attribute('java.lang:type=ClassLoading', 'LoadedClassCount') > 10 && jmx.attribute('java.lang:type=Runtime', 'ManagementSpecVersion') > 1" + "language.extension" : "ecma" + +The service properties starting with the `hc.` prefix in this example should be provided by all `HealthCheck` services. ## Configuring the Health Check Executor The health check executor can **optionally** be configured via service PID `org.apache.sling.hc.core.impl.executor.HealthCheckExecutorImpl`: -Property | Type | Default | Description +Property | Type | Default | Description ----------- | -------- | ------ | ------------ timeoutInMs | Long | 2000ms | Timeout in ms until a check is marked as timed out longRunningFutureThresholdForCriticalMs | Long | 300000ms = 5min | Threshold in ms until a check is marked as 'exceedingly' timed out and will marked CRITICAL instead of WARN only resultCacheTtlInMs | Long | 2000ms | Result Cache time to live - results will be cached for the given time ## Webconsole plugin -If the `org.apache.sling.hc.webconsole` bundle is active, a webconsole plugin +If the `org.apache.sling.hc.webconsole` bundle is active, a webconsole plugin at `/system/console/healthcheck` allows for executing health checks, optionally selected based on their tags (positive and negative selection, see the `HealthCheckFilter` mention above). @@ -180,11 +183,11 @@ The screenshot below shows an example, as of svn revision 1513462. ![Health Check Webconsole Plugin](sling-hc-plugin.jpg) ## JMX access to health checks -If the `org.apache.sling.hc.jmx` bundle is active, a JMX MBean is created for each `HealthCheck` which has the -service property `hc.mbean.name` service property set. All health check MBeans are registered in the +If the `org.apache.sling.hc.jmx` bundle is active, a JMX MBean is created for each `HealthCheck` which has the +service property `hc.mbean.name` service property set. All health check MBeans are registered in the domain `org.apache.sling.healthcheck` with a type of `HealthCheck`. -The MBean gives access to the `Result` and the log, as shown on the screenshot below. +The MBean gives access to the `Result` and the log, as shown on the screenshot below. See the example configurations of the `org.apache.sling.hc.samples` for more details. @@ -196,8 +199,8 @@ similar features to the Web Console plugin described above, with output in HTML, The Health Checks Servlet is disabled by default, to enable it create an OSGi configuration like -PID = org.apache.sling.hc.core.impl.servlet.HealthCheckExecutorServlet -servletPath = /system/health + PID = org.apache.sling.hc.core.impl.servlet.HealthCheckExecutorServlet + servletPath = /system/health which specifies the servlet's base path. That URL then returns an HTML page, by default with the results of all active health checks and with instructions at the end of the page about URL parameters which can be used to select specific Health Checks and control their execution and output format. @@ -205,20 +208,20 @@ with instructions at the end of the page about URL parameters which can be used Note that by design **the Health Checks Servlet doesn't do any access control by itself** to ensure it can detect unhealthy states of the authentication itself. Make sure the configured path is only accessible to relevant infrastructure and operations people. Usually all `/system/*` paths are only accessible from a local network and not routed to the Internet. ## Health Checks as server-side JUnit tests -The `org.apache.sling.hc.junit.bridge` bundle makes selected Health Checks available as server-side JUnit tests. +The `org.apache.sling.hc.junit.bridge` bundle makes selected Health Checks available as server-side JUnit tests. It requires the `org.apache.sling.junit.core bundle` which provides the server-side JUnit tests infrastructure. The idea is to implement the smoke tests of your system, for example, as health checks. You can then run them -as part of integration testing, using the [Sling Testing Tools](/documentation/development/sling-testing-tools.html) +as part of integration testing, using the [Sling Testing Tools](/documentation/development/sling-testing-tools.html) remote testing utilities, and also as plain Health Checks for monitoring or troubleshooting Sling instances. To use this module, configure sets of tags at `/system/console/configMgr/org.apache.sling.hc.junitbridge.HealthCheckTestsProvider` -using the standard `includeThisTag,-omitThatTag` syntax, and JUnit tests will be available at /system/sling/junit/HealthChecks.html +using the standard `includeThisTag,-omitThatTag` syntax, and JUnit tests will be available at /system/sling/junit/HealthChecks.html to run the corresponding Health Checks. To run the Health Check tests at build time, see the [testing/samples/integration-tests](http://svn.apache.org/repos/asf/sling/trunk/testing/samples/integration-tests) sample module. - + http://git-wip-us.apache.org/repos/asf/sling-site/blob/53c84cf9/content/documentation/bundles/sling-oak-restrictions.md ---------------------------------------------------------------------- diff --git a/content/documentation/bundles/sling-oak-restrictions.md b/content/documentation/bundles/sling-oak-restrictions.md index 13f6bd7..1363dda 100644 --- a/content/documentation/bundles/sling-oak-restrictions.md +++ b/content/documentation/bundles/sling-oak-restrictions.md @@ -1,37 +1,40 @@ -title=Sling Oak Restrictions -type=page +title=TODO title for sling-oak-restrictions.md +date=1900-01-01 +type=post +tags=blog status=published ~~~~~~ +Title: Sling Oak Restrictions [TOC] ## Introduction Oak introduced plugability of restrictions as described in [Oak Restriction Management](https://jackrabbit.apache.org/oak/docs/security/authorization/restriction.html#Pluggability). The bundle sling-oak-restrictions provides additional restrictions that generally make sense for sling applications. Currently sling restrictions for exact resource type match and resource type match including all descendants are supplied. -**Important:** Using the sling restrictions (as well as standard oak restrictions) is not as performant as simple path based ACE entries without any restrictions. Permission setups should always mostly work with path based ACEs and only use ACEs with restrictions for special cases. +**Important:** Using the sling restrictions (as well as standard oak restrictions) is not as performant as simple path based ACE entries without any restrictions. Permission setups should always mostly work with path based ACEs and only use ACEs with restrictions for special cases. ## Restriction sling:resourceTypes -This restriction allows to match against a sling resource type of a node and works much like the oak standard restriction `rep:ntNames`. Only resources that have one of the supplied resource types are matched, child and parent resources with other resource types are not matched. +This restriction allows to match against a sling resource type of a node and works much like the oak standard restriction `rep:ntNames`. Only resources that have one of the supplied resource types are matched, child and parent resources with other resource types are not matched. The following example allows `myAuthorizable` to write to all nodes that have either resource type `myproj/comp1` or `myproj/comp2`: -- /content/myprj/mynode -- rep:policy (rep:ACL) -- allow (rep:GrantACE) -+ principalName (String) = "myAuthorizable" -+ rep:privileges (Name[]) = "rep:write" -- rep:restrictions (rep:Restrictions) -+ sling:resourceTypes (String[]) = [myproj/comp1,myproj/comp2] + - /content/myprj/mynode + - rep:policy (rep:ACL) + - allow (rep:GrantACE) + + principalName (String) = "myAuthorizable" + + rep:privileges (Name[]) = "rep:write" + - rep:restrictions (rep:Restrictions) + + sling:resourceTypes (String[]) = [myproj/comp1,myproj/comp2] Assuming the following structure -- /content/myprj -+ sling:resourceType (String) = "myproj/siteroot" -- mynode -+ sling:resourceType (String) = "myproj/comp1" -- mysubnode -+ sling:resourceType (String) = "myproj/comp3" + - /content/myprj + + sling:resourceType (String) = "myproj/siteroot" + - mynode + + sling:resourceType (String) = "myproj/comp1" + - mysubnode + + sling:resourceType (String) = "myproj/comp3" the rule from above will match `/content/myprj/mynode` and not `/content/myprj` (parent) nor `/content/myprj/mynode/mysubnode` (child). @@ -43,53 +46,53 @@ This restriction matches against resource types in the same way as [sling:resour The following example allows `myAuthorizable` to write to all nodes that have either resource type `myproj/comp1` or `myproj/comp2` **or are a child of a node, that has one of these resource types**: -- /content/myprj/mynode -- rep:policy (rep:ACL) -- allow (rep:GrantACE) -+ principalName (String) = "myAuthorizable" -+ rep:privileges (Name[]) = "rep:write" -- rep:restrictions (rep:Restrictions) -+ sling:resourceTypesWithDescendants (String[]) = [myproj/comp1,myproj/comp2] + - /content/myprj/mynode + - rep:policy (rep:ACL) + - allow (rep:GrantACE) + + principalName (String) = "myAuthorizable" + + rep:privileges (Name[]) = "rep:write" + - rep:restrictions (rep:Restrictions) + + sling:resourceTypesWithDescendants (String[]) = [myproj/comp1,myproj/comp2] Assuming the structure example as mentioned in [sling:resourceTypes](#restriction-slingresourcetypes), the rule from above will match `/content/myprj/mynode` and `/content/myprj/mynode/mysubnode` (and any other subnodes of `/content/myprj/mynode` with arbitrary resource types), but not `/content/myprj`. ## Advanced Path Matching -Both [sling:resourceTypes](#restriction-slingresourcetypes) and [sling:resourceTypesWithDescendants](#restriction-slingresourcetypeswithdescendants) support advanced path matching by using `resourcetype@path`. That way instead of checking the resource type of the current node, the resource type of node at the relative path is checked. For instance this is useful for the case where page content is stored in a `jcr:content` subnode of a hierarchy, the permission however is required to become effective on the parent node of `jcr:content`. +Both [sling:resourceTypes](#restriction-slingresourcetypes) and [sling:resourceTypesWithDescendants](#restriction-slingresourcetypeswithdescendants) support advanced path matching by using `resourcetype@path`. That way instead of checking the resource type of the current node, the resource type of node at the relative path is checked. For instance this is useful for the case where page content is stored in a `jcr:content` subnode of a hierarchy, the permission however is required to become effective on the parent node of `jcr:content`. The following example allows `myAuthorizable` to write to all nodes that have a subnode `jcr:content` with resource type `myproj/comp1` or `myproj/comp2` including their descendants: -- /content/myprj/mynode -- rep:policy (rep:ACL) -- allow (rep:GrantACE) -+ principalName (String) = "myAuthorizable" -+ rep:privileges (Name[]) = "rep:write" -- rep:restrictions (rep:Restrictions) -+ sling:resourceTypesWithDescendants (String[]) = [myproj/comp1@jcr:content,myproj/comp2@jcr:content] + - /content/myprj/mynode + - rep:policy (rep:ACL) + - allow (rep:GrantACE) + + principalName (String) = "myAuthorizable" + + rep:privileges (Name[]) = "rep:write" + - rep:restrictions (rep:Restrictions) + + sling:resourceTypesWithDescendants (String[]) = [myproj/comp1@jcr:content,myproj/comp2@jcr:content] Assuming the following structure -- /content/myprj -- jcr:content -+ sling:resourceType (String) = "myproj/siteroot" -- mynode1 -- jcr:content -+ sling:resourceType (String) = "myproj/comp1" -- mysubnode1 -- jcr:content -+ sling:resourceType (String) = "myproj/comp3" -- contentsubnode1 -+ sling:resourceType (String) = "myproj/comp4" -- contentsubnode2 -+ sling:resourceType (String) = "myproj/comp5" -- mysubnode2 -- jcr:content -+ sling:resourceType (String) = "myproj/comp3" -- mynode2 -- jcr:content -+ sling:resourceType (String) = "myproj/comp7" - -the rule from above will match + - /content/myprj + - jcr:content + + sling:resourceType (String) = "myproj/siteroot" + - mynode1 + - jcr:content + + sling:resourceType (String) = "myproj/comp1" + - mysubnode1 + - jcr:content + + sling:resourceType (String) = "myproj/comp3" + - contentsubnode1 + + sling:resourceType (String) = "myproj/comp4" + - contentsubnode2 + + sling:resourceType (String) = "myproj/comp5" + - mysubnode2 + - jcr:content + + sling:resourceType (String) = "myproj/comp3" + - mynode2 + - jcr:content + + sling:resourceType (String) = "myproj/comp7" + +the rule from above will match * `/content/myprj/mynode1` (because of the `@jcr:content` part of `myproj/comp1@jcr:content`) * `/content/myprj/mynode1/jcr:content` (it will check for `/content/myprj/mynode1/jcr:content/jcr:content` that does not exist, but since the parent `/content/myprj/mynode1` is already a match this matches because of `sling:resourceTypesWithDescendants`) @@ -98,6 +101,6 @@ the rule from above will match and not match -* `/content/myprj` -* `/content/myprj/mynode2` +* `/content/myprj` +* `/content/myprj/mynode2`