Create a component using Groovy
Last modified by Manuel Leduc on 2025/02/12 12:24
![]() | Creates a component which retrieves all the documents with a certain author |
Type | Snippet |
Category | |
Developed by | |
Rating | |
License | GNU Lesser General Public License 2.1 |
Description
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}}
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}}
$services.testComponent.getDocsByAuthor("XWiki.SimpleUser");
{{/velocity}}