incubator-sling-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Sling > Scripting variables
Date Thu, 07 Jan 2010 13:17:00 GMT
<html>
<head>
    <base href="http://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/1519/1/1/_/styles/combined.css?spaceKey=SLING&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background-color: white" bgcolor="white">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
     <h2><a href="http://cwiki.apache.org/confluence/display/SLING/Scripting+variables">Scripting
variables</a></h2>
     <h4>Page <b>edited</b> by             <a href="http://cwiki.apache.org/confluence/display/~cziegeler@apache.org">Carsten
Ziegeler</a>
    </h4>
     
          <br/>
     <div class="notificationGreySide">
         <h2><a name="Scriptingvariables-Commonscriptingvariables"></a>Common
scripting variables</h2>

<p>The basic objects, such as the request and response, are available for most scripting
languages (Note the differences for eg. JSP below).</p>

<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'>Name   </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> request </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/SlingHttpServletRequest.java?view=markup"
rel="nofollow">SlingHttpServletRequest</a> object, providing access to the HTTP request
header information - extends the standard <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html"
rel="nofollow">HttpServletRequest</a> - and provides access to Sling-specific things
like resource, path info, selector, etc. </td>
</tr>
<tr>
<td class='confluenceTd'> response </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/SlingHttpServletResponse.java?view=markup"
rel="nofollow">SlingHttpServletResponse</a> object, providing access for the HTTP
response that is created by the server. This is currently the same as the <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html"
rel="nofollow">HttpServletResponse</a> from which it extends. </td>
</tr>
<tr>
<td class='confluenceTd'> sling </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/scripting/SlingScriptHelper.java?view=markup"
rel="nofollow">SlingScriptHelper</a>, containing convenience methods for scripts,
mainly <tt>sling.include('/some/other/resource')</tt> for including the responses
of other resources inside this response (eg. embedding header html snippets) and <tt>sling.getService(foo.bar.Service.class)</tt>
to retrieve OSGi services available in Sling (Class notation depending on scripting language).
</td>
</tr>
<tr>
<td class='confluenceTd'> resource </td>
<td class='confluenceTd'> Current <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/resource/Resource.java?view=markup"
rel="nofollow">Resource</a> to handle, depending on the URL of the request. Same
as <tt>request.getResource()</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> reader </td>
<td class='confluenceTd'> Direct access to the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/Reader.html"
rel="nofollow">Reader</a> of the request - same as <tt>request.getReader()</tt>.
Use it for reading the data of an HTTP request body. </td>
</tr>
<tr>
<td class='confluenceTd'> out </td>
<td class='confluenceTd'> Direct access to the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintWriter.html"
rel="nofollow">PrintWriter</a> of the response - same as <tt>response.getWriter()</tt>.
Use it for writing to the HTTP response body. </td>
</tr>
<tr>
<td class='confluenceTd'> flush </td>
<td class='confluenceTd'> Indicates whether the output used by the script shall be flushed
after the script evaluation ended. It is a Boolean, so use <tt>TRUE</tt> for flushing
or <tt>FALSE</tt> for not flushing, which is the default value. The boolean value
notation depends on the scripting language. </td>
</tr>
<tr>
<td class='confluenceTd'> log </td>
<td class='confluenceTd'> Provides an <a href="http://www.slf4j.org/api/org/slf4j/Logger.html"
rel="nofollow">SLF4J Logger</a> for logging to the Sling log system from within scripts,
eg. <tt>log.info("Executing my script")</tt>.</td>
</tr>
</tbody></table>

<p>See also the api documentation of the <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/scripting/SlingBindings.java?view=markup"
rel="nofollow">org.apache.sling.api.scripting.SlingBindings.java</a> which defines
the common scripting variables.</p>

<p>In addition currently the <tt>currentNode</tt> binding is supported by
most scripting languages. If the current <tt>resource</tt> points to a JCR node
(which is typically the case in Sling), this gives you direct access to the <a href="http://day.com/maven/jsr170/javadocs/jcr-1.0/javax/jcr/Node.html"
rel="nofollow">Node</a> object. Otherwise this object is not defined. However, we
discourage using this variable as this directly binds you to the jcr api and makes your script
unusable with other data sources supported by Sling. The better approach is to rely on the
<tt>resource</tt> and the value map. Have a look at the <tt>ResourceUtil</tt>
class for more information.</p>


<h2><a name="Scriptingvariables-JSP"></a>JSP</h2>

<p>Since JSPs already have a few Java-objects pre-defined, things have to be named differently
here. And you will have to explicitly require the variables to be defined with a custom tag
<tt>&lt;sling:defineObjects /&gt;</tt>. Your jsp should start with:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
&lt;%@ page session=<span class="code-quote">"<span class="code-keyword">false</span>"</span>
%&gt;
&lt;%@ page <span class="code-keyword">import</span>="javax.jcr.*,
        org.apache.sling.api.resource.Resource"
%&gt;
&lt;%@ taglib prefix=<span class="code-quote">"sling"</span> uri=<span
class="code-quote">"http:<span class="code-comment">//sling.apache.org/taglibs/sling/1.0"</span>
%&gt;
</span>
&lt;sling:defineObjects /&gt;
</pre>
</div></div>

<table class='confluenceTable'><tbody>
<tr>
<td class='confluenceTd'> slingRequest </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/SlingHttpServletRequest.java?view=markup"
rel="nofollow">SlingHttpServletRequest</a> object, providing access to the HTTP request
header information - extends the standard <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html"
rel="nofollow">HttpServletRequest</a> - and provides access to Sling-specific things
like resource, path info, selector, etc. </td>
</tr>
<tr>
<td class='confluenceTd'> slingResponse </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/SlingHttpServletResponse.java?view=markup"
rel="nofollow">SlingHttpServletResponse</a> object, providing access for the HTTP
response that is created by the server. This is currently the same as the <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html"
rel="nofollow">HttpServletResponse</a> from which it extends. </td>
</tr>
<tr>
<td class='confluenceTd'> request </td>
<td class='confluenceTd'> The standard JSP request object which is a pure <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html"
rel="nofollow">HttpServletRequest</a>. </td>
</tr>
<tr>
<td class='confluenceTd'> response </td>
<td class='confluenceTd'> The standard JSP response object which is a pure <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html"
rel="nofollow">HttpServletResponse</a>. </td>
</tr>
<tr>
<td class='confluenceTd'> resourceResolver </td>
<td class='confluenceTd'> Current <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/resource/ResourceResolver.java?view=markup"
rel="nofollow">ResourceResolver</a>. Same as <tt>slingRequest.getResourceResolver()</tt>.
</td>
</tr>
<tr>
<td class='confluenceTd'> sling </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/scripting/SlingScriptHelper.java?view=markup"
rel="nofollow">SlingScriptHelper</a>, containing convenience methods for scripts,
mainly <tt>sling.include('/some/other/resource')</tt> for including the responses
of other resources inside this response (eg. embedding header html snippets) and <tt>sling.getService(foo.bar.Service.class)</tt>
to retrieve OSGi services available in Sling (Class notation depending on scripting language).
</td>
</tr>
<tr>
<td class='confluenceTd'> resource </td>
<td class='confluenceTd'> Current <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/resource/Resource.java?view=markup"
rel="nofollow">Resource</a> to handle, depending on the URL of the request. Same
as <tt>slingRequest.getResource()</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> log </td>
<td class='confluenceTd'> Provides an <a href="http://www.slf4j.org/api/org/slf4j/Logger.html"
rel="nofollow">SLF4J Logger</a> for logging to the Sling log system from within scripts,
eg. <tt>log.info("Executing my script")</tt>.</td>
</tr>
</tbody></table>

<p>In addition currently the <tt>currentNode</tt> binding is supported.
If the current <tt>resource</tt> points to a JCR node (which is typically the
case in Sling), this gives you direct access to the <a href="http://day.com/maven/jsr170/javadocs/jcr-1.0/javax/jcr/Node.html"
rel="nofollow">Node</a> object. Otherwise this object is not defined. However, we
discourage using this variable as this directly binds you to the jcr api and makes your script
unusable with other data sources supported by Sling. The better approach is to rely on the
<tt>resource</tt> and the value map. Have a look at the <tt>ResourceUtil</tt>
class for more information.</p>


<h3><a name="Scriptingvariables-ResourceInclusion"></a>Resource Inclusion</h3>

<p>Instead of <tt>sling.include("/path/to/resource")</tt> you can use the
sling taglib for that:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
&lt;sling:include path=<span class="code-quote">"/path/to/resource"</span>
/&gt; 
</pre>
</div></div>

<p>For more options of the sling taglib see the <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/jsp-taglib/src/main/resources/META-INF/taglib.tld?view=markup"
rel="nofollow">tag lib definition file</a>.</p>

<h2><a name="Scriptingvariables-ESP"></a>ESP</h2>

<p>Here's a few of the objects and methods available in an ESP file:</p>

<div class="code panel" style="border-style: solid;border-width: 1px;"><div class="codeHeader
panelHeader" style="border-bottom-width: 1px;border-bottom-style: solid;"><b>html.esp</b></div><div
class="codeContent panelContent">
<pre class="code-java">
&lt;html&gt;
&lt;head&gt;&lt;title&gt;Sling ESP reference documentation&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	
&lt;h2&gt;Sling ESP documentation (work in progress)&lt;/h2&gt;
&lt;p&gt;Have a look at <span class="code-keyword">this</span> file's
source or at Sling's ScriptableNodeTest.java&lt;/p&gt;&lt;br/&gt;
	
&lt;%= 'tags: use \&lt;%=  %\&gt; to evaluate, \&lt;%  %\&gt; otherwise.'
%&gt;
&lt;%  'e.g. <span class="code-keyword">this</span> will not be printed';
%&gt;&lt;br/&gt;
&lt;%

<span class="code-comment">// create a <span class="code-keyword">new</span>
node under currentNode
</span><span class="code-keyword">var</span> n = currentNode.addNode('n');
prt('path of n: ' + n.getPath());

<span class="code-comment">// create <span class="code-keyword">new</span>
node and specify node type
</span><span class="code-keyword">var</span> n2 = n.addNode('n2', 'nt:folder');

<span class="code-comment">// set and get property
</span>n.setProperty('thename', 'thevalue');
prt('get prop thename: ' + n['thename']               ); <span class="code-comment">//
thevalue
</span>prt('another way: '      + n.thename                  ); <span class="code-comment">//
thevalue
</span>prt('get type of n2:  '  + n2['jcr:primaryType']      ); <span class="code-comment">//
nt:folder
</span>prt('test type of n2: '  + n2.isNodeType('nt:folder') ); <span class="code-comment">//
<span class="code-keyword">true</span>
</span>
<span class="code-comment">// iterate over properties
</span><span class="code-keyword">var</span> props = n.getProperties();
<span class="code-keyword">for</span>(i in props) { 
  prt('getProperties(): ' + props[i].name + ': ' + props[i].value.string); 
}

<span class="code-comment">// getNodes()
</span>n.addNode('abcd');
n.addNode('abcdef')
n.addNode('abcdefgh');
prt('get all nodes: ' +n.getNodes().length         ); <span class="code-comment">//
4, incl n2	
</span>prt('get abcd: '      +n.getNodes('abcd').length   ); <span class="code-comment">//
1, abcd
</span>prt('get abcde*: '    +n.getNodes('abcde*').length ); <span class="code-comment">//
2, abcdef and abdefgh
</span>
<span class="code-comment">// remove()
</span>n.getNode('abcd').remove();
prt('removed abcd node ' + n.hasNode('abcd'));				<span class="code-comment">// <span
class="code-keyword">false</span>
</span>
<span class="code-comment">// get the root node (3 ways)
</span>prt( currentNode.getAncestor(0));
prt( currentNode.session.getRootNode());
prt( currentNode.getSession().getRootNode());

<span class="code-comment">// include the rendered result of another node (see Sling
in 15 minutes)
</span><span class="code-comment">// sling.include(<span class="code-quote">"/content/header"</span>,
<span class="code-quote">"forceResourceType=wiki.page,replaceSelectors=edit,replaceSuffix=validation"</span>);
</span>
function prt(s) { out.print(s+'&lt;br/&gt;&lt;br/&gt;'); }
%&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
</div></div>

<h2><a name="Scriptingvariables-Groovy"></a>Groovy</h2>

<p>An enhanced version of the GET.groovy script from <a href="http://sling.apache.org/site/groovy-support.html"
rel="nofollow">http://sling.apache.org/site/groovy-support.html</a> that shows all
the variables and a little of what's groovy about Groovy.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
response.setContentType(<span class="code-quote">"text/html"</span>);
response.setCharacterEncoding(<span class="code-quote">"UTF-8"</span>);

log.info <span class="code-quote">"Groovin' on ${resource}"</span>

def mb = <span class="code-keyword">new</span> groovy.xml.MarkupBuilder(out)

mb.html {

   <span class="code-comment">// Shouldn't javax.jcr.Property.getString() take care
of <span class="code-keyword">this</span> <span class="code-keyword">for</span>
us?
</span>   def formatMultipleValues = { prop -&gt;
      <span class="code-keyword">if</span> (prop.definition.isMultiple()) {
         prop.values.string.join('; ')
      } <span class="code-keyword">else</span> {
         prop.string
      }
   }
   
   def tableForMap = { cap, map -&gt;
      table {
         caption { h2 cap }
         tr { th 'property' ; th 'value' }
         map.each { key, value -&gt; tr { td key ; td value } }
      }
   }

   meta {
      title 'Groovy Scripting Sample <span class="code-keyword">for</span> Sling'
   }
   body {
      h1 <span class="code-quote">"Hello World !"</span> 
      p <span class="code-quote">"This is Groovy Speaking"</span> 
      p <span class="code-quote">"You requested the Resource ${resource} (yes, <span
class="code-keyword">this</span> is a GString)"</span>

      <span class="code-comment">// If we get called on a system file, then there won't
be a currentNode binding.
</span>      <span class="code-keyword">if</span> (<span class="code-keyword">this</span>.binding.variables.containsKey('currentNode'))
{
         table {
            caption { h2 'Current Node Properties' }
            tr { th 'property' ; th 'value' }
            currentNode.properties.each { prop -&gt; tr { td prop.name ; td formatMultipleValues(prop)
} }
         }
      }
      tableForMap 'Resource Properties', resource.properties
      tableForMap 'Script Bindings', <span class="code-keyword">this</span>.binding.variables
      tableForMap 'Request Properties', request.properties
   }
}
</pre>
</div></div>

<p>And what's up with the Java Content Repository API not using the Java Collections
API?  A repository is a collection after all.  Not very groovy...</p>

<p>Here's another example of using Groovy's MarkupBuilder with Sling <a href="http://n1ceone.blogspot.com/2008/09/using-groovy-builders-in-sling.html"
rel="nofollow">http://n1ceone.blogspot.com/2008/09/using-groovy-builders-in-sling.html</a>.</p>
     </div>
     <div id="commentsSection" class="wiki-content pageSection">
       <div style="float: right;">
            <a href="http://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
       </div>

       <a href="http://cwiki.apache.org/confluence/display/SLING/Scripting+variables">View
Online</a>
       |
       <a href="http://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=90231&revisedVersion=16&originalVersion=15">View
Change</a>
              |
       <a href="http://cwiki.apache.org/confluence/display/SLING/Scripting+variables?showComments=true&amp;showCommentArea=true#addcomment">Add
Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message