Wiki source code of WritingComponents

Version 21.4 by Vincent Massol on 2009/08/21

Hide last authors
Anca Luca 1.1 1 1 Writing XWiki components
2
3 #toc("", "", "")
4
Vincent Massol 21.1 5 This tutorial guides you through the creation of an XWiki component, which replaces the Plugin architecture and which is now the recommended way of writing XWiki modules. They should be able to execute any Java code and communicate with XWiki by using the existing XWiki (core) components, as well as being exposed to the XWiki documents scripting environment (velocity and groovy).
Anca Luca 1.1 6
Vincent Massol 21.3 7 You should start by reading the [Reference document on XWiki Components>code:Modules.ComponentModule].
Anca Luca 1.1 8
Vincent Massol 21.2 9 #warning("The tutorial below is slightly outdated since some changes have been brought to the Component Module since it was written. See the [Reference document on XWiki Components>code:Modules.ComponentModule] for fresh information. This tutorial needs to be rewritten and duplicate with the Reference document removed.")
Anca Luca 1.1 10
11 1.1 Let's get started!
12
13 Enough talking, let's see some code!
14
15 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.
16
17 1.1.1 Creating a XWiki component using maven
18
19 To simplify the three steps process of component creation in XWiki, and since the XWiki code lifecycle is based on [maven>http://maven.apache.org/], we have created a maven archetype to help create a simple component module with a single command, with respect to the XWiki architecture and components specific requirements.
20 * download the archetype from here: {attach:xwiki-archetype-component-1.0-SNAPSHOT.jar} (it will soon be uploaded on our maven repository).
21 * use maven to install this file on your local repository by executing (make sure you replace <tt>path-to-jar-file</tt> with your own path):
22 {code}
23 mvn install:install-file -Dfile=<path-to-jar-file> -DartifactId=xwiki-archetype-component -DgroupId=com.xpn.xwiki.platform.tools -Dversion=1.0-SNAPSHOT -Dpackaging=jar
24 {code}
25 * now you're ready to use maven to generate the xwiki component based on this archetype. Navigate to the directory where you want your component to be located and type:
26 {code}
27 mvn archetype:generate -DarchetypeGroupId=com.xpn.xwiki.platform.tools -DarchetypeArtifactId=xwiki-archetype-component -DarchetypeVersion=1.0-SNAPSHOT -DgroupId=<component-group-id> -DartifactId=<component-artifact-id> -Dpackage=<component-package> -Dversion=<component-version> -Dpackaging=jar
28 {code}
29 where you replace <tt>component-group-id</tt>, <tt>component-artifact-id</tt>, <tt>component-package</tt>, <tt>component-version</tt> with the corresponding values for your component. To create a server XWiki Watch component, for example, we used <tt>-DgroupId=com.xpn.xwiki.products -DartifactId=xwiki-watch-component -Dpackage=org.xwiki.watch.component -Dversion=1.1-SNAPSHOT</tt>. Don't forget to follow the [xwiki package names guidelines > http://dev.xwiki.org/xwiki/bin/view/Community/CodeStyle#HPackagenames-1].
30
31 Now this will create a new maven module in a folder named <tt>component-artifact-id</tt> in your folder, with a default xwiki component inside.
32 #info("Note that if your parent (current, from where you are executing maven) folder is the folder of a maven module (contains a <tt>pom.xml</tt> file), then the command above will fail unless the module is packaged as <tt>pom</tt>. If the project is packaged as <tt>pom</tt>, then the newly created module will be added in its modules list, and the parent of the newly created component module will be set to this project's <tt>pom</tt>.")
33
34 1.1.1 The component explained
35
36 Assume, for the following explanations, that the package you used is <tt>org.xwiki.component</tt>
37
38 Navigating in the component project folder, you will see standard maven project structure like this:
39 {code}
40 pom.xml
41 src/main/java/org/xwiki/component/HelloWorld.java
42 src/main/java/org/xwiki/component/internal/DefaultHelloWorld.java
dan 19.1 43 src/main/resources/META-INF/components.txt
Anca Luca 1.1 44 src/test/java/org/xwiki/component/HelloWorldTest.java
45 {code}
dan 19.1 46 which corresponds to the default files created: the <tt>HelloWorld</tt> interface (service), its implementation <tt>DefaultHelloWorld</tt>, a test class for this component <tt>HelloWorldTest</tt>, the component declaration file <tt>components.txt</tt> and the maven project <tt>pom</tt> file.
Anca Luca 1.1 47
48 If we have a look in the <tt>pom</tt>, we see something like this:
49 {code}
50 <groupId>your-group-id</groupId>
51 <artifactId>your-artifact-id</artifactId>
52 <version>your-version</version>
53 {code}
54 which are the group, artifact and version you used when you created your component
55 {code}
56 <properties>
57 <!-- TODO: remove this if you inherit a project that has the core version set -->
Anca Luca 17.2 58 <platform.core.version>1.8-SNAPSHOT</platform.core.version>
Anca Luca 1.1 59 </properties>
60 {code}
61 used to define the core version for the xwiki-component dependency. If your component is created as part of a project already depending on the core (and which most probably already has a property for the core version), use the inherited property value instead of redefining it here. Or, if the component should have the same version as the rest of the XWiki modules, you can use <tt>${pom.version}</tt> as the version for other XWiki dependencies.
62 {code}
63 <dependencies>
64 <dependency>
65 <groupId>org.xwiki.platform</groupId>
66 <artifactId>xwiki-core-component</artifactId>
67 <version>${platform.core.version}</version>
68 </dependency>
69 <dependency>
70 <groupId>junit</groupId>
71 <artifactId>junit</artifactId>
72 <version>3.8.1</version>
73 <scope>test</scope>
74 </dependency>
75 <!-- Add here all your other dependencies -->
76 </dependencies>
77 {code}
78 which define the dependency on the xwiki-component module in the core and the junit for the testing phase and, of course, marks the spot for you to add all your other components, modules, and libraries dependencies for maven to know and put them on your classpath when compiling, etc.
79
dan 19.1 80 The interface file (<tt>HelloWorld.java</tt>) contains the definition of a regular Java interface, and looks like this:
Anca Luca 1.1 81 {code}
dan 19.1 82 @ComponentRole /* annotation used for declaring the service our component will provide */
83 public interface HelloWorld
84 {
85 String sayHello();
86 }
Anca Luca 1.1 87 {code}
88
dan 19.1 89 Keep in mind that only this interface specifies the functions the other components will use to communicate with our component, no other functions besides the ones defined in this interface will be accessible to the "outside world". In our case, we'll build a polite component that can only <tt>sayHello()</tt>.
Anca Luca 1.1 90
91 Then we have the implementation of the interface, the <tt>DefaltHelloWorld</tt> class.
92 {code}
dan 19.2 93 @Component
Anca Luca 1.1 94 public class DefaultHelloWorld extends AbstractLogEnabled implements HelloWorld, Initializable
95 {code}
dan 19.1 96
dan 19.2 97 Notice the <tt>@Component</tt> annotation used for declaring the implementation for the component. Optionally, a component implementation can have a ~~hint~~ assigned. This is useful especially when we want to distinguish between several implementations for the same type of component. In this case, the <tt>DefaltHelloWorld</tt> class would look like this:
98 {code}
99 @Component("myCustomHelloWorld")
100 public class DefaultHelloWorld extends AbstractLogEnabled implements HelloWorld, Initializable
101 {code}
dan 20.1 102 We can go even deeper into more advanced issues and specify multiple component hints for the same implementation, if we want. This can be done as follows:
103 {code}
104 @Component(hints = {"info", "warning", "error" })
105 public class DefaultHelloWorld extends AbstractLogEnabled implements HelloWorld, Initializable
106 {code}
dan 19.1 107
dan 19.2 108 This class extends <tt>AbstractLogEnabled</tt> to be able to use the logging system, implements the component interface, and also the <tt>Initializable</tt> interface which allows it to hook initialization code upon its instantiation by the component manager, in the <tt>initialize()</tt> function:
109
Anca Luca 1.1 110 {code}
dan 19.1 111 public void initialize() throws InitializationException
112 {
113 // TODO: initialize component
114 // getLogger is inherited from AbstractLogEnabled
115 getLogger().debug("DefaultHelloWorld initialized");
116 }
Anca Luca 1.1 117 {code}
118
119 {code}
120
dan 19.1 121 /**
122 * Says hello by returning a greeting to the caller.
123 *
124 * @return A greeting.
125 */
126 public String sayHello()
127 {
128 return "Hello world!";
129 }
Anca Luca 1.1 130 {code}
131
dan 19.1 132 And now, the <tt>components.txt</tt>:
Anca Luca 1.1 133 {code}
dan 19.1 134 org.xwiki.component.internal.DefaultHelloWorld
Anca Luca 1.1 135 {code}
136
137
138 1.1 How to find my component and use it?
139
140 1.1.1 From other components
141
142 To access your component from another component we use the components engine, and specify the dependencies declarative, leaving instantiation and component injection to the be handled by the component manager. The most straightforward way is the use of the requirements mechanism of plexus, specifying that our component is required by the component that needs to access it.
143
144 Don't forget that any code that uses the component we wrote needs to have the component interface accessible in its classpath. Even if instantiation and dependency is handled by the engine at runtime, the code still needs to compile.
145 If the two components are not in the same module (the same .jar), don't forget to add the module of the greeter component as a dependency of the module of any component that uses it.
146
147 Then, to effectively use the <tt>HelloWorld</tt> component, we need a reference to it in the the component that uses it. For this, we use a member variable in the implementation of the using component, for example, a <tt>Socializer</tt> component will need to be able to say hello to the world:
148 {code}
dan 19.1 149 @Component
Anca Luca 1.1 150 public class DefaultSocializer extends AbstractLogEnabled implements Socializer, Initializable
151 {
152 [...]
153
154 /** Will be injected by the component manager */
dan 19.1 155 @Requirement
Anca Luca 1.1 156 private HelloWorld helloWorld;
157
158 [...]
159 }
160 {code}
161
dan 19.1 162 Note the <tt>@Requirement</tt> annotation, which instructs the component manager to inject the required component where needed.
163
164 And the <tt>components.txt</tt>
Anca Luca 1.1 165 {code}
dan 19.1 166 org.xwiki.component.internal.DefaultSocializer
Anca Luca 1.1 167 {code}
168
169 And that's it, you can now use the <tt>helloWorld</tt> member anywhere in the <tt>DefaultSocializer</tt> class freely, without further concerns, it will be assigned by the component manager provided that the <tt>HelloWorld</tt> component is on the classpath at runtime when the <tt>Socializer</tt> is used. Such as:
170
171 {code}
172 public class DefaultSocializer extends AbstractLogEnabled implements Socializer, Initializable
173 {
174 [...]
175
176 public void startConversation()
177 {
178 this.helloWorld.sayHello();
179
180 [...]
181 }
182
183 [...]
184 }
185 {code}
186
187 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.
188
189 TODO: refer to the other ways of implementing dependencies but requirements mechanism. Details, explanations, links.
190
191 1.1.1 From non-components java code (e.g. older plugins)
192
dan 19.2 193 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 <tt>com.xpn.xwiki.web.Utils.getComponent(String role, String hint)</tt> 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 <tt>role</tt>, 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 > http://plexus.codehaus.org/guides/developer-guide/building-components/component-identity.html]). The <tt>getComponent</tt> function also has a version without the <tt>hint</tt> parameter, that uses the default hint.
Anca Luca 1.1 194
195 To use our greetings provider component, we simply invoke:
196 {code}
dan 19.1 197 HelloWorld greeter = (HelloWorld) Utils.getComponent(HelloWorld.class);
Anca Luca 1.1 198 //use the HelloWorld service
199 greeter.sayHello();
200 {code}
201
dan 19.1 202 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.
Anca Luca 1.1 203
dan 19.1 204 #info("The usage of <tt>Utils.getComponent()</tt> 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.")
Anca Luca 15.1 205
Anca Luca 1.1 206 1.1.1 From wiki pages
207
208 In order to use a component in wiki pages, we need to expose it to the scripting environments: groovy and velocity.
209
210 1.1.1.1 Accessing a component from groovy
211
Anca Luca 5.1 212 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 > WritingComponents#HFromnoncomponentsjavacode28egolderplugins29], using the <tt>Utils</tt> class. A simple page that would print the greeting from the <tt>HelloWorld</tt> component would look like this (of course, with your own package for the HelloWorld interface):
Anca Luca 1.1 213
214 {code}
215 <%
dan 19.1 216 def greeter = com.xpn.xwiki.web.Utils.getComponent(org.xwiki.component.HelloWorld.class);
Anca Luca 1.1 217 println greeter.sayHello();
218 %>
219 {code}
220
221 TODO: talk about the future plans (?) to make a component accessible in the groovy context through a groovy bridge.
222
223 1.1.1.1 Accessing a component from velocity
224
225 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:
226
Anca Luca 17.3 227 We write another component in our package, that implements the <a href="http://svn.xwiki.org/svnroot/xwiki/platform/core/trunk/xwiki-velocity/src/main/java/org/xwiki/velocity/VelocityContextInitializer.java"><tt>VelocityContextInitializer</tt></a>, which is responsible for the initialization of the velocity context in XWiki through its method <tt>initialize(VelocityContext context)</tt>, called automatically when a new velocity context is created. As you probably guessed, we will use this function to add our <tt>HelloWorld</tt> component to the velocity context.
Anca Luca 1.1 228
229 {code}
Vincent Massol 21.4 230 @Component("helloWorld")
Anca Luca 1.1 231 public class HelloWorldVelocityContextInitializer implements VelocityContextInitializer
232 {
233 /** The key to add to the velocity context */
234 public static final String VELOCITY_CONTEXT_KEY = "greeter";
235
236 /** The component instance to add to the velocity context, injected by the component manager */
dan 19.2 237 @Requirement
Anca Luca 1.1 238 private HelloWorld helloWorld;
239
240 /**
241 * Add the component instance to the velocity context received as parameter.
242 */
243 public void initialize(VelocityContext context)
244 {
245 context.put(VELOCITY_CONTEXT_KEY, this.helloWorld);
246 }
247 }
248 {code}
249
250 The result of this will be the availability of the <tt>HelloWorld</tt> instance in velocity through the key ~~greeter~~ (as in <tt>$greeter.sayHello()</tt>).
251
252 Of course, we need to have our <tt>HelloWorld</tt> component reference when we execute this code so we add it as a dependency to this velocity context initializer component, as described in [the section above>#HFromothercomponents]:
253 {code}
dan 19.1 254 org.xwiki.component.internal.vcinitializer.HelloWorldVelocityContextInitializer
Anca Luca 1.1 255 {code}
256
dan 19.1 257 This code goes in the <tt>components.txt</tt> file of the package where the velocity context initializer is located. In our case, in the same file as the description for the <tt>HelloWorld</tt> is.
Anca Luca 1.1 258
dan 19.1 259 Note that this time, we also use roles for component identification, because we need to differentiate this implementation of the <tt>VelocityContextInitializer</tt> from the other implementations, as it is not the only component with this role in XWiki.
Anca Luca 1.1 260
261 Of course, in order to for all this to compile, we need to have the <tt>VelocityContextInitializer</tt> interface available on the classpath so we have this new dependency in the component module's pom:
262 {code}
263 <dependency>
264 <groupId>org.xwiki.platform</groupId>
265 <artifactId>xwiki-core-velocity</artifactId>
266 <version>${platform.core.version}</version>
267 </dependency>
268 {code}
269
270 And that's it, you have made your <tt>HelloWorld</tt> 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:
271 {code}
272 $greeter.sayHello()
273 {code}
274
Anca Luca 5.1 275 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 {attach:xwiki-archetype-velocity-component-1.0-SNAPSHOT.jar}. Download it and use it as described in [the first part of this tutorial > WritingComponents#HCreatingaXWikicomponentusingmaven].
Anca Luca 1.1 276
277
278
279
280
281
282
283
Anca Luca 15.1 284
Anca Luca 1.1 285 1.1 How do I find other code?
286
287 1.1.1 The XWiki data model
288
289 Since the XWiki data model (documents, objects, attachments, etc.) reside in the big, old <tt>xwiki-core</tt> 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 <tt>xwiki-core</tt>.
290
291 In short, the way this works is based on the fact that implementations for a component don't have to be in the same <tt>.jar</tt> 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 <tt>xwiki-core</tt> as the default implementation for those components.
292
Anca Luca 3.1 293 If your component needs to access the XWiki data model, it will use the components from the <tt>xwiki-core-bridge</tt> 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>dev:Community.MailingLists].
Anca Luca 1.1 294
295 For example:
296 {code}
dan 19.1 297 @Component
Anca Luca 1.1 298 public class DefaultHelloWorld implements HelloWorld
299 {
300 /** Provides access to documents. Injected by the Component Manager. */
dan 19.1 301 @Requirement
Anca Luca 1.1 302 private DocumentAccessBridge documentAccessBridge;
303
304 [...]
305
306 private String getConfiguredGreeting()
307 {
308 return documentAccessBridge.getProperty("XWiki.XWikiPreferences", "greeting_text");
309 }
310 {code}
311
312 1.1.1 The XWiki context
313
314 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>http://en.wikipedia.org/wiki/Ball_and_chain] present everywhere in the code.
315
316 In the component world, the current request information is held in an *[execution context>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core-context/apidocs/org/xwiki/context/ExecutionContext.html]*. 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>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core-context/apidocs/org/xwiki/context/Execution.html]*, which you can use just like any other XWiki component.
317
318 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 <tt>Execution</tt> component (located in the <tt>xwiki-core-context</tt> module), and then you can write:
319 {code}
320 /** Provides access to the request context. Injected by the Component Manager. */
dan 19.1 321 @Requirement
Anca Luca 1.1 322 private Execution execution;
323
324 [...]
325
326 private void workWithTheContext()
327 {
328 ExecutionContext context = execution.getContext();
329 // Do something with the execution context
330 }
331 {code}
332
333 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 <tt>XWikiContext</tt>, which would pull the whole xwiki-core as a dependency, but to a <tt>Map</tt>. 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.
334 {code}
335 private void workWithTheContext()
336 {
337 ExecutionContext context = execution.getContext();
338 Map<Object, Object> xwikiContext = (Map<Object, Object>) context.getProperty("xwikicontext");
339 // Do something with the XWiki context
340 }
341 {code}
342
343 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>http://maven.xwiki.org/site/xwiki-core-parent/xwiki-core-context/apidocs/org/xwiki/context/ExecutionContextInitializer.html] component, and populate newly created execution contexts, just like with [velocity contexts>#HAccessingacomponentfromvelocity].
344
345 1.1.1 Code outside components
346
347 You can use external libraries as in any other maven module, just declare the right dependencies in your module's <tt>pom.xml</tt>.
348
349 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 <tt>xwiki-core</tt> 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.
350
Anca Luca 4.1 351 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>dev:Community.MailingLists], so that we can design and implement it collaboratively.
Anca Luca 1.1 352
353 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.
354
355
356
357

Get Connected