Wiki source code of Writing XWiki components

Version 42.3 by Sorin Burjan on 2011/08/25

Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}{{toc/}}{{/box}}
2
3 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>>DevGuide.RenderingMacroTutorial]].
4
5 {{info}}Components replace the older Plugin architecture which has been deprecated a while ago.{{/info}}
6
7 You should start by reading the [[Reference document on XWiki Components>>extensions:Extension.Component Module]].
8
9 = Let's get started! =
10
11 Enough talking, let's see some code!
12
13 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.
14
15 == Creating a XWiki component using Maven ==
16
17 As you've read in the [[XWiki Component Reference>>extensions:Extension.Component Module]] 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.
18
19 After you've [[installed Maven and added XWiki repositories in your profile>>dev:Community.Building#HInstallingMaven]], open a shell prompt and type:
20
21 {{info}}
22 Ideally we would use the [[GitHub URL>>https://raw.github.com/xwiki/xwiki-platform/master/xwiki-platform-tools/xwiki-platform-tool-archetypes/xwiki-platform-tool-archetype-component/archetype-catalog.xml]] for locating our Maven Archetype Catalog. However there's a [[Maven Bug>>http://jira.codehaus.org/browse/ARCHETYPE-220]] that prevents us from using a HTTPS URL (which is what GitHub gives us). In the meantime we've created a page on xwiki.org that gets the content from GitHub and republishes it under an HTTP URL
23 {{/info}}
24
25 {{code language="none"}}
26 mvn archetype:generate -DarchetypeCatalog="http://dev.xwiki.org/xwiki/bin/view/Main/MavenComponentArchetype?outputSyntax=plain&xpage=plain"
27 {{/code}}
28
29 Then follow the instructions. For example:
30
31 {{code language="none"}}
32 vmassol@target $ mvn archetype:generate -DarchetypeCatalog="http://dev.xwiki.org/xwiki/bin/view/Main/MavenComponentArchetype?outputSyntax=plain&xpage=plain"
33 [INFO] Scanning for projects...
34 [INFO]
35 [INFO] ------------------------------------------------------------------------
36 [INFO] Building Maven Stub Project (No POM) 1
37 [INFO] ------------------------------------------------------------------------
38 [INFO]
39 [INFO] >>> maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom >>>
40 [INFO]
41 [INFO] <<< maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom <<<
42 [INFO]
43 [INFO] --- maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom ---
44 [INFO] Generating project in Interactive mode
45 [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
46 Choose archetype:
47 1: http://dev.xwiki.org/xwiki/bin/view/Main/MavenComponentArchetype?outputSyntax=plain&xpage=plain -> xwiki-archetype-component (Make it easy to create a maven project for creating a XWiki Component.)
48 Choose a number: : 1
49 Downloading: http://maven.xwiki.org/snapshots/org/xwiki/platform/tools/xwiki-archetype-component/1.0-SNAPSHOT/maven-metadata.xml
50 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)
51 Downloading: http://maven.xwiki.org/snapshots/org/xwiki/platform/tools/xwiki-archetype-component/1.0-SNAPSHOT/maven-metadata.xml
52 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)
53 Define value for property 'groupId': : com.acme
54 Define value for property 'artifactId': : example
55 Define value for property 'version': 1.0-SNAPSHOT: :
56 Define value for property 'package': com.acme: :
57 Confirm properties configuration:
58 groupId: com.acme
59 artifactId: example
60 version: 1.0-SNAPSHOT
61 package: com.acme
62 Y: : Y
63 [INFO] ----------------------------------------------------------------------------
64 [INFO] Using following parameters for creating project from Old (1.x) Archetype: xwiki-archetype-component:1.0-SNAPSHOT
65 [INFO] ----------------------------------------------------------------------------
66 [INFO] Parameter: groupId, Value: com.acme
67 [INFO] Parameter: packageName, Value: com.acme
68 [INFO] Parameter: package, Value: com.acme
69 [INFO] Parameter: artifactId, Value: example
70 [INFO] Parameter: basedir, Value: /Users/vmassol/dev/xwiki/trunks-clean4/platform/tools/xwiki-archetypes/target
71 [INFO] Parameter: version, Value: 1.0-SNAPSHOT
72 [INFO] ********************* End of debug info from resources from generated POM ***********************
73 [INFO] project created from Old (1.x) Archetype in dir: /Users/vmassol/dev/xwiki/trunks-clean4/platform/tools/xwiki-archetypes/target/example
74 [INFO] ------------------------------------------------------------------------
75 [INFO] BUILD SUCCESS
76 [INFO] ------------------------------------------------------------------------
77 [INFO] Total time: 12.868s
78 [INFO] Finished at: Sun Nov 14 18:27:52 CET 2010
79 [INFO] Final Memory: 9M/81M
80 [INFO] ------------------------------------------------------------------------
81 vmassol@target $
82 {{/code}}
83
84 Then go in the created directory (##example## in our example above) and run ##mvn install## to build your component.
85
86 == The Component explained ==
87
88 Assume, for the following explanations, that the package you used is ##com.acme##
89
90 Navigating in the component project folder, you will see the following standard Maven project structure:
91
92 {{code language="none"}}
93 pom.xml
94 src/main/java/com/acme/HelloWorld.java
95 src/main/java/com/acme/internal/DefaultHelloWorld.java
96 src/main/java/com/acme/internal/HelloWorldScriptService.java
97 src/main/resources/META-INF/components.txt
98 src/test/java/com/acme/HelloWorldTest.java
99 {{/code}}
100
101 which correspond 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. The ##HelloWorldScriptService## file is described below when we explain how to make the component's API available to wiki pages.
102
103 If you have a look in the ##pom.xml##, you'll notice the following dependencies:
104
105 {{code language="xml"}}
106 <dependencies>
107 <dependency>
108 <groupId>org.xwiki.platform</groupId>
109 <artifactId>xwiki-core-component-default</artifactId>
110 <version>${platform.core.version}</version>
111 </dependency>
112 <!-- Testing dependencies -->
113 <dependency>
114 <groupId>org.xwiki.platform</groupId>
115 <artifactId>xwiki-core-shared-tests</artifactId>
116 <version>${platform.core.version}</version>
117 <scope>test</scope>
118 </dependency>
119 </dependencies>
120 {{/code}}
121
122 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.
123
124 The interface file (##HelloWorld.java##) contains the definition of a regular Java interface, and looks like this:
125
126 {{code language="java"}}
127 @ComponentRole /* annotation used for declaring the service our component provides */
128 public interface HelloWorld
129 {
130 String sayHello();
131 }
132 {{/code}}
133
134 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()##.
135
136 Then we have the implementation of the interface, the ##DefaultHelloWorld## class.
137
138 {{code language="java"}}
139 @Component /* annotation used for declaring a component implementation */
140 public class DefaultHelloWorld implements HelloWorld
141 {{/code}}
142
143 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:
144
145 {{code language="java"}}
146 @Component("database")
147 public class DatabaseHelloWorld implements HelloWorld
148 {{/code}}
149
150 Then the ##sayHello## in ##DefaultHelloWorld## is basic in this example:
151
152 {{code language="java"}}
153 /**
154 * Says hello by returning a greeting to the caller.
155 *
156 * @return A greeting.
157 */
158 public String sayHello()
159 {
160 return "Hello world!";
161 }
162 {{/code}}
163
164 And now, the ##components.txt## file, in which component implementations present in this jar are specified for the ##ComponentManager## to register them.
165
166 {{code language="none"}}com.acme.internal.DefaultHelloWorld{{/code}}
167
168 = How to find my component and use it? =
169
170 == From other components ==
171
172 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.
173
174 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:
175
176 {{code}}
177 @Component
178 public class DefaultSocializer implements Socializer
179 {
180 [...]
181
182 /** Will be injected by the component manager */
183 @Requirement
184 private HelloWorld helloWorld;
185
186 [...]
187 }
188 {{/code}}
189
190 Note the ##@Requirement## annotation, which instructs the component manager to inject the required component where needed.
191
192 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:
193
194 {{code}}
195 public class DefaultSocializer implements Socializer
196 {
197 [...]
198
199 public void startConversation()
200 {
201 this.helloWorld.sayHello();
202
203 [...]
204 }
205
206 [...]
207 }
208 {{/code}}
209
210 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.
211
212 == From non-components java code (e.g. older plugins) ==
213
214 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. The ##getComponent## function also has a signature without the ##hint## parameter, that uses the default hint.
215
216 To use our greetings provider component, we would simply invoke:
217
218 {{code}}
219 HelloWorld greeter = Utils.getComponent(HelloWorld.class);
220 greeter.sayHello();
221 {{/code}}
222
223 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.
224
225 {{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 as described in the [[Component Module Reference>>extensions:Extension.Component Module]].{{/info}}
226
227 == From wiki pages ==
228
229 Components can be made accessible to wiki pages by writing a ##ScriptService## implementation. They can then be access using any provided scripting language (velocity, groovy, python, ruby, php, etc).
230
231 Let's make our ##sayHello## method accessible:
232
233 {{code language="java"}}
234 @Component("hello")
235 public class HelloWorldScriptService implements ScriptService
236 {
237 @Requirement
238 private HelloWorld helloWorld;
239
240 public String greet()
241 {
242 return this.helloWorld.sayHello();
243 }
244 }
245 {{/code}}
246
247 Notice the component hint used (the ##hello## part in the ##@Component##). This is the name under which the script service will be accessible from scripting languages.
248
249 For example to access it in velocity you'd write:
250 {{code language="none"}}
251 $services.hello.greet()
252 {{/code}}
253
254 From Groovy:
255 {{code language="none"}}
256 services.hello.greet()
257 {{/code}}
258
259 Now for our script service to work we need to register it as a component and thus add it to the ##META-INF/components.txt## file:
260 {{code language="none"}}
261 ...
262 com.acme.internal.HelloWorldScriptService
263 {{/code}}
264
265 We also need to make the Script Service infrastructure available in our classpath. This is done by adding the following in your ##pom.xml## file:
266 {{code language="xml"}}
267 <dependency>
268 <groupId>org.xwiki.platform</groupId>
269 <artifactId>xwiki-core-script</artifactId>
270 <version>${platform.core.version}</version>
271 </dependency>
272 {{/code}}
273
274 = Accessing Legacy code =
275
276 By legacy we mean old XWiki code that hasn't been moved to components yet.
277
278 == The XWiki data model ==
279
280 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##.
281
282 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.
283
284 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]].
285
286 For example:
287
288 {{code}}
289 @Component
290 public class DefaultHelloWorld implements HelloWorld
291 {
292 /** Provides access to documents. Injected by the Component Manager. */
293 @Requirement
294 private DocumentAccessBridge documentAccessBridge;
295
296 [...]
297
298 private String getConfiguredGreeting()
299 {
300 return documentAccessBridge.getProperty("XWiki.XWikiPreferences", "greeting_text");
301 }
302 {{/code}}
303
304 == The XWiki context ==
305
306 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.
307
308 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.
309
310 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:
311
312 {{code}}
313 /** Provides access to the request context. Injected by the Component Manager. */
314 @Requirement
315 private Execution execution;
316
317 [...]
318
319 private void workWithTheContext()
320 {
321 ExecutionContext context = execution.getContext();
322 // Do something with the execution context
323 }
324 {{/code}}
325
326 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.
327
328 {{code}}
329 private void workWithTheContext()
330 {
331 ExecutionContext context = execution.getContext();
332 Map<Object, Object> xwikiContext = (Map<Object, Object>) context.getProperty("xwikicontext");
333 // Do something with the XWiki context
334 }
335 {{/code}}
336
337 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]].
338
339 == Code outside components ==
340
341 You can use external libraries as in any other maven module, just declare the right dependencies in your module's ##pom.xml##.
342
343 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.
344
345 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.
346
347 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.
348
349 = Deploying the Component =
350
351 Now that we have a functioning Component let's build it and deploy it to a XWiki Enterprise instance:
352 * To build the component, issue ##mvn install##. This generates a JAR in the ##target## directory of your project.
353 * To install it into a XWiki Enterprise instance, just copy that JAR file in ##XE_WAR_HOME/WEB-INF/lib## where ##XE_WAR_HOME## is where the XWiki Enterprise WAR is deployed.
354
355 Your component is now ready for service.
356
357 Enjoy!

Get Connected