Writing XWiki components

Version 30.2 by Vincent Massol on 2010/11/14

This tutorial guides you through the creation of an XWiki component, which is a way to extend or customize the XWiki platform. Indeed the XWiki platform is composed of components and it's possible to replace the default implementations with your own implementations. It's also possible to add new component implementations to extend the platform such as by implementing new Rendering Macros.

Components replace the older Plugin architecture which has been deprecated a while ago.

You should start by reading the Reference document on XWiki Components.

Let's get started!

Enough talking, let's see some code!

In the followings we will guide you through writing a simple component, helping you to quickly get oriented in XWiki components world and explaining how it works.

Creating a XWiki component using Maven

As you've read in the XWiki Component Reference writing a component is  a three-streps process (component interface, component implementation, registration of component). To make it easier for you to get started, we have created a maven archetype to help create a simple component module with a single command. 

After you've [installed Maven>http://dev.xwiki.org/xwiki/bin/view/Community/Building#HInstallingMaven], open a shell prompt an type:
 mvn archetype:generate -DarchetypeCatalog=http://svn.xwiki.org/svnroot/xwiki/platform/xwiki-tools/trunk/xwiki-archetypes/xwiki-archetype-component/archetype-catalog.xml

Then follow the instructions. For example:
vmassol@target $ mvn archetype:generate -DarchetypeCatalog=http://svn.xwiki.org/svnroot/xwiki/platform/xwiki-tools/trunk/xwiki-archetypes/xwiki-archetype-component/archetype-catalog.xml
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
1: http://svn.xwiki.org/svnroot/xwiki/platform/xwiki-tools/trunk/xwiki-archetypes/xwiki-archetype-component/archetype-catalog.xml -> xwiki-archetype-component (Make it easy to create a maven project for creating a XWiki Component.)
Choose a number: : 1
Downloading: http://maven.xwiki.org/snapshots/org/xwiki/platform/tools/xwiki-archetype-component/1.0-SNAPSHOT/maven-metadata.xml
Downloaded: http://maven.xwiki.org/snapshots/org/xwiki/platform/tools/xwiki-archetype-component/1.0-SNAPSHOT/maven-metadata.xml (383 B at 3.4 KB/sec)
Downloading: http://maven.xwiki.org/snapshots/org/xwiki/platform/tools/xwiki-archetype-component/1.0-SNAPSHOT/maven-metadata.xml
Downloaded: http://maven.xwiki.org/snapshots/org/xwiki/platform/tools/xwiki-archetype-component/1.0-SNAPSHOT/maven-metadata.xml (383 B at 4.9 KB/sec)
Define value for property 'groupId': : com.acme
Define value for property 'artifactId': : example
Define value for property 'version':  1.0-SNAPSHOT: :
Define value for property 'package':  com.acme: :
Confirm properties configuration:
groupId: com.acme
artifactId: example
version: 1.0-SNAPSHOT
package: com.acme
 Y: : Y
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: xwiki-archetype-component:1.0-SNAPSHOT
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.acme
[INFO] Parameter: packageName, Value: com.acme
[INFO] Parameter: package, Value: com.acme
[INFO] Parameter: artifactId, Value: example
[INFO] Parameter: basedir, Value: /Users/vmassol/dev/xwiki/trunks-clean4/platform/tools/xwiki-archetypes/target
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] ********************* End of debug info from resources from generated POM ***********************
[INFO] project created from Old (1.x) Archetype in dir: /Users/vmassol/dev/xwiki/trunks-clean4/platform/tools/xwiki-archetypes/target/example
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.868s
[INFO] Finished at: Sun Nov 14 18:27:52 CET 2010
[INFO] Final Memory: 9M/81M
[INFO] ------------------------------------------------------------------------
vmassol@target $ 

Then go in the created directory (example in our example above) and run mvn install to build your component.

The Component explained

Assume, for the following explanations, that the package you used is com.acme

Navigating in the component project folder, you will see the following standard Maven project structure:

pom.xml
src/main/java/com/acme/HelloWorld.java
src/main/java/com/acme/internal/DefaultHelloWorld.java
src/main/resources/META-INF/components.txt
src/test/java/com/acme/HelloWorldTest.java

which corresponds to the default files created: the HelloWorld interface (a.k.a component role), its implementation DefaultHelloWorld (component implementation), a test class for this component HelloWorldTest, the component declaration file components.txt and the Maven project pom.xml file.

If you have a look in the pom.xml, you'll notice the following dependencies:

  <dependencies>
   <dependency>
     <groupId>org.xwiki.platform</groupId>
     <artifactId>xwiki-core-component-default</artifactId>
     <version>${platform.core.version}</version>
   </dependency>
   <!-- Testing dependencies -->
   <dependency>
     <groupId>org.xwiki.platform</groupId>
     <artifactId>xwiki-core-shared-tests</artifactId>
     <version>${platform.core.version}</version>
     <scope>test</scope>
   </dependency>
 </dependencies>

The code above defines the dependency on the xwiki-core-component-default in the core which is where XWiki Component notions are defined. There's also a dependency on xwiki-core-shared-tests which provides helper classes to easily test components.

The interface file (HelloWorld.java) contains the definition of a regular Java interface, and looks like this: 

@ComponentRole /* annotation used for declaring the service our component provides */
public interface HelloWorld
{
    String sayHello();
}

Keep in mind that this interface specifies the API that other components can use on your component. In our case, we'll build a polite component that can sayHello().

Then we have the implementation of the interface, the DefaltHelloWorld class. 

@Component /* annotation used for declaring a component implementation */
public class DefaultHelloWorld implements HelloWorld

Note that optionally, the @Component annotation can specify a hint. This is useful especially when we want to distinguish between several implementations for the same type of component. Image we had a special HelloWorld implementation taking the greeting message from a database; it could look lile:

@Component("database")
public class DatabaseHelloWorld implements HelloWorld

Then the sayHello in DefaultHelloWorld is basic in this example:

/**
 * Says hello by returning a greeting to the caller.
 *
 * @return A greeting.
 */

public String sayHello()
{
  return "Hello world!";
}

And now, the components.txt file, in which component implementations present in this jar are specified for the ComponentManager to register them.

com.acme.internal.DefaultHelloWorld

How to find my component and use it?

From other components

To access your component from another component we use the components engine, and specify the dependencies, leaving instantiation and component injection to the be handled by the component manager.

In order to use the HelloWorld component, you need a reference to it in the the component that uses it. For this, you should use a member variable in the implementation of the using component, for example, a Socializer component will need to be able to say hello to the world:

@Component
public class DefaultSocializer implements Socializer
{
    
[...]

    
/** Will be injected by the component manager */
    
@Requirement
    
private HelloWorld helloWorld;

    
[...]
}

Note the @Requirement annotation, which instructs the component manager to inject the required component where needed.

And that's it, you can now use the helloWorld member anywhere in the DefaultSocializer class freely, without further concerns, it will be assigned by the component manager provided that the HelloWorld component is on the classpath at runtime when the Socializer is used. Such as:

public class DefaultSocializer implements Socializer
{
    [...]

   public void startConversation()
   {
        this.helloWorld.sayHello();
       
        [...]
   }

    [...]
}

More, note that all through the process of defining a communication path between two components, we never referred components implementations, all specifications being done through roles and interfaces: the implementation of a service is completely hidden from any code external to the component.

From non-components java code (e.g. older plugins)

TODO: Update tutorial from this point forward since it hasn't been revised yet

For this kind of usages, since we cannot use the component-based architecture advantages and the "magic" of the component manager, the XWiki team has created a helper method that acts like a bridge between component code and non-component code, the com.xpn.xwiki.web.Utils.getComponent(String role, String hint) that gets the specified component instance from the component manager and returns it. As seen in the previous sections, the hint is an optional identifier, additional to role, used to differentiate between implementations of the same interface: the roles identify services while the hints help differentiate between implementations (see more at http://plexus.codehaus.org/guides/developer-guide/building-components/component-identity.html). The getComponent function also has a version without the hint parameter, that uses the default hint.

To use our greetings provider component, we simply invoke:

HelloWorld greeter = (HelloWorld) Utils.getComponent(HelloWorld.class);
//use the HelloWorld service
greeter.sayHello();

Note that, even if, in fact, the object returned by this function is an instance of the DefaultHelloWorld, you should never declare your object of the implementation type nor cast to implementation instead of interface. A component is represented by its interface, the implementation for such a service can be provided by any code, any class so relying on the implementation type is neither good practice (since the interface contract should be enough for a component), nor safe. In the future, a maven enforcer plugin will be setup in the build lifecycle, so that any reference to component implementations (located in an "internal" subpackage) will cause build errors.

The usage of Utils.getComponent() functions is highly discouraged, reserved for this type of situations, when you need to access a component from non-componentized code. For the componentized code, you should use either dependency declaration at 'compile-time' (as shown before with annotations) or, if you need to resolve components dependencies at runtime, use the ComponentManager, which you can access by implementing the Composable interface described above.

From wiki pages

In order to use a component in wiki pages, we need to expose it to the scripting environments: groovy and velocity.

Accessing a component from groovy

Since, in groovy, we have access to all classes and functions in XWiki (all this protected by the requirement for programming rights), it means that we can use the same method as in the previous section, using the Utils class. A simple page that would print the greeting from the HelloWorld component would look like this (of course, with your own package for the HelloWorld interface):

<%
def greeter = com.xpn.xwiki.web.Utils.getComponent(org.xwiki.component.HelloWorld.class);
println greeter.sayHello();
%>

TODO: talk about the future plans help to make a component accessible in the groovy context through a groovy bridge.

Accessing a component from velocity

XWiki dev team is currently working on the design of a VelocityBridge interface that will handle components access from velocity. Until this specification is ready and its first implementation done, we can do it as follows:

We write another component in our package, that implements the VelocityContextInitializer, which is responsible for the initialization of the velocity context in XWiki through its method initialize(VelocityContext context), called automatically when a new velocity context is created. As you probably guessed, we will use this function to add our HelloWorld component to the velocity context.

@Component("helloWorld")
public class HelloWorldVelocityContextInitializer implements VelocityContextInitializer
{
    
/** The key to add to the velocity context */
    
public static final String VELOCITY_CONTEXT_KEY = "greeter";
   
    
/** The component instance to add to the velocity context, injected by the component manager */
    
@Requirement
    
private HelloWorld helloWorld;

    
/**
     * Add the component instance to the velocity context received as parameter.
     */

    
public void initialize(VelocityContext context)
    
{
        
context.put(VELOCITY_CONTEXT_KEY, this.helloWorld);
    
}
}

The result of this will be the availability of the HelloWorld instance in velocity through the key greeter (as in $greeter.sayHello()).

This instance of HelloWorld will be injected by the component manager in the helloWorld member, due to the @Requirement annotation.

In order to have the VelocityContextInitializer component accessible to the component manager, therefore initialized indeed when a velocity context is created, we specify it as a component in the components.txt file (in our case, the same file where we have DefaultHelloWorld component):

[...]
org.component.internal.vcinitializer.HelloWorldVelocityContextInitializer

Note that this time, we specify a hint for component identification, because we need to differentiate this implementation of the VelocityContextInitializer from the other implementations, as it is not the only component with this role in XWiki. 

Of course, in order to for all this to compile, we need to have the VelocityContextInitializer interface available on the classpath so we have this new dependency in the component module's pom:

<dependency>
     <groupId>org.xwiki.platform</groupId>
     <artifactId>xwiki-core-velocity</artifactId>
     <version>${platform.core.version}</version>
   </dependency>

And that's it, you have made your HelloWorld component velocity-accessible! Just recompile your package, copy it in the WEB-INF/lib folder of your xwiki webbapp container, and restart the server. You'll be able to get a greeting in velocity through:

$greeter.sayHello()

For the automatic creation of a velocity accessible xwiki component through this method, we have also created a maven archetype for this purpose too, the xwiki-archetype-velocity-component-1.0-SNAPSHOT.jar. Download it and use it as described in the first part of this tutorial.

How do I find other code?

The XWiki data model

Since the XWiki data model (documents, objects, attachments, etc.) reside in the big, old xwiki-core module, and since we don't want to add the whole core and all its dependencies as a dependency of a simple lightweight component (this would eventually lead to a circular dependency, which is not allowed by maven), the current strategy, until the data model is completely turned into a component, is to use a bridge between the new component architecture and the old xwiki-core.

In short, the way this works is based on the fact that implementations for a component don't have to be in the same .jar as the interface, and there is no dependency from the component interface to the actual implementation, only the other way around. So, we made a few simple components that offer basic access to XWiki documents, and declared the classes in xwiki-core as the default implementation for those components.

If your component needs to access the XWiki data model, it will use the components from the xwiki-core-bridge module for that. Note that these interfaces are rather small, so you can't do everything that you could with the old model. If you need to add some methods to the bridge, feel free to propose it on the mailing list.

For example:

@Component
public class DefaultHelloWorld implements HelloWorld
{
   /** Provides access to documents. Injected by the Component Manager. */
    @Requirement
   private DocumentAccessBridge documentAccessBridge;

    [...]

   private String getConfiguredGreeting()
    {
       return documentAccessBridge.getProperty("XWiki.XWikiPreferences", "greeting_text");
    }

The XWiki context

Note that the XWiki context is deprecated. It was an older way of keeping track of the current request, which had to be passed around from method to method, looking like a ball and chain present everywhere in the code.

In the component world, the current request information is held in an execution context. This is actually more powerful than the old XWiki context, as it is a generic execution context, and you can create one anytime you want and use it anyway you want. And you don't have to manually pass it around with all method calls, as execution contexts are managed by the Execution component, which you can use just like any other XWiki component.

In short, if you want to get access to the execution context (which holds context information inserted by the new components), you must declare a requirement on the Execution component (located in the xwiki-core-context module), and then you can write:

/** Provides access to the request context. Injected by the Component Manager. */
    @Requirement
   private Execution execution;

    [...]

   private void workWithTheContext()
    {
       ExecutionContext context = execution.getContext();
       // Do something with the execution context
    }

If you still need to access the old XWiki context, then you can get a reference to it from the execution context, but you should not cast it to an XWikiContext, which would pull the whole xwiki-core as a dependency, but to a Map. You won't be able to access all the properties, like the current user name or the URL factory, but you can access anything placed in the internal map of the XWikiContext.

private void workWithTheContext()
    {
       ExecutionContext context = execution.getContext();
       Map<Object, Object> xwikiContext = (Map<Object, Object>) context.getProperty("xwikicontext");
       // Do something with the XWiki context
    }

If you want not just to use the execution context, but to make something available in every execution context, you can create an implementation of the ExecutionContextInitializer component, and populate newly created execution contexts, just like with velocity contexts.

Code outside components

You can use external libraries as in any other maven module, just declare the right dependencies in your module's pom.xml.

As a general rule, you should not work with any non-componentized XWiki code, as the way the old code was designed leads to an eventual dependency on the whole xwiki-core module, which we are trying to avoid. If the component you are writing is needed by other modules (which is the case with most components, since a component which isn't providing any usable/used services is kind of useless), then this will likely lead to an eventual cyclic dependency, which will break the whole build.

If you need some functionality from the old core, consider rewriting that part as a new component first, and then use that new component from your code. You should ask first on the devs mailing list, so that we can design and implement it collaboratively.

If the effort needed for this is too large, you can try creating a bridge component, by writing just the interfaces in a new module, and make the classes from the core the default implementation of those interfaces. Then, since in the end the xwiki-core, the bridge component and your component will reside in the same classpath, plexus will take care of coupling the right classes. Be careful when writing such bridges, as they are short lived (since in the end all the old code will be replaced by proper components), and if the future real component will have a different interface, then you will have to rewrite your code to adapt to the new method names, or worse, the new component logic.

Deploying and using the component

In order to have your component work with XWiki, build the maven module, and find the produced .jar in the target folder. Copy this .jar to the /WEB-INF/lib folder of your wiki instance, restart the servlet container and you're done: you should be able to access your component from velocity or groovy code, and other potential components depending on it should be able to look it up.

Tags:
   

Get Connected