Create a component using Groovy

Last modified by Manuel Leduc on 2023/10/10 16:48

cogCreates a component which retrieves all the documents with a certain author
TypeSnippet
Category
Developed by

Oana Florea

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Description

Please refer instead to the Groovy Script Service Tutorial. This snippet is deprecated since the introduction of wiki components. Also, bear in mind this snippet has a major downside: it requires the page containing it to be viewed at least once for the component to be correctly registered, hence the need of a scheduler, which is overkill.

XWiki components can be written in Java, but also using Groovy.

{{groovy}}
import org.xwiki.component.descriptor.*;
import org.xwiki.script.service.*;
import org.xwiki.context.*;
import com.xpn.xwiki.web.*;

class TestComponent implements ScriptService {
  org.xwiki.context.Execution e;
  List<String> getDocsByAuthor(String authorFullName) {
    def context = e.getContext().getProperty("xwikicontext");
    def hql = " where doc.author=(?)";
    def results = context.getWiki().getStore().searchDocuments(hql,0, 0, [authorFullName], context);
    print results;
   if (results.size() > 0) {
     return results;
    }
   return [];
 }
}
DefaultComponentDescriptor descriptor = new DefaultComponentDescriptor(implementation: TestComponent.class, role: ScriptService.class, roleHint: 'testComponent');
DefaultComponentDependency dep = new DefaultComponentDependency(name: 'e', role: Execution.class, roleHint: 'default');
descriptor.addComponentDependency(dep);
def cm = services.component.getComponentManager(null)
cm.unregisterComponent(ScriptService.class, 'testComponent');
cm.registerComponent(descriptor);
{{/groovy}}

The component must be registered once by executing the code above: either manually view the page containing the code or put the code in a scheduled job with very frequent trigger to auto-register after the server restarts

Accessing the component from Velocity

{{velocity}}
$services.testComponent.getDocsByAuthor("XWiki.SimpleUser");
{{/velocity}}

Other component implementations

Get Connected