Wiki source code of WritingComponents

Version 26.1 by Silvia Macovei on 2010/02/25

Show last authors
1 = Writing XWiki components =
2
3 {{toc start="" depth="" numbered=""/}}
4
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).
6
7 You should start by reading the [[Reference document on XWiki Components>>code:Modules.ComponentModule]].
8
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.{{/warning}}
10
11 == 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 === 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
21 * download the archetype from here: attach:xwiki-archetype-component-1.0-SNAPSHOT.jar (it will soon be uploaded on our maven repository).
22 * use maven to install this file on your local repository by executing (make sure you replace ##path-to-jar-file## with your own path):
23
24 {{code}}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{{/code}}
25
26 * 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:
27
28 {{code}}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{{/code}}
29
30 where you replace ##component-group-id##, ##component-artifact-id##, ##component-package##, ##component-version## with the corresponding values for your component. To create a server XWiki Watch component, for example, we used ##-DgroupId=com.xpn.xwiki.products -DartifactId=xwiki-watch-component -Dpackage=org.xwiki.watch.component -Dversion=1.1-SNAPSHOT##. Don't forget to follow the [[xwiki package names guidelines>>http://dev.xwiki.org/xwiki/bin/view/Community/CodeStyle#HPackagenames-1]].
31
32 Now this will create a new maven module in a folder named ##component-artifact-id## in your folder, with a default xwiki component inside. {{info}}Note that if your parent (current, from where you are executing maven) folder is the folder of a maven module (contains a ##pom.xml## file), then the command above will fail unless the module is packaged as ##pom##. If the project is packaged as ##pom##, 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 ##pom##.{{/info}}
33
34 === The component explained ===
35
36 Assume, for the following explanations, that the package you used is ##org.xwiki.component##
37
38 Navigating in the component project folder, you will see standard maven project structure like this:
39
40 {{code}}
41 pom.xml
42 src/main/java/org/xwiki/component/HelloWorld.java
43 src/main/java/org/xwiki/component/internal/DefaultHelloWorld.java
44 src/main/resources/META-INF/components.txt
45 src/test/java/org/xwiki/component/HelloWorldTest.java
46 {{/code}}
47
48 which corresponds to the default files created: the ##HelloWorld## interface (service), its implementation ##DefaultHelloWorld##, a test class for this component ##HelloWorldTest##, the component declaration file ##components.txt## and the maven project ##pom## file.
49
50 If we have a look in the ##pom##, we see something like this:
51
52 {{code}}
53 <groupId>your-group-id</groupId>
54 <artifactId>your-artifact-id</artifactId>
55 <version>your-version</version>
56 {{/code}}
57
58 which are the group, artifact and version you used when you created your component
59
60 {{velocity filter="none"}}
61 {{html clean="false" wiki="true"}}
62 {{code}}
63 <properties>
64 <!-- TODO: remove this if you inherit a project that has the core version set -->
65 <platform.core.version>1.8-SNAPSHOT</platform.core.version>
66 </properties>
67 {{/code}}
68 It defines the core version for the ##xwiki-component-api## 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 ##${pom.version}## as the version for other XWiki dependencies.
69
70 {{code}}
71 <dependencies>
72 <dependency>
73 <groupId>org.xwiki.platform</groupId>
74 <artifactId>xwiki-core-component-api</artifactId>
75 <version>${platform.core.version}</version>
76 </dependency>
77 <dependency>
78 <groupId>junit</groupId>
79 <artifactId>junit</artifactId>
80 <version>3.8.1</version>
81 <scope>test</scope>
82 </dependency>
83 <!-- Add here all your other dependencies -->
84 </dependencies>
85 {{/code}}
86 The code above defines the dependency on the ##xwiki-component module-api## 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 library dependencies for maven to know and put them on your classpath when compiling, etc.
87 <p/>
88 To inherit all the properties of the platform projects (among others, source and target compatibility with <b>Java 1.5</b>), we inherit our project from the platform pom:
89
90 {{code}}
91 <parent>
92 <groupId>org.xwiki.platform</groupId>
93 <artifactId>xwiki</artifactId>
94 <version>28</version>
95 </parent>
96 {{/code}}
97
98 The interface file (##HelloWorld.java##) contains the definition of a regular Java interface, and looks like this:
99
100 {{code}}
101 @ComponentRole /* annotation used for declaring the service our component will provide */
102 public interface HelloWorld
103 {
104 String sayHello();
105 }
106 {{/code}}
107
108 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 ##sayHello()##.
109 <p/>
110 Then we have the implementation of the interface, the ##DefaltHelloWorld## class.
111
112 {{code}}
113 @Component
114 public class DefaultHelloWorld extends AbstractLogEnabled implements HelloWorld, Initializable
115 {{/code}}
116
117 Notice the ##@Component## 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 ##DefaltHelloWorld## class would look like this:
118
119 {{code}}
120 @Component("myCustomHelloWorld")
121 public class DefaultHelloWorld extends AbstractLogEnabled implements HelloWorld, Initializable
122 {{/code}}
123 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:
124
125 {{code}}
126 @Component(hints = {"info", "warning", "error" })
127 public class DefaultHelloWorld extends AbstractLogEnabled implements HelloWorld, Initializable
128 {{/code}}
129
130 This class extends ##AbstractLogEnabled## to be able to use the logging system, implements the component interface, and also the ##Initializable## interface which allows it to hook initialization code upon its instantiation by the component manager, in the ##initialize()## function:
131
132 {{code}}
133 public void initialize() throws InitializationException
134 {
135 // TODO: initialize component
136 // getLogger is inherited from AbstractLogEnabled
137 getLogger().debug("DefaultHelloWorld initialized");
138 }
139 {{/code}}
140
141 {{code}}
142 /**
143 * Says hello by returning a greeting to the caller.
144 *
145 * @return A greeting.
146 */
147 public String sayHello()
148 {
149 return "Hello world!";
150 }
151 {{/code}}
152
153 And now, the ##components.txt## file, in which component implementations present in this jar are specified for the ##ComponentManager## to register them
154
155 {{code}}org.xwiki.component.internal.DefaultHelloWorld{{/code}}
156
157 == How to find my component and use it? ==
158
159 === From other components ===
160
161 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.
162 <p/>
163 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.
164 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.
165 <p/>
166 Then, to effectively use the ##HelloWorld## 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 ##Socializer## component will need to be able to say hello to the world:
167
168 {{code}}
169 @Component
170 public class DefaultSocializer extends AbstractLogEnabled implements Socializer, Initializable
171 {
172 [...]
173
174 /** Will be injected by the component manager */
175 @Requirement
176 private HelloWorld helloWorld;
177
178 [...]
179 }
180 {{/code}}
181
182 Note the ##@Requirement## annotation, which instructs the component manager to inject the required component where needed.
183 <p/>
184 The content of ##components.txt## should be updated with:
185
186 {{code}}org.xwiki.component.internal.DefaultSocializer{{/code}}
187
188 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:
189
190 {{code}}
191 public class DefaultSocializer extends AbstractLogEnabled implements Socializer, Initializable
192 {
193 [...]
194
195 public void startConversation()
196 {
197 this.helloWorld.sayHello();
198
199 [...]
200 }
201
202 [...]
203 }
204 {{/code}}
205
206 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.
207 <p/>
208 TODO: refer to the other ways of implementing dependencies but requirements mechanism. Details, explanations, links.
209
210 === From non-components java code (e.g. older plugins) ===
211
212 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>>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.
213 <p/>
214 To use our greetings provider component, we simply invoke:
215
216 {{code}}
217 HelloWorld greeter = (HelloWorld) Utils.getComponent(HelloWorld.class);
218 //use the HelloWorld service
219 greeter.sayHello();
220 {{/code}}
221
222 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.
223 <p/>
224 {{info}}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.{{/info}}
225
226 === From wiki pages ===
227
228 In order to use a component in wiki pages, we need to expose it to the scripting environments: groovy and velocity.
229
230 ==== Accessing a component from groovy ====
231
232 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 ##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):
233
234 {{code}}
235 <%
236 def greeter = com.xpn.xwiki.web.Utils.getComponent(org.xwiki.component.HelloWorld.class);
237 println greeter.sayHello();
238 %>
239 {{/code}}
240
241 TODO: talk about the future plans (?) to make a component accessible in the groovy context through a groovy bridge.
242
243 ==== Accessing a component from velocity ====
244
245 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:
246 <p/>
247 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 ##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.
248
249 {{code}}
250 @Component("helloWorld")
251 public class HelloWorldVelocityContextInitializer implements VelocityContextInitializer
252 {
253 /** The key to add to the velocity context */
254 public static final String VELOCITY_CONTEXT_KEY = "greeter";
255
256 /** The component instance to add to the velocity context, injected by the component manager */
257 @Requirement
258 private HelloWorld helloWorld;
259
260 /**
261 * Add the component instance to the velocity context received as parameter.
262 */
263 public void initialize(VelocityContext context)
264 {
265 context.put(VELOCITY_CONTEXT_KEY, this.helloWorld);
266 }
267 }
268 {{/code}}
269
270 The result of this will be the availability of the ##HelloWorld## instance in velocity through the key //greeter// (as in ##$greeter.sayHello()##).
271 <p/>
272 This instance of ##HelloWorld## will be injected by the component manager in the ##helloWorld## member, due to the ##@Requirement## annotation.
273 <p/>
274 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):
275
276 {{code}}
277 [...]
278 org.component.internal.vcinitializer.HelloWorldVelocityContextInitializer
279 {{/code}}
280
281 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.
282 <p/>
283 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:
284
285 {{code}}
286 <dependency>
287 <groupId>org.xwiki.platform</groupId>
288 <artifactId>xwiki-core-velocity</artifactId>
289 <version>${platform.core.version}</version>
290 </dependency>
291 {{/code}}
292
293 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:
294
295 {{code}}$greeter.sayHello(){{/code}}
296
297 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]].
298
299 == How do I find other code? ==
300
301 === The XWiki data model ===
302
303 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##.
304 <p/>
305 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.
306 <p/>
307 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>>dev:Community.MailingLists]].
308 <p/>
309 For example:
310
311 {{code}}
312 @Component
313 public class DefaultHelloWorld implements HelloWorld
314 {
315 /** Provides access to documents. Injected by the Component Manager. */
316 @Requirement
317 private DocumentAccessBridge documentAccessBridge;
318
319 [...]
320
321 private String getConfiguredGreeting()
322 {
323 return documentAccessBridge.getProperty("XWiki.XWikiPreferences", "greeting_text");
324 }
325 {{/code}}
326
327 === The XWiki context ===
328
329 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.
330 <p/>
331 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.
332 <p/>
333 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:
334
335 {{code}}
336 /** Provides access to the request context. Injected by the Component Manager. */
337 @Requirement
338 private Execution execution;
339
340 [...]
341
342 private void workWithTheContext()
343 {
344 ExecutionContext context = execution.getContext();
345 // Do something with the execution context
346 }
347 {{/code}}
348
349 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.
350
351 {{code}}
352 private void workWithTheContext()
353 {
354 ExecutionContext context = execution.getContext();
355 Map<Object, Object> xwikiContext = (Map<Object, Object>) context.getProperty("xwikicontext");
356 // Do something with the XWiki context
357 }
358 {{/code}}
359
360 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]].
361
362 === Code outside components ===
363
364 You can use external libraries as in any other maven module, just declare the right dependencies in your module's ##pom.xml##.
365 <p/>
366 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.
367 <p/>
368 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.
369 <p/>
370 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.
371
372 == Deploying and using the component ==
373
374 In order to have your component work with XWiki, build the maven module, and find the produced <b>.jar</b> in the target folder. Copy this .jar to the <b>/WEB-INF/lib</b> 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.
375 {{/html}}
376 {{/velocity}}

Get Connected