A plugin is a Set of Extensions
A Sonar plugin is a set of Java objects that implement extension points. These extension points are interfaces or abstract classes which model an aspect of the system and define contracts of what needs to be implemented. They can be for example pages in the web application or sensors generating measures.
The extensions implemented in the plugin must be declared in a Java class extending org.sonar.api.Plugin. This class must then be declared in the pom with the property <pluginClass> :
The sonar-plugin packaging accepts advanced parameters.
Here is list of extension points available in the sonar plugin API. Please note that partial implementation of those extensions are available in the api as well. See all known sub-interfaces and implementing classes of org.sonar.api.Extension to get an exhaustive list.
CPD definition to detect duplicated lines on a new language
Used to decorate resources, i.e. calculate measures from other measures. Example : the number of lines of code of a package is the sum of the lines of its classes.
Define a new language.
Define a Maven2 plugin to execute before analyzing the project.
List new Metrics. A metric is an instance of org.sonar.api.measure.Metric. It can be quantitative (lines of code, number of rule violations) or qualitative (code coverage, complexity by class, rules compliance). As a rule, a metric is used to store a number but it can also be used to store a text field with list of key/value pairs, an XML or even binary data.
Post-jobs are tasks executed at the end of project analysis. Examples : purge database, generate report, send emails, ...
Job to delete data from database.
enables to ignore certain resources. The only implementations is the exclusion pattern management. (ExcludedResourceFilter in the core plugin).
Analyze project. It creates resources (classes, packages, ...) and measures. It can make requests on other systems. See below.
Enables to ignore violations. Has a very simple interface : public boolean isIgnored(Violation violation). A NoSonarFilter draft has been added to the Squid plugin.
Batch task executed before all other tasks (sensors, decorators, post-jobs)
Filter to exclude some files from analysis
Handle batch lifecycle events (sensor is started, stopped, ...)
Change project structure before analysis
Image generated by JFreeChart.
Extend the library sonar-colorizer to support new languages. By default only Java sources are colorized in Sonar.
Static HTML footer displayed in all pages.
Define a new language.
Add a page, linked from the left sidebar. The page is implemented as a GWT component. GWT RPC/servlets are not supported.
New view when displaying source code. It is used to add a new tab to the source viewer along with "Violations", "Sources", "Coverage", ... The new tab is implemented as a GWT component.
Add a page, linked from the left sidebar. The page is implemented as a JRuby on Rails view.
Experimental. Used to define new web services, written in JRuby on Rails.
New widget in project dashboards. It is implements as a JRuby on Rails template.
Define a new repository of rules, i.e. a list of coding rules to publish into the global referential
Programmatically define a Quality profile
Import a Quality profile, generally used when end-users create a profile by uploading a file
Export a Quality profile in a specific format, for example Checkstyle configuration format
Define a new Quality model, like SQALE
Delegates authentication of users to external system
Handle server startup notification
Handle server shutdown notification
Channel to publish notifications. An example is the Email channel.
Provides logic to determine which users are interested in receiving notification. Example : notify me when when someone changes review assigned to me or created by me.
Sensor or Decorator ?
There are two extensions that enables to save measures : Sensor and Decorator. A common problem when writing a plugin is to decide which one to use.
A Sensor is invoked once during the analysis of a project. The sensor can invoke a maven plugin, parse a flat file, connect to a web server... For example the Cobertura Sensor invokes the Codehaus Cobertura MOJO. Then the generated XML file is parsed and used to save the first-level of measures on resources (project, package or class).
A sensor has can access and save measures on the whole tree of resources. Sensor are generally used to add measure at the lowest level of the resource tree.
Decorators are triggered once all sensors have completed. Their decorate method is called on every resource of a certain level bottom up. Decorators can load (SELECT) and save (INSERT) measures. The call is contextual, i.e it is only possible to access the resource and its children.
Decorators are generally used either to consolidate at higher levels measures that have been added by Sensors at the lowest level.
How to reuse existing components ?
Extensions are registered in an IoC container, with constructor injection.To communicate with other extensions or with existing components provided by the API, just declare them in the constructor of your extension. For example to get references on DatabaseSession or RulesProfile :
References will be automatically set at runtime.
How to quickly start the plugin ?
As described in the Getting Started page, you can build sources, copy the JAR file to the directory extensions/plugins/ and restart the server. But this approach can quickly become tedious. The following solutions help to edit code without leaving your development environment :
Changes on Java code
The sonar-dev-maven-plugin allows to start a Sonar server and to deploy the plugin.
Once the server is launched, hit http://localhost:9000. By default, the in-process database (H2, or Derby prior to Sonar 3.2) is used but you can specify to use a local MySQL instance with the property "-Dsonar.database=mysql". In that case, the sonar schema must exist in the MySQL DB along with the user sonar/sonar (login/password) who must have all rights on the sonar schema.
Then you can feed the database by inspecting projects :
Debug Java batch
mvnDebug sonar:sonar and attach your IDE to the remote process. Example in Intellij Idea : Run -> Edit configurations -> Add new configuration -> Remote.
Changes on Ruby code
The technique is not the same for Ruby code. The good point is that changes are reloaded on the fly, without rebuilding the plugin. The steps are :
- Install Sonar
- Edit the file war/sonar-server/WEB-INF/web.xml and set the parameters
Use absolute path when declaring Ruby files in Java extensions. Be careful to not commit these changes to SCM. Example :
- Start server
- Edit Ruby code
How to use external libraries ?
A plugin benefits from all the dependencies provided by the API. Execute the following command on your plugin to list them :
Since version 2.2, the plugin classloader is isolated from other plugins, so it can embedd its own dependencies. Just define the dependencies you need with the scope 'compile'.
Constraints are :
- Libraries used for GWT compilation must be defined with scope provided
- The plugin classloader is a child of the Sonar classloader, with a parent-first delegation model. There are two consequences :
- Sonar libraries are automatically inherited. Their versions can not be changed.
- There are side-effects on some libraries, for example the classloader must be explicitely set for XStream :
How to log ?
SLF4J is used as a simple facade of various logging frameworks (log4j, commons-log, logback, java.util.logging). It's simple to use :
Read the SLF4J manual for more details.
How to get configuration ?
org.sonar.api.config.Settings provides properties for batch extensions (global/project settings, command-line parameters, system properties) and server extensions (global settings, system properties, file $SONAR_HOME/conf/sonar.properties). It replaces Apache Commons Configuration that is deprecated since release 2.12.
To benefit from advanced features (default value, availability in the settings page), properties should be declared on the Plugin entry point or on extensions :
Persistent properties are also accessible from the Web Service named 'properties'. To exclude some properties from anonymous requests, add the suffix ".secured" to the key (
my.property.secured). It can be useful for license keys for example.
Sonar web server provides two other services :
- the Web Service API publishes data in various formats (XML, JSON). It can be used to feed external systems or GWT extensions
- Sonar integrates JFreechart Eastwood, a partial implementation of the Google Chart API . To know if a chart is implemented, simply replace http://chart.apis.google.com/chart?... by http://localhost:9000/gchart?...