openhab-docs/developers/guidelines.md

354 lines
15 KiB
Markdown
Raw Normal View History

---
layout: developersguide
title: Coding Guidelines
---
{% include base.html %}
# Coding Guidelines
Rewrite developer section (#942) * Rewrite developer section * More work on module types * More module-type stuff * Adapt vuepress files * Write binding doc * Add TODOs for missing topics * Add all missing topics from ESH. * Tests * Audio extensions * Utilities * i18n * Event-bus * Small fixes * Command Description * Add some tocs * Add concept drawing to binding dev. * Update developers/osgi/configadmin.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update administration/logging.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update developers/bindings/thing-xml.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Convert HTML tables to Markdown Signed-off-by: Hakan Tandogan <hakan@tandogan.com> * Resolved one line per sentence review parts. Signed-off-by: Jerome Luckenbach <github@luckenba.ch> * Update developers/index.md * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Add persistence placeholder. Address review comments * fix persistence subdirectory Signed-off-by: David Graeff <david.graeff@web.de> * Update developers/audio/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/contributing.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/osgi/osgids.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/transformations/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/ioservices/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Remove extensionservices (for now ;) Signed-off-by: David Graeff <david.graeff@web.de> * Fix typos Signed-off-by: David Graeff <david.graeff@web.de> * Added example code for 'DynamicCommandDescriptionProvider' and 'DynamicCommandDescriptionProvider' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Added example code for 'ThingHandlerFactory' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Applied review comments Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de>
2019-05-02 18:52:37 +00:00
{:.no_toc}
The following guidelines apply to all (Java) code of the openHAB project.
They must be followed to ensure a consistent code base for easy readability and maintainability.
Exceptions can certainly be made, but they should be discussed and approved by a project maintainer upfront.
Note that this list also serves as a checklist for code reviews on pull requests.
To speed up the contribution process, we therefore advice to go through this checklist yourself before creating a pull request.
Rewrite developer section (#942) * Rewrite developer section * More work on module types * More module-type stuff * Adapt vuepress files * Write binding doc * Add TODOs for missing topics * Add all missing topics from ESH. * Tests * Audio extensions * Utilities * i18n * Event-bus * Small fixes * Command Description * Add some tocs * Add concept drawing to binding dev. * Update developers/osgi/configadmin.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update administration/logging.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update developers/bindings/thing-xml.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Convert HTML tables to Markdown Signed-off-by: Hakan Tandogan <hakan@tandogan.com> * Resolved one line per sentence review parts. Signed-off-by: Jerome Luckenbach <github@luckenba.ch> * Update developers/index.md * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Add persistence placeholder. Address review comments * fix persistence subdirectory Signed-off-by: David Graeff <david.graeff@web.de> * Update developers/audio/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/contributing.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/osgi/osgids.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/transformations/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/ioservices/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Remove extensionservices (for now ;) Signed-off-by: David Graeff <david.graeff@web.de> * Fix typos Signed-off-by: David Graeff <david.graeff@web.de> * Added example code for 'DynamicCommandDescriptionProvider' and 'DynamicCommandDescriptionProvider' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Added example code for 'ThingHandlerFactory' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Applied review comments Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de>
2019-05-02 18:52:37 +00:00
If you are just keen on binding development, you may skip this document first and come back later.
{::options toc_levels="2,3"/}
* TOC
{:toc}
## A. Directory and File Layout
The structure of a binding follows the structure of a typical OSGi bundle project.
```
Merge 2.5.x into main (#1266) * Update README (2.5.x) (#1153) Change branch name. Signed-off-by: Yannick Schaus <github@schaus.net> * Update items.md (#1156) * Added var and VA units to UoM (#1146) VA (Volt-Ampere - apparent power) and var (Volt-Ampere reactive) are used to measure power and energy consumption in AC circuits. Signed-off-by: Nagy Attila Gabor <mrbig@sneaker.hu> * Fix filepath to keystore (#1148) Default openHAB userdata environment variable should be `$OPENHAB_USERDATA`, not `$USER_DATA` shouldn't it? At least, this is the default on my fresh openHABian and also the most popular variant to find in the docs. * Slight language corrections (#1150) I think it reads better this way Signed-off-by: Richard Davies <rwdrich@gmail.com> * additional example for non default persistence service (#1152) For me it was confusing how to pass on the serviceId into methods that already had an argument. An extra example is always good. Signed-off-by: jaco <jaco.waes@gmail.com> * Adding 12 new logos for OH Add-Ons page on website (#1158) Signed-off-by: bracklanna bracklanna@users.noreply.github.com * Added missing preset variables (#1104) * Added missing preset variables Signed-off-by: Scott Rushworth <openhab@5iver.com> * Cleaned up blank lines, fixed table, and added file name for SimpleRule Signed-off-by: Scott Rushworth <openhab@5iver.com> * Fix broken link (#1165) * Added Hotlink from "label" section to "state presentation" (#1167) * Added note about broken action (#1164) * Added note about broken action See https://github.com/openhab/openhab-core/issues/1374 Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Incorporated changes from review Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Incorporated changes from review Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Update index.md (#1170) Link appears to be wrong and does not work when I click on it in Edge. Loads the same page again instead of loading the correct new page from the hyperlink. https://www.openhab.org/docs/developer/guidelines.html * Added Airthings logo (#1171) * typo in exambp (#1172) `Temperature.averageSince(now.minusMinutes(5),"influxdb")` * file.encoding=UTF-8 (#1173) * Update demo URL and add demo.rules URL (#1174) Based on: https://community.openhab.org/t/demo-setup-missing/94850 Old Link is broken leading to 404. The link to the demo.rules on github is an extra :) * Replace outdated zulu.org link. (#1177) * Replace outdated zulu.org link. As of 3/23/2020 zulu.org has an SSL cert that expired on 9/28/2019. Changed link to azul.com/downloads, since that appears to be the new official source. Signed-off-by: Billy Stevens <contact@wasv.me> * Changed all http links to https for installation/index.md. All changed links working, tested on 3/24/2020. Signed-off-by: Billy Stevens <contact@wasv.me> * Minor language tweak (#1178) * Ending an active scan/stopScan (#1179) Signed-off-by: Mark Theiding <mark.theiding@gmail.com> * Add files via upload (#1184) * Update persistence.md (#1185) Clarify return objects for max/min rules extensions. Signed-off-by: Ross Kennedy rossko@culzean.clara.co.uk * Update things.md (#1186) Amended example code to include using label and location when defining a Thing with a bridge that is defined elsewhere. * Correct typos (#1190) * Correct usage of its/it's "It's" is always a contraction of "it is" or "it has". "Its" is a possessive. Correct a few places where they were used backwards. Signed-off-by: Bjorn Helgaas <bjorn@helgaas.com> * Correct "Z-Wave" spelling Per https://www.z-wave.com/, the canonical spelling appears to be "Z-Wave". Most places use "Z-Wave" already; change the remaining references to match. Signed-off-by: Bjorn Helgaas <bjorn@helgaas.com> * Correct typos and grammatical errors Correct some typos and grammatical errors. Signed-off-by: Bjorn Helgaas <bjorn@helgaas.com> * Update sitemap.md section charts (#1191) I observed that the unique first word in the labels of items charted in a group isn't causing an empty chart anymore. I'm on openHAB 2.5.1. Signed-off-by: Juergen Baginski opus42@gmx.de * Add image for insteon binding (#1196) Signed-off-by: Rob Nielsen <rob.nielsen@yahoo.com> * typo (#1198) Signed-off-by: Mark Theiding <mark.theiding@gmail.com> * Installation details (#1197) Added more details around the installation and configuration process. Fixed that engine no longer logs "Activated scripting support..." Signed-off-by: Mark Theiding <mark.theiding@gmail.com> * Update sitemaps.md (#1202) Added full item definition for usage of visibility. See https://community.openhab.org/t/sitemap-visibility-basic-ui/97304/9 * Updated ecobee logo (https://brand.ecobee.com/) (#1203) Signed-off-by: Rob Nielsen <rob.nielsen@yahoo.com> * tutorial: Fix description of sitemap 'type' (#1204) In the tutorial, the generic sitemap description says that ItemType has to be the same as the type defined in default.items. Looking at https://www.openhab.org/docs/configuration/items.html#type and https://www.openhab.org/docs/configuration/sitemaps.html#element-types this is incorrect as they take different values. The example is even mislading as `Switch` is one of the only types which is common between items and sitemaps. Might be better to describe `Default` instead. Signed-off-by: Christophe Fergeau <cfergeau@redhat.com> * Added information about DateTime Group functions LATEST/EARLIEST (#1206) Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Add section for documentation contributions (#1205) Hopefully this will lower the hurdle for people to submit documentation contributions. I know from myself that I didn't submit various documentation improvements, because I didn't know git and thought it would be a much more involved process. Ideally there would be a separate documentation section, but submitting this under the development contribution page for now (as per discussion with @Confectrician in https://github.com/openhab/openhab-docs/pull/1179#issuecomment-605642091). Note that I am addressing the issue of DCO failures wrt specifying the full name that I ran into myself in https://github.com/openhab/openhab-docs/pull/1197#issuecomment-615597308. I found a good discussion of the issue at https://github.com/probot/dco/issues/43. Signed-off-by: Mark Theiding <mark.theiding@gmail.com> * fix typo (#1209) * add description of Ephemeris localization support (#1210) Add a new section to describe the localization support and how-to steps Signed-off-by: Michael Roßner Schrott.Micha@web.de * Line 115 broken link - should be: (#1217) * Line 115 broken link - should be: ({{base}}/docs/configuration/sitemaps.html#element-types) was: ({{base}}/configuration/configuration/sitemaps.html#element-types) * Removed diplicated docs breadcrumb Signed-off-by: Jerome Luckenbach <github@luckenba.ch> Co-authored-by: Jerome Luckenbach <github@luckenba.ch> * add missing space between words (#1212) * Update configuration.md (#1215) I'm a beginner myself. Though I liked this tutorial very much, it took me some time trying and erroring and finally reading forum posts to get behind this. I didn't even know there was something like a more modern ping. So maybe others are happy to learn this right from the beginning. * Remove architecture from Docker tags (#1220) Docker automatically detects the architecture and downloads the appropriate image (openhab/openhab-docker#213). BuildKit will no longer generate new tags having the architecture (openhab/openhab-docker#293). Signed-off-by: Wouter Born <github@maindrain.net> * slight readability improvements (#1221) * slight readability improvements * Update introduction.md * Update introduction.md * minor wording update * Update eclipse.md (#1225) Clarifying that it's no longer possible to make changes in the Core Framework for 2.5.x. Signed-off-by: Mark Theiding <mark.theiding@gmail.com> * [fmiweather] logo for FMI Weather binding (#929) Signed-off-by: Sami Salonen <ssalonen@gmail.com> * Update eclipse.md (#1226) Added additional structure around install, run, debug and update steps. Provided more pointers to interactions with Eclipse, Maven and Git. Signed-off-by: Mark Theiding <mark.theiding@gmail.com> * Update contributing.md (#1227) Need to escape \< and \> in the sign off message format so users see them explicitly in the Contributing to the Documentation section. Signed-off-by: Mark Theiding <mark.theiding@gmail.com> * Update contributing.md (#1228) Small refinement on documentation change submission flow. Signed-off-by: Mark Theiding <mark.theiding@gmail.com> * Add doc folder to the binding directory structure (#1230) Signed-off-by: Fabian Wolter <github@fabian-wolter.de> * Make Subheadings Use Proper Subheading Syntax (#1234) This way they render out as proper markdown and don't look weird on the website Signed-off-by: Stefan Zabka <zabkaste@informatik.hu-berlin.de> * Remove unnecessary isCancelled() from code example (#1235) Cancelling an already canceled task has no effect. IMHO this check is not necesssary and removal would simplify the code. I came to this because I saw this pattern in many bindings during reviewing. Signed-off-by: Fabian Wolter <github@fabian-wolter.de> * Update thing-xml.md (#1236) Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Fix broken ESH links (#1231) Signed-off-by: Wouter Born <github@maindrain.net> * Update logging.md (#1238) Add information on how to find out the symbolic names of the bundles * Remove Apache Commons from Default Libraries (#1229) See openhab/openhab-addons#7722 Signed-off-by: Fabian Wolter <git@fabian-wolter.de> * Update introduction.md (#1239) * Update introduction.md Signed-off-by: Markus Storm markus.storm@gmx.net * Update introduction.md * Revise Java recommendations (#1240) * Revise Java recommendations * Delete pine.md Do not recommend PINE, it's not supported any longer by openHABian. * Removed sidebar link in config Signed-off-by: Jerome Luckenbach <github@luckenba.ch> Co-authored-by: Jerome Luckenbach <github@luckenba.ch> * Update security.md (#1241) Been using FreeDNS for many years (ever since all these companies got rid of their free tiers) and never an issue! * Fix DecimalType hex conversion example (#1243) See: https://github.com/openhab/openhab-core/issues/1526 Signed-off-by: Wouter Born <github@maindrain.net> * Fix typo (#1244) Signed-off-by: Wouter Born <github@maindrain.net> * Update persistence.md (#1246) Fixes link to quartz docs page. * Revision. (openhab#1187) (#1237) * Revision. (openhab#1187) - Update of screenshots, removal of old screenshots - Chapters for better formatting - Removal of ZWave chapter (one example of adding things should be enough IMHO) - Adding items in simple mode and in "manual" mode Signed-off-by: Sascha Billian <sascha.billian@googlemail.com> * Use one line per sentence Signed-off-by: Sascha Billian <sascha.billian@googlemail.com> Co-authored-by: Jerome Luckenbach <github@luckenba.ch> * Add notes for configuring Synology Diskstation (#1219) * Add notes for configuring Synology Diskstation I have a working set up for SSL enabled remote access on a Synology diskstation, taking advantage of the GUI as much as possible, to ensure automatic renewal of certs from Let's Encrypt, etc. It took me about 8 hours to suss it all out, but it could be achieved in about 30 mins if you knew exactly what to do... may not be widely useful, but since Synology is officially supported, I figured this might be a good addition. There's also a minor error in the 'allow' masks - these should be 192.168.0.0/24 to allow access to anything in the 192.168.0.xxx range. * Updated to use one line per sentence Updated to use one line per sentence - sorry for the delay! * Update security.md * Updated for one line per sentence Updated for one line per sentence Signed-off-by: Andrew Mills mills@prettymachine.co.nz * Bad subnet (#1245) Nginx warns about low address bits of `192.168.0.1/24` because they are meaningless. The correct subnet mask should be `192.168.0.0/24` Signed-off-by: Olivier Béraud <olivierberaud@free.fr> * Fixed broken images. (#1247) * Fixed broken images. Signed-off-by: Jerome Luckenbach <github@luckenba.ch> * Fix image path Signed-off-by: Jerome Luckenbach <github@luckenba.ch> * [documentation] clarification of representation property (#1248) * [documentation] clarification of representation property Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentation] typo Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentation] adopt suggestions of reviewers Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentation] commas Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentation] typo Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentation] addopted suggestions of @bobadair Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentation] typo Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentaion] example added back Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentaion] simplified text Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentation] typo Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * [documentation] adopted reviewer comment Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch> * Add Alexa mapping along side a channel mapping (#1249) * Add Alexa mapping along side a channel mapping It took me a while to find this https://community.openhab.org/t/tagging-devices-for-alexa-support/98155/3 on the Forum and its not clearly documented in the openHAB Amazon Alexa Smart Home Skill or here in Item Metadata. I originally suggested this as an update to the openHAB Amazon Alexa Smart Home Skill documentaion, but it fits better here, then other integrations using metadata (e.g. HomeKit or Google Assistant) could refer to it as well. * Update items.md * Mention defaults for element type setpoint. (#1250) Mention defaults for min, max and step value for element type setpoint. Signed-off-by: Thomas Weiler <toweosp@gmail.com> * Update index.md (#1251) I thought 'workl' was probably intended to be 'work'. * Items - Bedroom_Light written as Light_Bedroom (#1252) Fix small error which might mislead some readers. * Added example for time-weighted averages (#1253) Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Remove deprecated UIs, Eclipse Marketplace from sidebar Signed-off-by: Yannick Schaus <github@schaus.net> * Update branch name in README Signed-off-by: Yannick Schaus <github@schaus.net> Co-authored-by: Markus Storm <markus.storm@gmx.net> Co-authored-by: Nagy Attila Gábor <mrbig@sneaker.hu> Co-authored-by: Christoph Thiede <38782922+LinqLover@users.noreply.github.com> Co-authored-by: Richard Davies <rwdrich@gmail.com> Co-authored-by: jwaes <50528773+jwaes@users.noreply.github.com> Co-authored-by: bracklanna <16140600+bracklanna@users.noreply.github.com> Co-authored-by: Scott Rushworth <openhab@5iver.com> Co-authored-by: cpmeister <mistercpp2000@gmail.com> Co-authored-by: Ross Kennedy <rossko@culzean.clara.co.uk> Co-authored-by: Christoph Weitkamp <github@christophweitkamp.de> Co-authored-by: Skinah <32607303+Skinah@users.noreply.github.com> Co-authored-by: pali <pauli.anttila@gmail.com> Co-authored-by: ljsquare <laurens-jan@merkx-ewals.nl> Co-authored-by: PatrikG <40170469+PatrikG8@users.noreply.github.com> Co-authored-by: Elias H <E.Hackradt@web.de> Co-authored-by: Billy Stevens <contact@wasv.me> Co-authored-by: theiding <mark.theiding@gmail.com> Co-authored-by: jadcx <60408305+jadcx@users.noreply.github.com> Co-authored-by: Bjorn Helgaas <bjorn@helgaas.com> Co-authored-by: Jürgen Baginski <opus42@gmx.de> Co-authored-by: robnielsen <rob.nielsen@yahoo.com> Co-authored-by: GumbyMan82 <40233411+GumbyMan82@users.noreply.github.com> Co-authored-by: Christophe Fergeau <teuf@gnome.org> Co-authored-by: Paulo "JCranky" Siqueira <paulo.siqueira@gmail.com> Co-authored-by: Michael Rossner <Schrott.Micha@web.de> Co-authored-by: BugSmurF <52825547+bugsmurf@users.noreply.github.com> Co-authored-by: Jerome Luckenbach <github@luckenba.ch> Co-authored-by: josefscript <64727123+josefscript@users.noreply.github.com> Co-authored-by: Wouter Born <github@maindrain.net> Co-authored-by: Sami Salonen <ssalonen@gmail.com> Co-authored-by: Fabian Wolter <github@fabian-wolter.de> Co-authored-by: Stefan Zabka <zabkaste@informatik.hu-berlin.de> Co-authored-by: TRS-80 <25938297+TRSx80@users.noreply.github.com> Co-authored-by: sihui <10405486+sihui62@users.noreply.github.com> Co-authored-by: Andrew Mills <amil109@users.noreply.github.com> Co-authored-by: Olivier Béraud <olivbd@users.noreply.github.com> Co-authored-by: Andrew Fiddian-Green <software@whitebear.ch> Co-authored-by: LeeC77 <LeeC77@users.noreply.github.com> Co-authored-by: Thomas Weiler <18066810+toweosp@users.noreply.github.com> Co-authored-by: garretcook <garretcook@gmail.com> Co-authored-by: Michael Fielding <michael.fielding@gmail.com>
2020-09-21 11:29:39 +00:00
|- doc Images and other assets used in the Readme.md
|- src/main
|---- feature
|-------- feature.xml Your OSGI feature file
|---- java Your Java code
|-------- org/openhab/[...]
|- src/main/resources/ESH-INF
|---- binding
|-------- binding.xml Binding name, description, author and other meta data
|---- config Configuration description files when not in things files
|-------- *.xml
|---- i18n Your localized binding texts
|-------- *_<local>.properties
|---- thing One or more xml files with thing descriptions
|-------- *.xml
|- src/test
|---- java It's easy to write unit tests and fellow developers will thank you
|-------- org/openhab/[...]
|---- resources Any resource files used in your unit tests, like test data
|-------- [...]
|- NOTICE License information
| 3rd party content has to be given in the NOTICE file
|- pom.xml Build system file: Describe your dependencies here
|- README.md The file describing your binding
```
* Every Java file must have a license header. You can run ```mvn license:format``` on the root of the repo to automatically add missing headers.
## B. Code formatting rules & style
### Code format
In order to keep the code layout consistent, code formatting rules have been defined.
Rules are enforced as part of the build process using [Spotless Maven Plugin](https://github.com/diffplug/spotless).
To check if your code is following the code style run `mvn spotless:check`. If Maven prints `[INFO] Spotless check skipped` then run `mvn spotless:check -Dspotless.check.skip=false` instead as the check isn't mandatory yet.
To reformat you code run `mvn spotless:apply`
Code styles files are located in here: https://github.com/openhab/static-code-analysis/tree/master/codestyle/src/main/resources
#### Java Code
The rules are defined using the Eclipse Java Formatter definitions. There are plugins available for several IDEs that support these definitons.
* Official [openHAB Eclipse IDE setup](ide/eclipse.html) is preconfigured
* Eclipse standalone installation
- You can manually import [openhab_codestyle.xml](https://raw.githubusercontent.com/openhab/static-code-analysis/master/codestyle/src/main/resources/openhab_codestyle.xml) via `Eclipse Preferences -> Java -> Code Style -> Formatter` and [openhab.importorder](https://raw.githubusercontent.com/openhab/static-code-analysis/master/codestyle/src/main/resources/openhab.importorder) via `Eclipse Preferences -> Java -> Code Style -> Organize Imports`
* IntelliJ using plugin https://plugins.jetbrains.com/plugin/6546-eclipse-code-formatter
- Same files as for the Eclipse standalone installation. Be sure to follow *all* the plugin configuration steps.
#### XML files
* Maven `pom.xml` files shall have 2 space indentation
* Other `xml` files shall have 1 tab indentation
* Line length shall be 120 characters
The rules are defined at https://github.com/openhab/static-code-analysis/tree/master/codestyle/src/main/resources for the Eclipse WTP formatter, but will have to be manually entered into your IDE.
### Java Coding Style
* The [Java naming conventions](http://java.about.com/od/javasyntax/a/nameconventions.htm) should be used for source files.
* Generics must be used where applicable. See example below:
```java
public static <T> boolean isEqual(GenericsType<T> g1, GenericsType<T> g2){
return g1.get().equals(g2.get());
}
```
* Code MUST not show any warnings.
Warnings that cannot be circumvented should be suppressed by using the `@SuppressWarnings` annotation.
* Your classes are generally organised within an internal package
```java
org.openhab.binding.coolbinding.internal
org.openhab.binding.coolbinding.internal.handler
org.openhab.binding.coolbinding.internal.discovery
```
Remember that classes that are meant to be used by scripts or other bindings must be non internal.
* Every class, except data-transfer-objects (DTO), must be annotated with `@NonNullByDefault`.
For details see [Null annotation](#null-annotations).
* OSGi Declarative Services annotations are to be used
```java
@Component(service=MyCoolService.class)
public class MyCoolService {
@Reference
private @NonNullByDefault({}) ItemRegistry itemRegistry;
}
```
## C. Documentation
JavaDoc is required to describe the purpose and usage of every:
* class,
* interface,
* enumeration (except inner classes and enums),
* constant, field and method with visibility of default, protected or public.
An @author tag is required within the JavaDoc for every author who made a substantial contribution to the file.
New @author tags should be placed below the older ones.
Data-transfer-objects (DTOs map from Json/XML to Java classes) do not require JavaDoc.
## D. Language Levels and Libraries
1. openHAB generally targets the long time supported Java 11 releases with the following restrictions:
* To allow optimized runtimes, the set of Java packages to be used is further restricted to [Compact Profile 2](https://www.oracle.com/technetwork/java/embedded/resources/tech/compact-profiles-overview-2157132.html).
2. The [OSGi Core Release 7](https://osgi.org/download/r7/osgi.core-7.0.0.pdf) with [OSGI Compendium Release 7](https://osgi.org/download/r7/osgi.cmpn-7.0.0.pdf) is targeted, and newer features should not be used.
3. [slf4j](http://slf4j.org) is used for logging.
Rewrite developer section (#942) * Rewrite developer section * More work on module types * More module-type stuff * Adapt vuepress files * Write binding doc * Add TODOs for missing topics * Add all missing topics from ESH. * Tests * Audio extensions * Utilities * i18n * Event-bus * Small fixes * Command Description * Add some tocs * Add concept drawing to binding dev. * Update developers/osgi/configadmin.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update administration/logging.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update developers/bindings/thing-xml.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Convert HTML tables to Markdown Signed-off-by: Hakan Tandogan <hakan@tandogan.com> * Resolved one line per sentence review parts. Signed-off-by: Jerome Luckenbach <github@luckenba.ch> * Update developers/index.md * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Add persistence placeholder. Address review comments * fix persistence subdirectory Signed-off-by: David Graeff <david.graeff@web.de> * Update developers/audio/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/contributing.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/osgi/osgids.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/transformations/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/ioservices/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Remove extensionservices (for now ;) Signed-off-by: David Graeff <david.graeff@web.de> * Fix typos Signed-off-by: David Graeff <david.graeff@web.de> * Added example code for 'DynamicCommandDescriptionProvider' and 'DynamicCommandDescriptionProvider' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Added example code for 'ThingHandlerFactory' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Applied review comments Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de>
2019-05-02 18:52:37 +00:00
You might also have the need to use other libraries for specific use cases like XML processing, networking etc.
See [Default libraries](#default-libraries) for more details.
## E. Runtime Behavior
1. Overridden methods from abstract classes or interfaces are expected to return fast unless otherwise stated in their JavaDoc.
Expensive operations should therefore rather be scheduled as a job.
2. Creation of threads must be avoided.
Instead, resort into using existing schedulers which use pre-configured thread pools.
If there is no suitable scheduler available, start a discussion in the forum about it rather than creating a thread by yourself.
For periodically executed jobs that do not require a fixed rate [scheduleWithFixedDelay](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ScheduledExecutorService.html#scheduleWithFixedDelay(java.lang.Runnable,long,long,java.util.concurrent.TimeUnit)) should be preferred over [scheduleAtFixedRate](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate(java.lang.Runnable,long,long,java.util.concurrent.TimeUnit)).
3. Bundles need to cleanly start and stop without throwing exceptions or malfunctioning.
This can be tested by manually starting and stopping the bundle from the console (```stop <bundle-id>``` resp. ```start <bundle-id>```).
4. Bundles must not require any substantial CPU time.
Test this e.g. using "top" or VisualVM and compare CPU utilization with your bundle stopped vs. started.
## F. Logging
This section explains some logging usage patterns.
The logger that is used allows logging at multiple severity levels (trace, info, debug, warn, error).
Most of the time, a level of `warn` or `debug` will be used.
Please remember that every logging statement adds to code size and runtime cost.
* Loggers should be [non-static](http://slf4j.org/faq.html#declared_static), `final` when ever possible and have the name `logger`.
```java
class MyCoolClass {
private final Logger logger = LoggerFactory.getLogger(MyCoolClass.class);
}
```
* Parametrized logging must be used (instead of string concatenation).
```java
void myFun() {
String someValue = "abc";
int someInt = 12;
logger.log("Current value is {} and int is {}", someValue, someInt);
}
```
* Exceptions with stacktraces in the log are considered to be bugs in your binding that should be reported and fixed.
If you add an exception as a last parameter to the logging, the stack trace will be printed.
Configuration errors by users should only print log messages about what's wrong. In that case you would use `e.getMessage()`.
```java
void myFun() {
try {
doSomething();
} catch (IOException e) {
logger.warn("Explain what went wrong and how to avoid it. You can have arguments {}.", someVariable, e);
}
}
```
* Logging is not a replacement for using the debugger.
```java
void myFun() {
logger.trace("Enter myfun"); // DONT, DONT, really DONT do that
doSomething();
logger.trace("Leave myfun"); // DONT, DONT, really DONT do that
}
```
* Logging is not a replacement to use respective `update*` methods of the framework
```java
void myFun() {
logger.debug("And now the thing goes online"); // DONT, DONT, really DONT do that
updateState(ThingState.ONLINE);
}
```
Logging levels should focus on the system itself and describe its state.
As every bundle is only one out of many, logging should be done very scarce.
It should be up to the user to increase the logging level for specific bundles, packages or classes if necessary.
This means in detail:
* `error` logging should only be used
- to inform the user that something is tremendously wrong in the setup, the system cannot function normally anymore, and there is a need for immediate action.
- in case some code fails irrecoverably and the user should report it as a severe bug.
* `warn` logging should only be used
- to inform the user that something seems to be wrong in the overall setup, but the system can nonetheless function as normal,
- in recoverable situations when a section of code that is not accessed under normal operating conditions is reached.
* `info` logging should be used sparsely.
e.g. a newly started component or a user file that has been loaded.
* `debug` logging should be used for detailed logging
- to give the user debug information in cases of unexpected behavior.
- to log exceptions in case of temporary problems, like connection problems.
In case of such exceptions this should be reflected in an updated state of the binding.
* `trace` logging should be used for verbose debug logging.
For example printing output values that can be large, but can help when debugging changed external apis.
In general bindings should NOT log to error/warn if e.g. connections are dropped -
this is considered to be an external problem and from a system perspective to be a normal and expected situation.
The correct way to inform users about such events is to update the Thing status accordingl
Note that all events (including Thing status events) are anyhow already logged.
## G. Other code attributions
If you copy code from somewhere make sure that the license is compatible to the Eclipse License version 2.
This includes the Apache license, the Eclipse license v1, the MIT and BSD license.
You may also use Stackoverflow snippets, because they are automatically MIT licensed.
Please make sure to not remove author attributions or modify the license header in code files that you have copied.
Add the filename, author and license to the NOTICE file of your addon (except for short snippets, eg from Stackoverflow etc).
## Guideline details
This sections provides some background and more detailed information about parts of the guideline.
### Static Code Analysis
The openHAB Maven build includes [tooling for static code analysis](https://github.com/openhab/static-code-analysis) that will validate your code against the Coding Guidelines and some additional best practices.
Information about the checks can be found [here](https://github.com/openhab/static-code-analysis/blob/master/docs/included-checks.md).
The tool will generate an individual report for each bundle that you can find in `path/to/bundle/target/code-analysis/report.html` file and a report for the whole build that contains links to the individual reports in the `target/summary_report.html`.
The tool categorizes the found issues by priority: 1(error),2(warning) or 3(info).
If any error is found within your code the Maven build will end with failure.
You will receive detailed information (path to the file, line and message) listing all problems with Priority 1 and 2 on the console.
### Null Annotations
[Null annotations](https://wiki.eclipse.org/JDT_Core/Null_Analysis) are used from the Eclipse JDT project.
Those annotations help the compiler and our static code analyser to figure out if a potential null pointer access would happen in your code.
Classes (except data transfer objects (DTO)) must be annotated with `@NonNullByDefault`:
```java
@NonNullByDefault
public class MyClass(){}
```
This forces you to think about every field in your class if it can be null at any point, or should rather be default initialized.
If you have fields that are neither marked as nullable, nor are initialized, the code will not compile.
Fields that can be null are to be annotated like this:
```java
private @Nullable MyType myField;
```
The compiler will force you to check if `myField` is null, before using it:
```java
private void myFunction() {
final MyType myField = this.myField; // You need a local copy of the field for thread safety.
if (myField != null) {
myField.soSomething();
}
}
```
Methods should be annotated as follows:
```java
private @Nullable MyReturnType myMethod(){};
```
If you reference an OSGi service, OSGi will already make sure that the field is non-null.
The compiler doesn't know about that fact though.
You must therefore disable null-checks for such references:
```java
@Reference
private @NonNullByDefault({}) MyService injectedService;
```
Rewrite developer section (#942) * Rewrite developer section * More work on module types * More module-type stuff * Adapt vuepress files * Write binding doc * Add TODOs for missing topics * Add all missing topics from ESH. * Tests * Audio extensions * Utilities * i18n * Event-bus * Small fixes * Command Description * Add some tocs * Add concept drawing to binding dev. * Update developers/osgi/configadmin.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update administration/logging.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update developers/bindings/thing-xml.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Convert HTML tables to Markdown Signed-off-by: Hakan Tandogan <hakan@tandogan.com> * Resolved one line per sentence review parts. Signed-off-by: Jerome Luckenbach <github@luckenba.ch> * Update developers/index.md * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Add persistence placeholder. Address review comments * fix persistence subdirectory Signed-off-by: David Graeff <david.graeff@web.de> * Update developers/audio/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/contributing.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/osgi/osgids.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/transformations/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/ioservices/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Remove extensionservices (for now ;) Signed-off-by: David Graeff <david.graeff@web.de> * Fix typos Signed-off-by: David Graeff <david.graeff@web.de> * Added example code for 'DynamicCommandDescriptionProvider' and 'DynamicCommandDescriptionProvider' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Added example code for 'ThingHandlerFactory' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Applied review comments Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de>
2019-05-02 18:52:37 +00:00
### Default Libraries
In order to not have every binding use a different library, the following packages are available by default:
For XML Processing
* com.thoughtworks.xstream
* com.thoughtworks.xstream.annotations
* com.thoughtworks.xstream.converters
* com.thoughtworks.xstream.io
* com.thoughtworks.xstream.io.xml
For JSON Processing
* com.google.gson.*
For HTTP Operations
* org.eclipse.jetty.client.*
* org.eclipse.jetty.client.api.*
* org.eclipse.jetty.http.*
* org.eclipse.jetty.util.*
::: tip Note
HttpClient instances should be obtained by the handler factory through the HttpClientFactory service and unless there are specific configuration requirements, the shared instance should be used.
:::
Rewrite developer section (#942) * Rewrite developer section * More work on module types * More module-type stuff * Adapt vuepress files * Write binding doc * Add TODOs for missing topics * Add all missing topics from ESH. * Tests * Audio extensions * Utilities * i18n * Event-bus * Small fixes * Command Description * Add some tocs * Add concept drawing to binding dev. * Update developers/osgi/configadmin.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update administration/logging.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Update developers/bindings/thing-xml.md Co-Authored-By: davidgraeff <david.graeff@web.de> * Convert HTML tables to Markdown Signed-off-by: Hakan Tandogan <hakan@tandogan.com> * Resolved one line per sentence review parts. Signed-off-by: Jerome Luckenbach <github@luckenba.ch> * Update developers/index.md * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Add persistence placeholder. Address review comments * fix persistence subdirectory Signed-off-by: David Graeff <david.graeff@web.de> * Update developers/audio/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/contributing.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/buildsystem.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/guidelines.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/osgi/osgids.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/transformations/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Update developers/ioservices/index.md Co-Authored-By: davidgraeff <davgraeff@gmail.com> * Remove extensionservices (for now ;) Signed-off-by: David Graeff <david.graeff@web.de> * Fix typos Signed-off-by: David Graeff <david.graeff@web.de> * Added example code for 'DynamicCommandDescriptionProvider' and 'DynamicCommandDescriptionProvider' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Added example code for 'ThingHandlerFactory' Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de> * Applied review comments Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de>
2019-05-02 18:52:37 +00:00
For Web Socket Operations
* org.eclipse.jetty.websocket.client
* org.eclipse.jetty.websocket.api
::: tip Note
WebSocketClient instances should be obtained by the handler factory through the WebSocketClientFactory service and unless there are specific configuration requirements, the shared instance should be used.
:::