Wiki source code of Creating Plugins

Version 5.4 by Vincent Massol on 2017/09/05

Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc/}}
3 {{/box}}
4
5 {{warning}}
6 Plugins are the old way of writing XWiki extensions. The new way is to [[write a Component>>platform:DevGuide.WritingComponents]].
7 {{/warning}}
8
9 Plugins are quite handy when you want to interact with third-party code from the Velocity context. Check the [[Extensions wiki>>extensions:Main.WebHome]] for a list of existing plugins.
10
11 Here are the steps to develop a "Hello World" plugin and more.
12
13 = The plugin architecture =
14
15 Basically, a plugin is composed of two parts:
16
17 * The **plugin** itself: it must implement the [[XWikiPluginInterface>>https://fisheye2.atlassian.com/browse/xwiki/xwiki-platform/core/trunk/xwiki-core/src/main/java/com/xpn/xwiki/plugin/XWikiPluginInterface.java]] interface. For simplicity you can also extend the [[XWikiDefaultPlugin>>https://fisheye2.atlassian.com/browse/xwiki/xwiki-platform/core/trunk/xwiki-core/src/main/java/com/xpn/xwiki/plugin/XWikiDefaultPlugin.java]] class which is an adapter to the XWikiPluginInterface. The plugin contains the core functions of your plugin. They will not be accessible from scripting (without programming rights).
18 * Its **API**: it should extend the [[Api>>https://fisheye2.atlassian.com/browse/xwiki/xwiki-platform/core/trunk/xwiki-core/src/main/java/com/xpn/xwiki/api/Api.java]] class. Will contain all the public methods, accessible from scripting.
19
20 Although you can write the functionality inside the API, this is not recommended; the plugin functionality is written in the //hidden// part ("hidden" as in "not publicly accessible"), and the API can filter the access to privileged users, beautify the method names or parameter list, etc., or simply forward the call to the hidden part.
21
22 == Plugin lifecycle ==
23
24 When the XWiki engine is initialized, the Plugin Manager calls the class constructor for all the enabled plugins (classes implementing the com.xpn.xwiki.plugin.XWikiPluginInterface). For each plugin the class constructor is called only once, and the plugin manager calls the init(XWikiContext) method of the plugin. Each time a plugin is referenced by a Velocity script, for example, when you call a method served by the plugin API:
25
26 {{code}}#set($helloWorldText = "$xwiki.helloworld.hello()"){{/code}}
27
28 or when you ask the XWiki instance for the plugin API object :
29
30 {{code}}
31 #set($pluginObject = $xwiki.getPlugin("helloworld")
32
33 #* the name given as argument of getPlugin() should be
34 the one returned by the getName() method of the Plugin class.
35 *#
36 {{/code}}
37
38 XWiki calls the getPluginApi() method for the plugin's instance, which itself creates an instance of the class com.xpn.xwiki.plugin.PluginApi. This is why you should not store things in fields of the class extending PluginApi in your plugin, since the usual behavior for the getPluginApi() method is to create a new instance of the PluginApi class every time Velocity needs to access the API for your plugin. This is not true if you store the returned plugin API in a variable, for example:
39
40 {{code}}
41 #set($myPluginApi = $xwiki.helloworld)
42 {{/code}}
43
44 The myPluginApi variable will point to the same object as long as the variable exists. You can declare fields in your plugin class instead, since there is only one instance of this class, whose lifecycle spans over the entire servlet's lifecycle.
45
46 = Write the plugin =
47
48 First of all let's **declare our plugin class**:
49
50 {{code language="java"}}
51 public class HelloWorldPlugin extends XWikiDefaultPlugin {...}
52 {{/code}}
53
54 Then let's **implement the needed constructor**:
55
56 {{code language="java"}}
57 public HelloWorldPlugin(String name, String className, XWikiContext context) {
58 super(name,className,context);
59 }
60 {{/code}}
61
62 **Set a method to get the name of the plugin**. That's how we will call it from Velocity. For example, we will be able to use our plugin with ##$xwiki.helloworld.myMethod()##;
63
64 {{code language="java"}}
65 public String getName() {
66 return "helloworld";
67 }
68 {{/code}}
69
70 **Write a method to get the plugin API**. Don't forget to cast the plugin.
71
72 {{code language="java"}}
73 public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) {
74 return new HelloWorldPluginApi((HelloWorldPlugin) plugin, context);
75 }
76 {{/code}}
77
78 **Overload the cache flush method** (optional):
79
80 {{code language="java"}}
81 public void flushCache() {}
82 {{/code}}
83
84 Optionally, we can **create a [[log4j>>http://logging.apache.org/log4j/1.2/apidocs/index.html]] instance** for the plugin:
85
86 {{code language="java"}}
87 private static final Log LOG = LogFactory.getLog(HelloWorldPlugin.class);
88 {{/code}}
89
90 This is very useful for debugging. The logger could be invoked from any method like:
91
92 {{code language="java"}}
93 public String getName() {
94 LOG.debug("Entered method getName");
95 return "helloworld";
96 }
97 {{/code}}
98
99 Then, to enable logging at a specific level for your plugin, edit //webapps/xwiki/WEB-INF/classes/log4j.properties// and add, for example:
100
101 {{code}}
102 log4j.com.xpn.xwiki.plugin.helloworld.HelloWorldPlugin=debug
103 {{/code}}
104
105 You'll then be able to follow your plugin's log messages by tailing your ##xwiki.log## file. Note that you'll need to restart the app server for changes to ##log4j.properties## to take effect.
106
107 And finally, **write a method to init the context**:
108
109 {{code language="java"}}
110 public void init(XWikiContext context) {
111 super.init(context);
112 }
113 {{/code}}
114
115 Here is the code you should have now:
116
117 {{code language="java"}}
118 package com.xpn.xwiki.plugin.helloworld;
119
120 import org.apache.commons.logging.Log;
121 import org.apache.commons.logging.LogFactory;
122
123 import com.xpn.xwiki.XWikiContext;
124 import com.xpn.xwiki.api.Api;
125 import com.xpn.xwiki.plugin.XWikiDefaultPlugin;
126 import com.xpn.xwiki.plugin.XWikiPluginInterface;
127
128 public class HelloWorldPlugin extends XWikiDefaultPlugin {
129
130 private static Log LOG = LogFactory.getLog(HelloWorldPlugin.class);
131
132 public HelloWorldPlugin(String name, String className, XWikiContext context) {
133 super(name,className,context);
134 init(context);
135 }
136
137 public String getName() {
138 return "helloworld";
139 }
140
141 public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) {
142 return new HelloWorldPluginApi((HelloWorldPlugin) plugin, context);
143 }
144
145 public void flushCache() {
146 }
147
148 public void init(XWikiContext context) {
149 super.init(context);
150 }
151 }
152 {{/code}}
153
154 = Write the API =
155
156 Let's write the API class which will contain the methods that can be called from Velocity.
157
158 Firstly, **class declaration**:
159
160 {{code language="java"}}
161 public class HelloWorldPluginApi extends Api {...}
162 {{/code}}
163
164 Then, **plugin field declaration**. It will let our API to call backend methods.
165
166 {{code language="java"}}
167 private HelloWorldPlugin plugin;
168 {{/code}}
169
170 **Required constructor**
171
172 {{code language="java"}}
173 public HelloWorldPluginApi(HelloWorldPlugin plugin, XWikiContext context) {
174 super(context);
175 setPlugin(plugin);
176 }
177 {{/code}}
178
179 Classic **plugin getter and setter**. These methods are not required at all, on the contrary, they should not be defined, unless they are really needed.
180
181 {{code language="java"}}
182 public HelloWorldPlugin getPlugin(){
183 return (hasProgrammingRights() ? plugin : null);
184 // Uncomment for allowing unrestricted access to the plugin
185 // return plugin;
186 }
187
188 public void setPlugin(HelloWorldPlugin plugin) {
189 this.plugin = plugin;
190 }
191 {{/code}}
192
193 Here is the key **API method**. Here is the one that you will call from velocity. You can define any number of them and call your plugin backend from them.
194
195 {{code language="java"}}
196 public String hello() {
197 return "Hello World!";
198 }
199 {{/code}}
200
201 You can also have void methods:
202
203 {{code language="java"}}
204 public void updatePage() {
205 //...
206 }
207 {{/code}}
208
209 Here is the complete API code:
210
211 {{code language="java"}}
212 package com.xpn.xwiki.plugin.helloworld;
213
214 import com.xpn.xwiki.XWikiContext;
215 import com.xpn.xwiki.api.Api;
216
217 public class HelloWorldPluginApi extends Api {
218 private HelloWorldPlugin plugin;
219
220 public HelloWorldPluginApi(HelloWorldPlugin plugin, XWikiContext context) {
221 super(context);
222 setPlugin(plugin);
223 }
224
225 public HelloWorldPlugin getPlugin(){
226 return (hasProgrammingRights() ? plugin : null);
227 // Uncomment for allowing unrestricted access to the plugin
228 // return plugin;
229 }
230
231 public void setPlugin(HelloWorldPlugin plugin) {
232 this.plugin = plugin;
233 }
234
235 public String hello() {
236 return "Hello World!";
237 }
238
239 public void updatePage() {
240 //...
241 }
242 }
243 {{/code}}
244
245 = Integrate the plugin in your XWiki installation =
246
247 First of all you need to **copy your classes to the XWiki servlet installation**. Don't forget to be consistent with your package tree. With a Linux Tomcat installation, you'll need to follow these steps which you should be able to reproduce easily in your favourite operating system:
248
249 {{code}}
250 go to the tomcat installation folder (or whatever container you are using)
251 $ cd myTomcatInstallation
252 go to the xwiki WEB-INF directory
253 $ cd webapps/xwiki/WEB-INF
254 create the classes tree, compliant to the "package" directive that you set in the plugin source files
255 $ mkdir classes/com/xpn/xwiki/plugin/helloworld
256 And then copy the class files to this location
257 $ cp myPluginsFolder/HelloWorldPlugin.class classes/com/xpn/xwiki/plugin/helloworld
258 $ cp myPluginsFolder/HelloWorldPluginAPI.class classes/com/xpn/xwiki/plugin/helloworld
259 {{/code}}
260
261 Alternatively, you can jar up your classes (with the required directory structure) and place the jar in //webapps/xwiki/WEB-INF/lib//. This is a more agreeable way of distributing your plugin.
262
263 Finally you need to **register your plugin** in the ##xwiki.cfg## file located in //WEB-INF//:
264
265 {{code}}
266 xwiki.plugins=com.xpn.xwiki.plugin.calendar.CalendarPlugin,\
267 ...,\
268 com.xpn.xwiki.plugin.helloworld.HelloWorldPlugin
269 {{/code}}
270
271 Don't forget to restart your servlet container after this. XWiki has to re-read the configuration file.
272
273 = Use the plugin =
274
275 Here is the simplest part. Edit a page and write: {{code}}My plugin says: "$xwiki.helloworld.hello()"{{/code}}.
276 It should be rendered like this: {{code}}My plugin says: "Hello World!"{{/code}}.
277 You can also call void methods specified in the API class :
278
279 {{code}}
280 $xwiki.helloworld.updatePage()
281 The page has been updated.
282 {{/code}}
283
284 = Examples =
285
286 Here are some examples of what you can do with plugins. You should actually check the [[API Guide>>platform:DevGuide.APIGuide]], since it contains examples on how to use the XWiki API. The examples in the API Guide are written in Velocity, and are thus easily applicable to Java.
287
288 == Accessing pages, objects and object properties from pages ==
289
290 This is something you can do from Velocity as well, but when you need to perform complex treatments on your XWiki pages, you need to do it from a java plugin.
291
292 The class representing a document in the XWiki Java model is ##com.xpn.xwiki.doc.XWikiDocument##. The class representing an object in the XWiki Java model is ##com.xpn.xwiki.objects.BaseObject##.
293
294 If you need to access existing documents from your plugin, you use the XWiki class, ##com.xpn.xwiki.XWiki##, which has a getDocument() method. You can retrieve the current Xwiki instance by using the ##com.xpn.xwiki.XWikiContext## class, which has a getWiki() method.
295
296 The rule, in plugin programming, is to pass the current context as a ##com.xpn.xwiki.XWikiContext## function parameter, between the different methods of your plugin class. The plugin API class also has a context property pointing to the current context.
297
298 {{code}}
299 // You need the current context, which you always have in a plugin anyway
300 com.xpn.xwiki.doc.XWikiDocument doc = context.getDoc(); // current document;
301 com.xpn.xwiki.doc.XWikiDocument doc = context.getWiki().getDocument("theSpace.theDoc", context); // any document
302 com.xpn.xwiki.objects.BaseObject meta;
303 meta = doc.getObject("fooSpace.fooClass");
304 String docType = (String)meta.getStringValue("type"); //if the class of the object has a property named "type", which can accept a text value...
305 meta.set("type", "newValue", context);
306 {{/code}}
307
308 If you need to access the parent of an XWiki document, you should use the getDocument() method of the XWiki class, as seen in the example above, with, as parameter value, the parent's full name returned by the getParent() method of the XWikiDocument class.
309
310 {{code}}
311 com.xpn.xwiki.doc.XWikiDocument parentDocument = context.getWiki().getDocument(childDocument.getParent());
312 {{/code}}
313
314 You should not use ##XWikiDocument.getParentDoc## since it only returns a blank XWikiDocument object set with the same full name as the parent's full name.

Get Connected