Reference Manual for Gracelets - 2.0.0.SP2SourceForge.net Logo
2.19 - Tutorial : Writing Gracelet Components
When writing a library, you may want to provide automatic resolution for certain variables inside view scripts and other libraries. You can do this with ScriptBindings. You can define this inside the same library as the other components previously discussed.

As an example, here is the JBossPCComponentLibrary that comes with the optional JBoss library. It automatically detects via class lookup if we are possibly in a JBoss EJB3 environment. Then if so it sets up script bindings so that the persistence contexts are automatically available in session context via their real names and puts a wrapper in the session context.

Toggle Line Numbers
1 package org.ponder.gracelets.libraries.jboss 
2  
3 import net.sourceforge.javautil.database.jpa.EntityManagerExtendedHandler 
4 import net.sourceforge.javautil.developer.web.library.jsf.data.JSFEntityManagerExtended 
5  
6 namespace = "http://gracelets.api.extension/jboss" 
7  
8 JBossJNDI jbossJNDI = new JBossJNDI() 
9 JBossMBean jbossMBean = new JBossMBean() 
10  
11 jndi = ScriptBindings( 
12     resolve: { name ->  
13         if (name == "jndi") return jbossJNDI 
14         if (name == "mbean") return jbossMBean 
15     } 
16 ) 
17  
18 def exists = false; 
19 try { 
20     exists = Class.forName("org.jboss.ejb3.PersistenceUnitRegistry", false, Thread.currentThread().contextClassLoader) != null; 
21     log.info("Enabling JBoss EJB3 Persistence Context Resolution") 
22     ejb = ScriptBindings( 
23         resolve: { name -> 
24             if (name == "ejb3PCWrappers") return null; 
25             if (ejb3PCWrappers == null) sessionContext.set("ejb3PCWrappers", [:]) 
26             if (!exists) return null; 
27             if (ejb3PCWrappers[name] != null) return ejb3PCWrappers[name] 
28             if (JBossExtendedEntityManager.storageNames.contains(name)) {  
29                 return ejb3PCWrappers[name] = EntityManagerExtendedHandler.createEMProxy( 
30                     new JBossExtendedEntityManager(name), JSFEntityManagerExtended.class 
31                 ); 
32             } 
33         } 
34     ) 
35 } catch (t) { 
36     exists = false; 
37     log.info("Disabling JBoss EJB3 Persistence Context Resolution") 
38 } 
As can be seen above you can define a closure called 'resolve'. This will work for lazy initialization. You can also define one called apply. The apply closure should return a map of string -> object relationships which will automatically be initialized on each Binding for each script, library and so forth.