Configuring the ServiceRegistry as a Javascript Root Object

From AlfrescoWiki

Jump to: navigation, search


Contents


[edit] Introduction

In some cases you may have a need to call the Alfresco Foundation Services API from a Javascript script running within the Alfresco server.

One way to expose this object to Javascript scripts is to use the technique described at Adding Custom Script APIs to inject a proxy of the ServiceRegistry as a root scope Javascript object.

[edit] Configuring the Service Registry as a Javascript Root Object

Because the ServiceRegistry is not suitable for direct injection as a Javascript root object, the following proxy class (which simply delegates all calls to the real ServiceRegistry) can be used instead, providing equivalent behaviour:

public class JavascriptCompatibleServiceRegistry
    extends BaseProcessorExtension
    implements ServiceRegistry
{
    private ServiceRegistry impl;

    public setServiceRegistry(final ServiceRegistry impl)
    {
        this.impl = impl;
    }

    /**
     * @see org.alfresco.service.ServiceRegistry#getAVMLockingAwareService()
     */
    public AVMService getAVMLockingAwareService()
    {
        return(impl.getAVMLockingAwareService());
    }

    // ...
    // Other getters in ServiceRegistry go here
    // ...

    /**
     * @see org.alfresco.service.ServiceRegistry#isServiceProvided(org.alfresco.service.namespace.QName)
     */
    public boolean isServiceProvided(final QName qname)
    {
        return(impl.isServiceProvided(qname));
    }
}

The new root scope object is registered with the scripting framework in a custom Spring application context:

<bean id="javascriptServiceRegistry" parent="baseJavaScriptExtension" class="org.alfresco.repo.jscript.JavascriptCompatibleServiceRegistry">
  <property name="serviceRegistry" ref="ServiceRegistry" />
  <property name="extensionName"   value="serviceRegistry" />
</bean>

After this is done, scripts will have a new root scope object called "serviceRegistry" available that can be used to interact with the Alfresco Foundation Services API:

var avmService = serviceRegistry.getAVMService();
var stores     = avmService.getStores();
var result     = "List of AVM stores and versions:\n";

for (var i = 0; i < stores.size(); i++)
{
  var store     = stores.get(i);
  var storeName = store.getName();
  result += "\t" + storeName  + "@v" + avmService.getNextVersionID(storeName) + "\n";
}



Return to JavaScript API