Deutsch: Plugins schreiben
Writing Plugins for OpenYaBS¶
OpenYaBS plugins extend the application without touching the core codebase. Using a single, unified API — ExtensionContext — a plugin can add:
- Commands (in the Plugins menu and in Search anything via
Shift Shift) - Custom search results in Search anything
- Settings pages (under Settings › Plugins, searchable via the settings search bar)
- Custom tabs in the main window
- View decorations & locks (header badges, banners with action buttons, content locks on record views)
- Activity reactions (new/changed/deleted records, exported PDF/ODT/e-invoice files, messages)
- Record interceptors (validate, modify, or veto saving and deleting of records)
- Custom template placeholders (
[myplugin.key]in LibreOffice.odt/.fodttemplates) - Journal exports & tax-adviser ZIP entries (extra items in the Journal Export menu and files inside the tax-adviser ZIP)
- Pre-send e-mail warnings (interactive confirmation or batch skip for sensitive documents)
- E-invoice skip rules (fall back to plain PDF instead of ZUGFeRD / XRechnung for matching invoices)
- GDPR / privacy integration (custom retention deadlines, Art. 15/20 export files, cleanup on final deletion)
- Archived originals for locked documents (serve immutable originals and control stamped duplicates)
- Plugin-scoped internationalization (i18n) (automatic locale resolution,
MessageFormatarguments, zero key collisions)
Plugins can be written either as a single Groovy script (.groovy, zero build step) or as a Java JAR (.jar, full IDE & build tooling). Both receive the exact same ExtensionContext API.
Table of Contents¶
- How Plugins Work in OpenYaBS
- Groovy vs. Java: Pros, Cons, and Decision Guide
- Quickstart: Groovy Plugin (30 Seconds)
- Quickstart: Java Plugin (Gradle and Java 21)
- Complete API Reference
YabsExtensionand Version CompatibilityExtensionContextContributions (Auto-Removed on Stop)ExtensionContextActions, Helpers, and i18n- Supporting API Interfaces and Types
- Cookbook: Practical Examples (Groovy and Java)
- 1. Commands, Background Work, and Custom Tabs
- 2. Settings Pages: Per-Machine vs. Per-Database Config
- 3. Search Anything Provider
- 4. Reacting to Records and Exported Files (
onActivity) - 5. Validating and Vetoing Saves or Deletes (
addRecordModifier) - 6. Decorating and Locking Record Views (
onView) - 7. Custom Template Placeholders (
addTemplateFields) - 8. Journal Export and Tax-Adviser ZIP (
addJournalExport) - 9. Pre-Send E-Mail Warnings and E-Invoice Skip Rules
- 10. GDPR Retention, Export, and Final Deletion (
addPrivacyContributor) - 11. Archived Originals for Locked Records (
addLockedDocumentProvider) - 12. Multi-Language Plugins and i18n (
addTranslationBundle,tr) - 13. Custom Database Tables and Cross-Database JDBC
- 14. Working with OpenYaBS Domain Objects (
DatabaseObject,Context) - Threading, Bundled Libraries, and Best Practices
- Testing and Debugging Plugins
- Developing Plugins with AI Coding Agents
- Official Plugins as Reference Implementations
- Classic Plugins (Legacy)
How Plugins Work in OpenYaBS¶
- Location: Plugins live in the
plugins/directory inside your YaBS application folder (Settings › Plugins › Open folder). - Management UI: Settings › Plugins lists every built-in, Groovy, and Java plugin with its state (
RUNNING,STOPPED,DISABLED,FAILED), addition count, and error message if failed. Under Add a plugin, you can click New Groovy plugin…, Import Groovy plugin…, Import Java plugin…, or simply drag and drop a.groovyor.jarfile onto the page. - Non-blocking startup: After login, OpenYaBS discovers plugins and compiles Groovy scripts in a background thread (
yabs-plugins), showing progress in the status bar (Loading plugins (2/5): …), then calls each plugin'sstart(ctx)sequentially on the Swing Event Dispatch Thread (EDT). - Fault isolation: If a plugin throws an exception in
start(ctx)or fails itsminYabsVersion()check, any partial registrations are rolled back, the plugin is markedFAILEDwith its error message, and OpenYaBS and all other plugins continue normally. - Automatic cleanup & hot reload: Every contribution registered through
ExtensionContextis owned by the plugin'sidand automatically removed when the plugin stops, is disabled, reloaded, uninstalled, or fails to start. You can iterate and reload plugins without restarting OpenYaBS. - Database switching: When the user switches to or creates another database connection, OpenYaBS calls
stopAll()and thenstartAllInBackground(). Always guard database access instart(ctx)so your plugin handles reconnects and headless test runs cleanly. - Plugin IDs & seamless replacement: Every plugin must have a unique, stable
id(). Two plugins with the same ID never run simultaneously. Installing a new file whose plugin has the same ID as an existing file (for example, upgrading a Groovy prototype to a Java JAR) automatically stops the old plugin, activates the new one, and renames the old file to<filename>.replaced. - Per-plugin files on disk: Inside
plugins/, OpenYaBS manages: plugins.properties— comma-separated list of disabled plugin IDs<safe-plugin-id>.properties— key/value store returned byctx.settings()<safe-plugin-id>/— private directory returned byctx.dataFolder()(created on demand)
Groovy vs. Java: Pros, Cons, and Decision Guide¶
Both Groovy and Java plugins have full access to ExtensionContext and all OpenYaBS classes. The difference is developer workflow, packaging, performance, and maintainability.
Side-by-Side Comparison¶
| Aspect | Groovy Plugin (.groovy) |
Java Plugin (.jar) |
|---|---|---|
| API entry point | Script variable yabs (ExtensionContext) and plugin (GroovyExtension) |
YabsExtension.start(ExtensionContext ctx) |
| Metadata | Header comments: // @id, @name, @description, @version, @author, @minYabsVersion |
Interface methods: id(), name(), description(), version(), author(), minYabsVersion() |
| Stop hook | onStop = { … } or yabs.onStop { … } |
stop() and/or ctx.onStop(() -> …) |
| Build toolchain | None — edit and save a plain text file | JDK 21 + Gradle (or Maven / javac + jar) |
| Reload cycle | Instant (Ctrl+S in the built-in editor) |
Rebuild JAR → copy / import → click Reload |
| Built-in editor | Yes (Settings › Plugins › Edit): syntax highlighting, line numbers, F5 syntax check, snippets |
No — use IntelliJ IDEA, VS Code, Eclipse, or CLI + AI agent |
| Type safety | Dynamic typing (runtime errors for typos unless @CompileStatic is used) |
Full compile-time type checking and IDE refactoring |
| Startup overhead | Parsed and compiled by GroovyShell on every app start (noticeable for large scripts) |
Pre-compiled bytecode — near-instant load |
| Code organization | Single .groovy file (editor disables highlighting above ~60,000 chars) |
Unlimited packages, classes, helpers, and clean separation of concerns |
| Bundled resources | Not supported natively (must embed as strings or ship separate files) | Native JAR resources (getResourceAsStream): .fodt templates, i18n/*.properties, JSON catalogs, icons |
| Third-party libraries | No @Grab (Apache Ivy is intentionally excluded from OpenYaBS); limited to JDK + bundled OpenYaBS libs |
Full support — bundle extra dependencies in a fat/shaded JAR if needed |
| Multiple plugins per file | 1 plugin per .groovy file |
Multiple YabsExtension implementations in one JAR (one class per line in META-INF/services/…) |
| Unit testing & CI | Possible via ExtensionManager.install(file), harder to unit-test internal helpers |
First-class JUnit 5 testing of pure logic, SQL against H2, and headless ExtensionManager |
| Distribution | Share one .groovy file; users can inspect/tweak directly |
Share one .jar file; clean versioning and reproducible builds |
Groovy Plugins — Pros & Cons¶
Pros:
- Zero setup: No JDK install, no Gradle, no IDE required — anyone running OpenYaBS can write and run a plugin in 30 seconds.
- Built-in editor: Includes Groovy syntax highlighting, line numbers, working code snippets (Insert example), F5 compile check with jump-to-line error reporting, and Ctrl+S instant reload.
- Concise syntax: Groovy closures automatically coerce to Java functional interfaces (Runnable, Consumer, Function, Predicate, Supplier), and dynamic property access makes quick experiments effortless.
- Great for AI quick-fixes & automations: An AI agent can generate a single self-contained .groovy file that the user drops straight into plugins/ without running a build tool.
Cons:
- Runtime-only error detection: Misspelled method names or wrong argument types only fail when that code path executes.
- No bundled resources: Shipping LibreOffice .fodt templates, .properties translation files, or JSON catalogs is awkward compared to a JAR.
- No @Grab / external dependencies: Apache Ivy is excluded from OpenYaBS's Groovy runtime, so Groovy plugins can only use the JDK and libraries already bundled in OpenYaBS's lib/.
- Does not scale well to large plugins: Startup compilation takes seconds for large scripts, single-file navigation becomes painful, and the built-in editor turns off syntax highlighting above ~60,000 characters.
Java Plugins — Pros & Cons¶
Pros:
- Compile-time safety: The Java 21 compiler catches API mismatches, missing imports, and wrong types before the plugin ever runs.
- Clean multi-class architecture: Separate persistence (Store), pure business logic (Validator), Swing UI (Ui), and entry point (Plugin), just like all official OpenYaBS plugins.
- First-class resources & i18n: Bundle .fodt/.odt templates, UTF-8 messages_en.properties / messages_de.properties files, JSON data catalogs, and icons directly inside src/main/resources/.
- Fast startup & high performance: Pre-compiled bytecode loads cleanly through an isolated URLClassLoader.
- Full automated testing: Write fast JUnit 5 tests for validators, SQL queries (against in-memory H2), i18n bundles, and headless ExtensionManager lifecycle checks — ideal for AI coding agents running ./gradlew test in a loop!
- Third-party libraries: If you need a library not shipped with OpenYaBS, you can shade/bundle it inside your plugin JAR.
Cons:
- Requires a build toolchain: Needs JDK 21 and Gradle (or Maven) to compile and package the JAR.
- Slightly slower manual edit-test loop: Requires running ./gradlew jar and clicking Reload (though automated JUnit tests largely offset this).
Decision Guide: When to Choose Which?¶
| Choose Groovy if… | Choose Java if… |
|---|---|
| You want a small automation (< ~300 lines): custom command, notification, quick search provider, simple save rule. | You are building a domain/industry module (custom DB tables, dialogs, reports, exports, templates). |
| You want to prototype an idea live inside OpenYaBS without setting up a build environment. | You want to ship .fodt templates, multi-language .properties bundles, or data catalogs inside one JAR. |
| The end user should be able to open and tweak the script directly in Settings › Plugins › Edit. | You want compile-time verification, JUnit 5 tests, Git/CI workflows, or reliable distribution to many users. |
| You are only using OpenYaBS's built-in classes and JDK APIs. | You need third-party libraries or multiple classes/packages. |
Seamless Migration Path: Groovy → Java¶
You can safely start in Groovy and later rewrite the plugin in Java without breaking existing installations:
- In your Java
YabsExtension, return the exact sameid()that the Groovy script used (e.g."groovy.my-plugin"or your custom// @id). - When the user installs the new
.jarvia Settings › Plugins › Import Java plugin…, OpenYaBS automatically stops the Groovy plugin, activates the Java plugin, and renamesmy-plugin.groovytomy-plugin.groovy.replaced. - Because
ctx.settings(),ctx.dataFolder(), and any custom database tables are keyed byid(), all user settings, files, and data are preserved seamlessly. (The official GoBD plugin uses this exact mechanism withID = "groovy.gobd-compliance".)
Quickstart: Groovy Plugin (30 Seconds)¶
Option A: Using the Built-In Plugin Editor¶
- Open Settings › Plugins and click New Groovy plugin….
- Enter a name (e.g.
invoice-helper). OpenYaBS createsplugins/invoice-helper.groovyfrom a working template and opens the Groovy Plugin Editor. - Use Insert example ▾ to insert working snippets (command, search provider, activity listener, settings page, custom tab, record modifier, stored settings, background task).
- Press
F5(Check) to syntax-check in the background (errors jump straight to the offending line). - Press
Ctrl+S(Save and start) to save and immediately hot-reload the plugin. Click Other editor to edit the file in VS Code / IntelliJ / your system editor instead.
Option B: Creating a File Directly in plugins/¶
Create plugins/invoice-helper.groovy (UTF-8):
// @id com.example.invoice-helper
// @name Invoice Helper
// @description Notifies on new invoices and adds a quick lookup command
// @version 1.0.0
// @author Your Name
// @minYabsVersion 2.0.10
import mpv5.db.common.Context
import mpv5.db.common.DatabaseObject
import mpv5.db.objects.Item
import mpv5.handler.Activity
import mpv5.plugin.api.SearchResult
// 1. Register a command in the "Plugins" menu and "Search anything" (Shift Shift)
yabs.addCommand('Count open invoices', 'Counts all unpaid invoices in the background', {
yabs.background({
def all = DatabaseObject.getObjects(Context.getInvoice())
all.count { Item inv ->
inv.__getIntstatus() != Item.STATUS_PAID && inv.__getIntstatus() != Item.STATUS_CANCELLED
}
}, { openCount ->
yabs.notify("Open invoices: ${openCount}")
})
})
// 2. React to newly created invoices (locale-independent via Context!)
yabs.onActivity({ Activity.Entry entry ->
if (entry.kind == Activity.Kind.CREATED && Context.getInvoice().equals(entry.context)) {
yabs.notify("New invoice created: ${entry.text}")
}
})
// 3. Add custom results to "Search anything" (runs on a background thread)
yabs.addSearchProvider({ String query ->
if (query == null || !query.toLowerCase().startsWith('open ')) {
return []
}
def needle = query.substring(5).trim().toLowerCase()
if (needle.isEmpty()) {
return []
}
[new SearchResult("Search web for '${needle}'", 'Opens in default browser', {
java.awt.Desktop.desktop.browse(new URI('https://duckduckgo.com/?q=' + URLEncoder.encode(needle, 'UTF-8')))
} as Runnable)]
})
// 4. Optional cleanup when the plugin stops (disabled, reloaded, or app closes)
onStop = {
// Only needed for resources you created yourself (timers, threads, sockets).
// Commands, listeners, and providers registered via 'yabs' are removed automatically.
}
Save the file, then click Reload in Settings › Plugins (or restart OpenYaBS).
Groovy Plugin Details & Rules¶
- Header tags: Must appear at the very top of the file as
// @key value. Parsing stops at the first line that is neither blank nor a//comment. Keys are case-insensitive: @id— stable unique ID (defaults togroovy.<filename-without-extension>)@name— display name (defaults to<filename-without-extension>)@description— short description (defaults to"")@version— version string (defaults to"1.0")@author— author name (defaults to"")@minYabsVersion(aliases:@minYabs,@minVersion) — minimum OpenYaBS release version (defaults tonull, i.e., any version)- Bound variables:
yabs— theExtensionContextplugin— theGroovyExtensionwrapper itself- Returning a
YabsExtensionobject: Instead of callingyabs.*at top level, a Groovy script mayreturnan object implementingmpv5.plugin.api.YabsExtension. OpenYaBS will then delegatename(),description(),version(),author(),minYabsVersion(),start(ctx), andstop()to that object (note thatid()is still read from@idorgroovy.<filename>before execution).
Quickstart: Java Plugin (Gradle and Java 21)¶
1. Project Structure (Standalone Plugin Repository)¶
my-openyabs-plugin/
├── build.gradle
├── settings.gradle
└── src/
├── main/
│ ├── java/com/example/myplugin/
│ │ └── HelloPlugin.java
│ └── resources/
│ ├── META-INF/services/
│ │ └── mpv5.plugin.api.YabsExtension
│ └── com/example/myplugin/i18n/
│ ├── messages_en.properties
│ └── messages_de.properties
└── test/
└── java/com/example/myplugin/
└── HelloPluginTest.java
2. Implement YabsExtension¶
src/main/java/com/example/myplugin/HelloPlugin.java:
package com.example.myplugin;
import mpv5.plugin.api.ExtensionContext;
import mpv5.plugin.api.YabsExtension;
public final class HelloPlugin implements YabsExtension {
public static final String ID = "com.example.hello";
private ExtensionContext ctx;
@Override
public String id() {
return ID;
}
@Override
public String name() {
return ctx != null ? ctx.tr("plugin.name") : "Hello Plugin";
}
@Override
public String description() {
return ctx != null ? ctx.tr("plugin.description") : "Example Java plugin for OpenYaBS.";
}
@Override
public String version() {
return "1.0.0";
}
@Override
public String author() {
return "Your Name";
}
@Override
public String minYabsVersion() {
return "2.0.10";
}
@Override
public void start(ExtensionContext yabs) throws Exception {
this.ctx = yabs;
ClassLoader cl = HelloPlugin.class.getClassLoader();
yabs.addTranslationBundle("en", "/com/example/myplugin/i18n/messages_en.properties", cl);
yabs.addTranslationBundle("de", "/com/example/myplugin/i18n/messages_de.properties", cl);
yabs.addCommand(
yabs.tr("cmd.greet.title"),
yabs.tr("cmd.greet.desc"),
() -> yabs.notify(yabs.tr("cmd.greet.msg", yabs.yabsVersion())));
yabs.onStop(() -> {
// Release any custom threads, timers, or connections here.
});
}
@Override
public void stop() {
this.ctx = null;
}
}
3. Register via Java ServiceLoader¶
Create src/main/resources/META-INF/services/mpv5.plugin.api.YabsExtension with one fully qualified class name per line:
com.example.myplugin.HelloPlugin
Note: A single JAR may list multiple
YabsExtensionclasses (one per line). They share oneURLClassLoaderand are reloaded or uninstalled together. IfMETA-INF/services/mpv5.plugin.api.YabsExtensionis missing or empty, OpenYaBS rejects the JAR on import.
4. build.gradle (Standalone)¶
Point openyabsDir at an extracted OpenYaBS installation (containing openyabs.jar and lib/*.jar) or a local OpenYaBS build (build/libs):
plugins {
id 'java'
}
group = 'com.example'
version = '1.0.0'
def openyabsDir = findProperty('openyabsDir') ?: '/path/to/openyabs'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
tasks.withType(JavaCompile).configureEach {
options.release = 21
options.encoding = 'UTF-8'
}
repositories {
mavenCentral()
}
dependencies {
compileOnly files("${openyabsDir}/openyabs.jar")
compileOnly fileTree(dir: "${openyabsDir}/lib", include: ['*.jar'])
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testImplementation files("${openyabsDir}/openyabs.jar")
testImplementation fileTree(dir: "${openyabsDir}/lib", include: ['*.jar'])
}
test {
useJUnitPlatform()
}
jar {
archiveBaseName = 'hello-plugin'
manifest {
attributes(
'Implementation-Title': 'OpenYaBS Hello Plugin',
'Implementation-Version': project.version
)
}
}
Build and install:
./gradlew jar
Then install build/libs/hello-plugin-1.0.0.jar via Settings › Plugins › Import Java plugin… (or drag and drop it onto the Plugins page).
Adding an official/in-repo plugin inside the
openyabsrepository: OpenYaBS's rootbuild.gradleautomatically discovers every subdirectoryplugins/<name>/that containssrc/main/java! It creates a Gradle source set, compiles against OpenYaBS, wires it intosrc/test, and registers a<name>PluginJartask outputtingbuild/plugins/<name>.jar(run./gradlew pluginJars).Bundling third-party dependencies: If your Java plugin depends on an external library that is not already in OpenYaBS's
lib/, package it into your JAR (e.g. with the Gradle Shadow plugin or by unpackingconfigurations.runtimeClasspathintojar), keepingopenyabs.jarandlib/*.jarascompileOnlyso they are never duplicated in your plugin JAR.
Complete API Reference¶
All public plugin API classes live in package mpv5.plugin.api (browse on GitHub).
YabsExtension and Version Compatibility¶
Source: mpv5.plugin.api.YabsExtension
| Method | Required? | Default | Description |
|---|---|---|---|
String id() |
Yes | — | Stable unique identifier (e.g. "com.example.myplugin"). Used for deduplication, replacement, settings(), dataFolder(), and i18n scoping. |
String name() |
Yes | — | Display name shown in Plugin Manager and Plugins menu. |
String description() |
No | "" |
Short 1–2 sentence summary shown in Plugin Manager. |
String version() |
No | "1.0" |
Plugin version string (e.g. "1.2.0"). |
String author() |
No | "" |
Author or organization name. |
String minYabsVersion() |
No | null |
Minimum required OpenYaBS version (e.g. "2.0.10"). null or empty means any version. |
void start(ExtensionContext ctx) throws Exception |
Yes | — | Called on the Swing EDT to initialize the plugin and register contributions. Any thrown exception marks the plugin FAILED and rolls back partial registrations. |
void stop() |
No | no-op | Called on the Swing EDT when the plugin stops. Contributions registered through ctx are already removed by OpenYaBS; only free resources the plugin created itself (threads, timers, sockets, keys). |
How minYabsVersion() is checked:
- On formal releases (e.g. 2.0.17), semantic version comparison is strictly enforced (current >= minYabsVersion).
- On development/CI builds (e.g. 2.0-dev or 2.0.17-dev.123), plugins targeting the active major.minor release line are permitted so developers and CI can test upcoming features.
- Pass -Dyabs.plugins.ignoreVersion=true on the JVM command line to bypass version checks during debugging.
ExtensionContext Contributions (Auto-Removed on Stop)¶
Source: mpv5.plugin.api.ExtensionContext
Everything registered via these methods is tracked under the plugin's id() and automatically unregistered when the plugin stops, reloads, is disabled, or fails during start().
| Method | Callback Thread | What It Does |
|---|---|---|
addCommand(String title, String description, Runnable action) |
Swing EDT | Adds an action to the Plugins menu (grouped by plugin name) and to Search anything (Shift Shift). Exceptions are caught and reported without crashing OpenYaBS. |
addSettingsPage(String title, String description, Supplier<JComponent> page) |
Swing EDT | Adds a page to Settings under group Plugins (also indexed by Settings search). page.get() is invoked lazily when the user opens the page. |
addSearchProvider(Function<String, List<SearchResult>> provider) |
Background thread | Supplies custom entries in Search anything (Shift Shift) for the user's query string. Keep it fast; return an empty list if nothing matches. |
onActivity(Consumer<Activity.Entry> listener) |
Swing EDT | Notified whenever records are created/changed/deleted, files (PDF/ODT/e-invoice) are exported, or messages/warnings occur. Check entry.draft before finalizing on FILE events. |
addRecordModifier(DatabaseObjectModifier modifier) |
Caller thread (typically EDT) | Intercepts DatabaseObject lifecycle events (modifyOnSave, modifyOnDelete, executeAfterCreate, executeAfterSave, modifyOnExplode, modifyOnResolve). Throw ChangeNotApprovedException to veto a save or delete. |
onView(Consumer<DataPanel> listener) |
Swing EDT | Called whenever a record view (DataPanel) opens or displays another record — and immediately for all views already open when the plugin starts. Decorate with badges, banners, or content locks. |
addJournalExport(JournalExport export) |
export: EDTadviserPackageEntries: Background |
Adds an entry to the Journal's Export menu and can contribute extra files (e.g. CSVs) to the tax-adviser ZIP package (JournalAdviserPackage). |
addTemplateFields(Function<DatabaseObject, Map<String, Object>> provider) |
Export thread | Supplies extra placeholder key -> value pairs when formatting a DatabaseObject for .odt/.fodt/PDF export. Keys map to [key] placeholders in templates. |
addMailWarningProvider(Function<DatabaseObject, String> provider) |
Interactive: EDT Batch: Background |
Called before e-mailing a document. Return a non-empty warning message to ask for confirmation in interactive mode — or log and skip sending in batch mode. Return null/empty for no warning. |
addEInvoiceSkipRule(Predicate<Item> rule) |
Export / Mail thread | Return true to force plain PDF instead of ZUGFeRD / XRechnung for matching invoices (e.g. VAT-exempt services not subject to e-invoicing mandates). |
addPrivacyContributor(PrivacyContributor contributor) |
Caller / Background | Integrates plugin-owned personal data with OpenYaBS's GDPR subsystem: additional retention deadlines, Art. 15/20 export ZIP entries, and cleanup on final contact deletion. |
addLockedDocumentProvider(LockedDocumentProvider provider) |
Caller / EDT | Tells OpenYaBS that a record is locked with an archived original file. Print, PDF, preview, ODT, and e-invoice open the archived file instead of regenerating it, and coordinate stamped duplicates if the archive file is missing. |
addTranslations(String languageCode, Map<String, String> messages) |
Any | Registers localized key/pattern pairs for this plugin (plugin-ID scoped). languageCode accepts tags like "en", "de", "de_DE", "de-AT". |
addTranslations(String languageCode, Properties messages) |
Any | Convenience overload accepting java.util.Properties. |
addTranslationBundle(String languageCode, String resourcePath, ClassLoader loader) |
Any | Loads a UTF-8 .properties file from the plugin JAR classpath (e.g. "/com/example/i18n/messages_de.properties") and registers it for languageCode. |
onStop(Runnable action) |
Swing EDT | Runs cleanup code when the plugin stops, is disabled, reloaded, or fails mid-start. Can be called multiple times. Works identically in Java and Groovy. |
ExtensionContext Actions, Helpers, and i18n¶
| Method | Returns | What It Does |
|---|---|---|
openTab(String title, JComponent content) |
void |
Opens (or focuses) a custom tab in the main OpenYaBS window (automatically marshaled to the Swing EDT). |
notify(String message) |
void |
Displays a short status bar message and logs it in the activity list. |
notify(String message, DatabaseObject about) |
void |
Shows a notification pop-up linked to a specific record (clicking opens the record). |
popup(String message) |
void |
Shows a notification pop-up (and logs it in the activity list). |
error(String message) |
void |
Shows an error/warning notification pop-up. |
select(String sql) |
Object[][] |
Runs a plain SQL SELECT on the YaBS database. Returns Object[][] (never null; empty array on no rows or error — errors are swallowed). |
execute(String sql) |
void |
Runs a plain SQL statement (CREATE TABLE, INSERT, UPDATE, …). Note: For user input, transactions, or strict error handling, use JDBC PreparedStatement (see Example 13). |
ui(Runnable r) |
void |
Executes r immediately if already on the Swing EDT, otherwise via SwingUtilities.invokeLater(r). |
<T> void background(Supplier<T> work, Consumer<T> then) |
void |
Runs work on a daemon thread (plugin-<id>) and passes the result to then on the Swing EDT (then may be null). Uncaught exceptions are logged and displayed via the host error handler. |
currentView() |
DataPanel |
Returns the DataPanel in the currently selected main-window tab, or null. |
refreshView(DatabaseObject record) |
void |
Re-populates record in every open main-window tab currently displaying that record (e.g. after locking or modifying metadata). |
openFile(File file) |
void |
Opens a file with its configured program (for PDFs, respects Settings › External programs). |
settings() |
PluginSettings |
Local key/value store saved on this machine in plugins/<safeId>.properties. |
dataFolder() |
File |
Private folder plugins/<safeId>/ for plugin files (automatically created via mkdirs()). |
yabsVersion() |
String |
Current OpenYaBS version string (e.g. "2.0.17" or "2.0-dev"). |
language() |
String |
Active OpenYaBS UI language tag normalized to ll or ll_CC (e.g. "de", "de_DE", "en"). |
tr(String key, Object... args) |
String |
Resolves a plugin-scoped translation key for the active user language and formats optional MessageFormat placeholders ({0}, {1}, …). Returns key if not found. |
trOrDefault(String key, String fallback, Object... args) |
String |
Same as tr, but uses fallback if key is not registered. |
Supporting API Interfaces and Types¶
PluginSettings (source)¶
String get(String key, String fallback)void set(String key, String value)— passnullto remove the keyboolean getBoolean(String key, boolean fallback)void setBoolean(String key, boolean value)
SearchResult (source)¶
- Constructor:
new SearchResult(String title, String detail, Runnable open) - Fields:
public final String title,public final String detail(gray subtitle, nevernull),public final Runnable open(invoked when the user presses Enter or clicks).
Activity.Entry & Activity.Kind (source)¶
Activity.Kind:MESSAGE,WARNING,FILE,CREATED,CHANGED,DELETED- Fields on
Activity.Entry: Date time— timestampKind kind— event typeString text— display text / filenameString detail— localized record type or file owner label (do not match on this for logic; usecontextinstead!)File file— exported file forKind.FILE, ornullContext context— record context (e.g.Context.getInvoice(),Context.getContact()), ornullint id— database ID (ids) of the record, or0boolean draft—truefor previews or intermediate PDFs (e.g. before ZUGFeRD embedding); always skipentry.draftwhen finalizing or archiving!- Helper methods:
hasRecord(),hasFile(),matches(String needle)
DataPanel (source)¶
Methods relevant to plugins inside onView:
- DatabaseObject getDataOwner() — the currently displayed record (Item, Contact, Product, Expense, Revenue, …; check owner != null && owner.__getIDS() > 0 for saved records)
- void setDataOwner(DatabaseObject object, boolean populateData) — reloads/shows a record
- void setPluginBadge(JComponent badge) — small status badge in the view header next to the record status
- void setPluginBanner(JComponent banner) — full-width banner below the toolbar (e.g. status summary + action buttons)
- void setContentLocked(boolean locked) / boolean isContentLocked() — disables content fields, line items, and deletion while keeping payment status, reminders, and export usable
- void setLockedDocument(File file) / File getLockedDocument() — marks a locked record's archived document on the view (addLockedDocumentProvider is preferred because it works even before a view is refreshed)
- boolean hasUnsavedChanges() — whether the user has unsaved edits in the view
OpenYaBS automatically clears
pluginBadge,pluginBanner, andcontentLockedwhenever a view is re-populated or a plugin with anonViewlistener stops, then re-runs all remaining activeonViewlisteners.
DatabaseObjectModifier (source)¶
DatabaseObject modifyOnExplode(DatabaseObject object)— called when a record is constructed/loadedDatabaseObject modifyOnSave(DatabaseObject object) throws ChangeNotApprovedException— called before saving; modify fields or thrownew ChangeNotApprovedException(object)to cancel the saveDatabaseObject executeAfterCreate(DatabaseObject object)— called after a new record is insertedDatabaseObject executeAfterSave(DatabaseObject object)— called after any saveMap<String, Object> modifyOnResolve(Map<String, Object> map)— called during reference resolutionDatabaseObject modifyOnDelete(DatabaseObject object) throws ChangeNotApprovedException— called before deletion; thrownew ChangeNotApprovedException(object)to block deletion
JournalExport & JournalExportContext (JournalExport, JournalExportContext)¶
JournalExport:String title()— menu item label in the Journal Export menudefault String tooltip()— optional tooltip (nullby default)void export(JournalExportContext context)— runs on the Swing EDT when selecteddefault Map<String, byte[]> adviserPackageEntries(JournalExportContext context) throws Exception— runs on a background thread during tax-adviser ZIP generation; returnszipPath -> fileBytes(e.g."myexport/report.csv" -> bytes)JournalExportContextfields:List<JournalCalc.Entry> entries— loaded journal rows (obj,itemId,type,status,net,tax,gross,discount,open,date,number,contact,prename,street,city,country,group,account,description,rates,effect,counted,overpayment)JournalCalc.Totals totals— aggregated totalsDate from,Date to— selected reporting periodList<String> filters— active filter descriptionsMap<BigDecimal, String> rateLabels— VAT rate labelsComponent parent— parent Swing component for dialogs (may benullin headless/background runs!)Consumer<File> onExported/notifyExported(File file)— callcontext.notifyExported(file)so the Journal displays a clickable link to the exported file
PrivacyContributor (source)¶
default Date retentionUntil(Contact contact)— returns an additional statutory retention end date (e.g. 10 years for medical records), ornulldefault Map<String, String> exportData(Contact contact)— returns extrazipEntryName -> UTF-8 contentfiles (e.g."myplugin_data.json" -> json) included in the Art. 15/20 GDPR export ZIPdefault void onDeleteFinally(Contact contact)— called when a contact is permanently erased after all retention deadlines expire; delete plugin-owned rows forcontact.__getIDS()
LockedDocumentProvider (source)¶
File lockedDocument(DatabaseObject record)— return the archived originalFile(even if currently missing on disk) if locked, ornullif not locked by this providerdefault String duplicateRefused(DatabaseObject record)— if the archived file is missing, return a reason string to refuse creating a stamped duplicate, ornullto allowdefault List<String> duplicateWarnings(DatabaseObject record)— return differences between current DB data and the locked snapshot that the user must confirm before creating a duplicatedefault void duplicateCreated(DatabaseObject record, File missing, File duplicate)— called after a stamped duplicate PDF was created (e.g. to record an audit log entry)
Cookbook: Practical Examples (Groovy and Java)¶
1. Commands, Background Work, and Custom Tabs¶
Never block the Swing EDT with database queries, file I/O, or HTTP calls. Use ctx.background(work, then) to run slow work off-thread and update the UI safely afterward.
Java:
yabs.addCommand("Revenue Summary", "Opens a summary tab of this year's paid invoices", () -> {
yabs.background(() -> {
Object[][] rows = yabs.select(
"SELECT cnumber, cname, netvalue, taxvalue FROM items "
+ "WHERE inttype = 0 AND intstatus = " + mpv5.db.objects.Item.STATUS_PAID
+ " ORDER BY dateadded DESC");
return rows;
}, rows -> {
String[] cols = {"Number", "Title", "Net", "Tax"};
javax.swing.JTable table = new javax.swing.JTable(rows, cols);
table.setAutoCreateRowSorter(true);
yabs.openTab("Paid Invoices (" + rows.length + ")", new javax.swing.JScrollPane(table));
});
});
Groovy:
yabs.addCommand('Revenue Summary', 'Opens a summary tab of paid invoices', {
yabs.background({
yabs.select("SELECT cnumber, cname, netvalue, taxvalue FROM items WHERE inttype = 0 AND intstatus = ${mpv5.db.objects.Item.STATUS_PAID} ORDER BY dateadded DESC")
}, { rows ->
def table = new javax.swing.JTable(rows, ['Number', 'Title', 'Net', 'Tax'] as Object[])
table.autoCreateRowSorter = true
yabs.openTab("Paid Invoices (${rows.length})", new javax.swing.JScrollPane(table))
})
})
2. Settings Pages: Per-Machine vs. Per-Database Config¶
OpenYaBS gives plugins two configuration mechanisms — pick the right one for your data:
| Storage | API | Scope | Best For |
|---|---|---|---|
| Local plugin settings | ctx.settings().get/set |
Saved in plugins/<safeId>.properties on this machine only |
Local paths (archive folder), local ports, window prefs |
| Database global settings | mpv5.globals.GlobalSettings.getProperty/setProperty + GlobalSettings.save() |
Stored in the OpenYaBS database (shared across all users/PCs) | Business rules, hourly rates, tax flags, account mappings |
Tip: Always prefix
GlobalSettingskeys with a unique namespace for your plugin (e.g."myplugin.defaultRate").
Java (settings page using ctx.settings()):
yabs.addSettingsPage("My Plugin", "Configure webhook URL and auto-sync", () -> {
javax.swing.JPanel panel = new javax.swing.JPanel(new java.awt.GridBagLayout());
panel.setBorder(javax.swing.BorderFactory.createEmptyBorder(12, 12, 12, 12));
java.awt.GridBagConstraints g = new java.awt.GridBagConstraints();
g.insets = new java.awt.Insets(4, 6, 4, 6);
g.anchor = java.awt.GridBagConstraints.WEST;
javax.swing.JTextField urlField = new javax.swing.JTextField(yabs.settings().get("webhook.url", ""), 30);
javax.swing.JCheckBox enabledBox = new javax.swing.JCheckBox("Enable notifications",
yabs.settings().getBoolean("webhook.enabled", false));
javax.swing.JButton saveBtn = new javax.swing.JButton("Save");
saveBtn.addActionListener(e -> {
yabs.settings().set("webhook.url", urlField.getText().trim());
yabs.settings().setBoolean("webhook.enabled", enabledBox.isSelected());
yabs.notify("My Plugin settings saved.");
});
g.gridx = 0; g.gridy = 0; panel.add(new javax.swing.JLabel("Webhook URL:"), g);
g.gridx = 1; panel.add(urlField, g);
g.gridx = 1; g.gridy = 1; panel.add(enabledBox, g);
g.gridx = 1; g.gridy = 2; panel.add(saveBtn, g);
return panel;
});
3. Search Anything Provider¶
Search providers run on a background thread on every keystroke in Search anything (Shift Shift). Return quickly, require a minimum query length (e.g. >= 2 chars), and cap result counts.
yabs.addSearchProvider(query -> {
if (query == null || query.trim().length() < 2) {
return java.util.Collections.emptyList();
}
String needle = query.trim().toLowerCase(java.util.Locale.ROOT);
java.util.List<mpv5.plugin.api.SearchResult> out = new java.util.ArrayList<>();
for (Vehicle v : loadMatchingVehicles(needle, 10)) {
out.add(new mpv5.plugin.api.SearchResult(
v.licensePlate + " — " + v.makeModel,
"Customer #" + v.contactId + " · Click to open",
() -> openVehicleDialog(v)));
}
return out;
});
4. Reacting to Records and Exported Files (onActivity)¶
Always check entry.context (locale-independent) rather than entry.detail (localized text), and always check !entry.draft before treating an exported PDF/ODT/XML as a finalized document!
yabs.onActivity(entry -> {
// 1. React to newly created invoices
if (entry.kind == mpv5.handler.Activity.Kind.CREATED
&& mpv5.db.common.Context.getInvoice().equals(entry.context)) {
yabs.notify("Created invoice #" + entry.id + ": " + entry.text);
}
// 2. React to issued (non-draft) exported files
if (entry.kind == mpv5.handler.Activity.Kind.FILE
&& !entry.draft
&& entry.hasFile()
&& mpv5.db.common.Context.getInvoice().equals(entry.context)) {
// entry.file is the exported PDF, ODT, or ZUGFeRD/XRechnung file
// Offload heavy I/O or network upload to background():
java.io.File exported = entry.file;
int invoiceId = entry.id;
yabs.background(() -> archiveCopy(invoiceId, exported),
ok -> yabs.notify("Archived " + exported.getName()));
}
});
5. Validating and Vetoing Saves or Deletes (addRecordModifier)¶
Throw new ChangeNotApprovedException(object) from modifyOnSave or modifyOnDelete to cancel the operation cleanly.
Java:
import java.util.Map;
import javax.swing.JOptionPane;
import mpv5.db.common.DatabaseObject;
import mpv5.db.common.DatabaseObjectModifier;
import mpv5.db.objects.Item;
import mpv5.globals.Constants;
import mpv5.ui.panels.ChangeNotApprovedException;
yabs.addRecordModifier(new DatabaseObjectModifier() {
@Override
public DatabaseObject modifyOnSave(DatabaseObject object) throws ChangeNotApprovedException {
if (object instanceof Item) {
Item item = (Item) object;
if (item.__getInttype() == Constants.TYPE_INVOICE
&& (item.__getDescription() == null || item.__getDescription().trim().isEmpty())) {
int choice = JOptionPane.showConfirmDialog(
null,
"This invoice has no description. Save anyway?",
"Invoice Check",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (choice != JOptionPane.YES_OPTION) {
throw new ChangeNotApprovedException(item);
}
}
}
return object;
}
@Override
public DatabaseObject modifyOnDelete(DatabaseObject object) throws ChangeNotApprovedException {
// Return object to allow, or throw new ChangeNotApprovedException(object) to block
return object;
}
@Override public DatabaseObject modifyOnExplode(DatabaseObject object) { return object; }
@Override public DatabaseObject executeAfterCreate(DatabaseObject object) { return object; }
@Override public DatabaseObject executeAfterSave(DatabaseObject object) { return object; }
@Override public Map<String, Object> modifyOnResolve(Map<String, Object> map) { return map; }
});
Groovy (map coercion):
import mpv5.db.common.DatabaseObjectModifier
import mpv5.db.objects.Contact
import mpv5.ui.panels.ChangeNotApprovedException
yabs.addRecordModifier([
modifyOnSave: { obj ->
if (obj instanceof Contact && obj.__getCname()?.trim()?.isEmpty()) {
yabs.error('Contact name must not be empty.')
throw new ChangeNotApprovedException(obj)
}
obj
},
modifyOnDelete : { o -> o },
modifyOnExplode : { o -> o },
executeAfterCreate: { o -> o },
executeAfterSave : { o -> o },
modifyOnResolve : { m -> m }
] as DatabaseObjectModifier)
6. Decorating and Locking Record Views (onView)¶
Add a header badge, an interactive banner with buttons, or lock content fields on any DataPanel (Invoices, Contacts, Products, Expenses, Revenues…).
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import mpv5.db.common.DatabaseObject;
import mpv5.db.objects.Item;
yabs.onView(view -> {
DatabaseObject owner = view.getDataOwner();
if (!(owner instanceof Item) || owner.__getIDS() <= 0) {
return;
}
Item invoice = (Item) owner;
// 1. Header badge next to status
if (invoice.__getIntstatus() == Item.STATUS_PAID) {
JLabel badge = new JLabel(" PAID ");
badge.setOpaque(true);
badge.setBackground(new Color(220, 252, 231));
badge.setForeground(new Color(22, 101, 52));
view.setPluginBadge(badge);
}
// 2. Banner with action button below toolbar
JPanel banner = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 4));
banner.setBackground(new Color(239, 246, 255));
banner.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(147, 197, 253)));
banner.add(new JLabel("Custom metadata for " + invoice.__getCnumber()));
JButton editBtn = new JButton("Edit details…");
editBtn.addActionListener(e -> {
// After modifying plugin data, refresh all open views of this record:
yabs.refreshView(invoice);
});
banner.add(editBtn);
view.setPluginBanner(banner);
// 3. Optionally lock content fields & deletion (payment status & export remain enabled)
// view.setContentLocked(true);
});
7. Custom Template Placeholders (addTemplateFields)¶
Expose custom fields from your plugin to any LibreOffice .odt or .fodt template!
- Every entry
"myplugin.fieldName" -> valuein the returned map becomes usable as[myplugin.fieldName]in templates. - Always namespace keys with a short plugin prefix (
myplugin.*) so they never collide with built-in fields (item.*,contact.*,companyinfo.*,template.*). - Return
""(empty string) rather thannullfor missing optional fields so placeholders don't remain literal[myplugin.foo]text in exported PDFs.
yabs.addTemplateFields(obj -> {
java.util.Map<String, Object> fields = new java.util.LinkedHashMap<>();
if (obj instanceof mpv5.db.objects.Item) {
mpv5.db.objects.Item item = (mpv5.db.objects.Item) obj;
fields.put("myplugin.projectCode", loadProjectCode(item.__getIDS())); // "" if none
fields.put("myplugin.contactRef", "C-" + item.__getContactsids());
}
return fields;
});
Bundling & exporting starter .fodt templates (Java): Place .fodt files under src/main/resources/com/example/myplugin/templates/ and offer a command that saves them via MyPlugin.class.getResourceAsStream(...) and mpv5.ui.dialogs.DialogForFile (see WorkshopPlugin.java for a full example).
8. Journal Export and Tax-Adviser ZIP (addJournalExport)¶
Contribute both an interactive export format in the Journal's Export menu and automatic files inside the tax-adviser ZIP package:
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collections;
import java.util.Map;
import mpv5.handler.JournalCalc;
import mpv5.plugin.api.JournalExport;
import mpv5.plugin.api.JournalExportContext;
import mpv5.ui.dialogs.DialogForFile;
yabs.addJournalExport(new JournalExport() {
@Override
public String title() {
return "Custom Accounting CSV";
}
@Override
public String tooltip() {
return "Exports counted journal entries as semicolon-separated UTF-8 CSV.";
}
@Override
public void export(JournalExportContext ctx) {
DialogForFile chooser = new DialogForFile(DialogForFile.FILES_ONLY, "custom-journal.csv");
if (!chooser.saveFile()) {
return;
}
try {
File target = chooser.getFile();
Files.write(target.toPath(), renderCsv(ctx).getBytes(StandardCharsets.UTF_8));
ctx.notifyExported(target); // shows clickable file link in Journal
yabs.notify("Exported " + target.getName());
} catch (Exception e) {
yabs.error("Export failed: " + e.getMessage());
}
}
@Override
public Map<String, byte[]> adviserPackageEntries(JournalExportContext ctx) {
byte[] bytes = renderCsv(ctx).getBytes(StandardCharsets.UTF_8);
return Collections.singletonMap("custom/journal.csv", bytes);
}
private String renderCsv(JournalExportContext ctx) {
StringBuilder sb = new StringBuilder("Date;Number;Contact;Net;Tax;Gross\n");
for (JournalCalc.Entry e : ctx.entries) {
if (!e.counted) {
continue;
}
sb.append(e.date).append(';')
.append(e.number).append(';')
.append(e.contact).append(';')
.append(e.net).append(';')
.append(e.tax).append(';')
.append(e.gross).append('\n');
}
return sb.toString();
}
});
9. Pre-Send E-Mail Warnings and E-Invoice Skip Rules¶
Useful for privacy-sensitive documents (e.g. medical diagnoses under Art. 9 GDPR) or VAT-exempt invoices where e-invoicing does not apply:
// 1. Warn before e-mailing a document (interactive: YES/NO dialog; batch: logged & skipped)
yabs.addMailWarningProvider(obj -> {
if (obj instanceof mpv5.db.objects.Item) {
mpv5.db.objects.Item item = (mpv5.db.objects.Item) obj;
if (containsConfidentialNotes(item.__getIDS())) {
return "This invoice contains confidential notes. Send via unencrypted e-mail anyway?";
}
}
return null; // no warning
});
// 2. Skip ZUGFeRD / XRechnung generation and fall back to plain PDF
yabs.addEInvoiceSkipRule(item -> isExemptFromEInvoice(item.__getIDS()));
10. GDPR Retention, Export, and Final Deletion (addPrivacyContributor)¶
If your plugin stores personal data linked to a Contact, register a PrivacyContributor so OpenYaBS's GDPR tools (Data protection / GDPR) automatically enforce your retention period, include your data in Art. 15/20 exports, and erase your rows on final deletion:
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import mpv5.db.objects.Contact;
import mpv5.plugin.api.PrivacyContributor;
yabs.addPrivacyContributor(new PrivacyContributor() {
@Override
public Date retentionUntil(Contact contact) {
// Return a Date if your plugin requires keeping this contact longer, else null
return loadRetentionEndDate(contact.__getIDS());
}
@Override
public Map<String, String> exportData(Contact contact) {
String json = exportPluginRecordsAsJson(contact.__getIDS());
if (json == null) {
return Collections.emptyMap();
}
return Collections.singletonMap("myplugin_contact_data.json", json);
}
@Override
public void onDeleteFinally(Contact contact) {
deletePluginRecordsForContact(contact.__getIDS());
}
});
11. Archived Originals for Locked Records (addLockedDocumentProvider)¶
When a plugin finalizes/locks a record with an archived PDF or e-invoice, register a LockedDocumentProvider. Whenever the user clicks Print, PDF, Preview, ODT, or E-invoice, OpenYaBS asks all providers and opens the archived original instead of regenerating the file — even if the view was not refreshed yet. If the archived file is missing on disk, OpenYaBS offers a stamped duplicate controlled by the provider:
import java.io.File;
import java.util.List;
import mpv5.db.common.DatabaseObject;
import mpv5.plugin.api.LockedDocumentProvider;
yabs.addLockedDocumentProvider(new LockedDocumentProvider() {
@Override
public File lockedDocument(DatabaseObject record) {
return findArchivedFileOrNull(record); // return File even if !file.exists()
}
@Override
public String duplicateRefused(DatabaseObject record) {
return hasTamperedData(record) ? "Record data no longer matches locked hash." : null;
}
@Override
public List<String> duplicateWarnings(DatabaseObject record) {
return findCustomerAddressDifferences(record); // user must confirm before duplicate
}
@Override
public void duplicateCreated(DatabaseObject record, File missing, File duplicate) {
logDuplicateAuditEntry(record, missing, duplicate);
}
});
12. Multi-Language Plugins and i18n (addTranslationBundle, tr)¶
OpenYaBS provides a built-in, plugin-ID-scoped translation system with java.text.MessageFormat support ({0}, {1}, …) and automatic cleanup on stop.
Fallback chain: exact locale (de_AT) → base language (de, automatically normalizing OpenYaBS names like DE-Yabs-2.0) → en → fallback (for trOrDefault) → key.
Java (UTF-8 .properties bundles in JAR resources):
src/main/resources/com/example/myplugin/i18n/messages_en.properties:
plugin.name=My Plugin
cmd.hello.title=Say hello
cmd.hello.msg=Hello {0}, running on OpenYaBS {1}!
src/main/resources/com/example/myplugin/i18n/messages_de.properties:
plugin.name=Mein Plugin
cmd.hello.title=Hallo sagen
cmd.hello.msg=Hallo {0}, OpenYaBS {1} läuft!
Register in start(ExtensionContext yabs):
ClassLoader cl = MyPlugin.class.getClassLoader();
yabs.addTranslationBundle("en", "/com/example/myplugin/i18n/messages_en.properties", cl);
yabs.addTranslationBundle("de", "/com/example/myplugin/i18n/messages_de.properties", cl);
String msg = yabs.tr("cmd.hello.msg", "Alice", yabs.yabsVersion());
String activeLang = yabs.language(); // e.g. "de", "de_DE", "en"
Groovy (inline maps):
yabs.addTranslations('en', [greet: 'Hello {0}!', title: 'My Tool'])
yabs.addTranslations('de', [greet: 'Hallo {0}!', title: 'Mein Werkzeug'])
yabs.addCommand(yabs.tr('title'), '', {
yabs.notify(yabs.tr('greet', 'World'))
})
13. Custom Database Tables and Cross-Database JDBC¶
OpenYaBS supports H2 (default, in Derby compatibility mode), Apache Derby, MySQL / MariaDB, and PostgreSQL.
ctx.select(sql)andctx.execute(sql)are convenient for quick queries, but they take plain SQL strings and swallow SQL errors.- For production plugins that create their own tables or accept user input, use JDBC
PreparedStatementon OpenYaBS's database connection and always guard withhasDatabase()(so your plugin doesn't fail during headless tests or before DB login):
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import mpv5.db.common.DatabaseConnection;
public static boolean hasDatabase() {
try {
return DatabaseConnection.getConnector() != null
&& DatabaseConnection.getConnector().getConnection() != null;
} catch (Throwable t) {
return false;
}
}
public static Connection connection() throws SQLException {
DatabaseConnection dc = DatabaseConnection.getConnector();
Connection c = dc == null ? null : dc.getConnection();
if (c == null) {
throw new SQLException("No active OpenYaBS database connection");
}
return c;
}
public static void initSchema(Connection conn) throws SQLException {
// Prefix table names with your plugin short name!
// Use portable SQL types: INT, BIGINT, VARCHAR(...), CLOB/TEXT, TIMESTAMP.
try (Statement st = conn.createStatement()) {
st.execute("CREATE TABLE IF NOT EXISTS myp_notes ("
+ "item_id INT PRIMARY KEY, "
+ "note VARCHAR(2000) NOT NULL, "
+ "updated_at VARCHAR(32) NOT NULL)");
} catch (SQLException e) {
// Apache Derby < 10.15 lacks IF NOT EXISTS (SQLState X0Y32 = table already exists)
if (!"X0Y32".equalsIgnoreCase(e.getSQLState())) {
throw e;
}
}
}
Cross-database SQL tips:
- Prefix all custom tables with a unique plugin prefix (e.g. ws_, hp_, verein_, gobd_).
- Never concatenate user input into SQL — always use ? placeholders in PreparedStatement.
- Do not close OpenYaBS's shared Connection! Only close your Statement, PreparedStatement, and ResultSet (via try-with-resources).
- Avoid DB-specific UPSERT syntax (ON CONFLICT, MERGE, ON DUPLICATE KEY); a portable pattern is UPDATE ... WHERE id = ? and if executeUpdate() == 0, run INSERT INTO ....
- Store ISO dates as VARCHAR(10) (YYYY-MM-DD) if you want identical behavior across H2, Derby, MySQL, and PostgreSQL without timezone surprises.
14. Working with OpenYaBS Domain Objects (DatabaseObject, Context)¶
Common OpenYaBS classes you will frequently use in plugins:
| Task | Code |
|---|---|
| Fetch one record by ID | Item inv = (Item) DatabaseObject.getObject(Context.getInvoice(), itemId); |
| Fetch all records of a type | ArrayList<DatabaseObject> list = DatabaseObject.getObjects(Context.getContact()); |
| Create & save a new record | Product p = new Product(); p.setInttype(Product.TYPE_SERVICE); p.setCnumber("SVC-1"); p.setCname("Consulting"); p.setExternalnetvalue(new BigDecimal("100.00")); p.save(true); |
| Read invoice line items | SubItem[] lines = item.getSubitems(); |
| Read invoice totals | item.getGrossAmount(), item.getNetAfterDiscount(), item.__getNetvalue(), item.__getTaxvalue() |
| Current logged-in user | User u = User.getCurrentUser(); |
| Open a record in a tab | mpv5.YabsViewProxy.instance().getIdentifierView().addTab(record); |
Common Context factories (mpv5.db.common.Context):
getInvoice(), getOrder(), getOffer(), getDelivery(), getConfirmation(), getCredit(), getPartPayment(), getDeposit(), getContact(), getCustomer(), getSupplier(), getProduct(), getProductGroup(), getSubItem(), getExpense(), getRevenue(), getTaxes(), getAccounts(), getGroup(), getUser(), getTemplate(), getSchedule(), getConversation().
Common document type constants (mpv5.globals.Constants):
TYPE_INVOICE (0), TYPE_ORDER (1), TYPE_OFFER (2), TYPE_DELIVERY_NOTE (3), TYPE_ORDER_CONFIRMATION (4), TYPE_CREDIT (20), TYPE_PART_PAYMENT (21), TYPE_DEPOSIT (22), TYPE_EXPENSE (18), TYPE_REVENUE (19), TYPE_PAYMENT (23), TYPE_CANCELLATION (24).
Common Item status constants (mpv5.db.objects.Item):
STATUS_QUEUED, STATUS_IN_PROGRESS, STATUS_PAUSED, STATUS_FINISHED, STATUS_PAID, STATUS_CANCELLED.
Threading, Bundled Libraries, and Best Practices¶
Threading Summary¶
| Callback / Method | Thread | Rule |
|---|---|---|
YabsExtension.start, stop, onStop |
Swing EDT | Keep fast; offload heavy startup queries to ctx.background(...). |
addCommand action |
Swing EDT | Keep fast; use ctx.background(...) for DB/file/network work. |
addSettingsPage supplier |
Swing EDT | Safe to create Swing components directly. |
onActivity, onView |
Swing EDT | Safe to update DataPanel badges/banners; avoid slow queries. |
addSearchProvider |
Background thread | Must be thread-safe and fast; do not touch Swing components directly (its SearchResult.open runs on EDT when selected). |
JournalExport.export |
Swing EDT | Safe to open dialogs; use background(...) for heavy exports. |
JournalExport.adviserPackageEntries |
Background thread | Must NOT show modal Swing dialogs (ctx.parent may be null). |
background(work, then) |
work: Daemon threadthen: Swing EDT |
Standard way to perform slow work and display results. |
Libraries Already Bundled in OpenYaBS (lib/ & Runtime)¶
Plugins automatically inherit OpenYaBS's classpath (parent classloader). Notable libraries already available at runtime (use compileOnly in Java, or import directly in Groovy):
- Java 21 standard library (
java.net.http.HttpClient,java.time.*,javax.crypto.*, etc.) - Apache Groovy 4.0.24 (excluding Apache Ivy /
@Grab) - Jackson 2.22 (
com.fasterxml.jackson.databind.ObjectMapper— JSON reading/writing) - Apache PDFBox 3.0.8 (PDF inspection, creation, stamping)
- Apache Commons IO 2.17, Commons Lang, Commons Codec
- FlatLaf 3.5.4 (modern Swing Look & Feel)
- ODFDOM / XDocReport (ODT document handling)
- Mustangproject (ZUGFeRD / XRechnung e-invoice libraries)
- H2 2.3, Derby, PostgreSQL, MySQL JDBC drivers
UI Styling Helpers¶
To make your settings pages and tabs match OpenYaBS's look and feel (including Dark Mode and HiDPI scaling), you can optionally reuse OpenYaBS's Swing helpers:
- mpv5.ui.modern.ModernTheme (px(int) for HiDPI scaling, font(delta, style), accent(), muted(), roomy(JTextField))
- mpv5.ui.modern.Card, mpv5.ui.modern.Applets, mpv5.ui.modern.PrimaryButton (see CashRegister.java)
- mpv5.ui.dialogs.DialogForFile (file/directory save & open dialogs)
Testing and Debugging Plugins¶
Headless JUnit 5 Unit Tests (No GUI Needed!)¶
ExtensionManager can be instantiated directly in unit tests with a temporary folder and a minimal stub Host — making it fast and reliable to test registration, commands, search providers, i18n, template fields, stop cleanup, and JAR packaging:
import static org.junit.jupiter.api.Assertions.*;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import mpv5.plugin.ExtensionManager;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class HelloPluginTest {
@TempDir
Path tempDir;
static final class StubHost implements ExtensionManager.Host {
final List<String> messages = new ArrayList<>();
final List<String> errors = new ArrayList<>();
@Override public void openTab(String title, JComponent content) {}
@Override public void notify(String message) { messages.add(message); }
@Override public void ui(Runnable r) { r.run(); }
@Override public void changed() {}
@Override public void error(String plugin, Throwable t) { errors.add(plugin + ": " + t); }
}
@Test
void startsRegistersCommandTranslatesAndCleansUpOnStop() {
StubHost host = new StubHost();
ExtensionManager mgr = new ExtensionManager(tempDir.toFile(), host);
ExtensionManager.Installed inst = mgr.register(new HelloPlugin());
assertTrue(mgr.start(inst));
assertEquals(ExtensionManager.State.RUNNING, inst.getState());
assertEquals(1, mgr.commands().size());
assertTrue(host.errors.isEmpty());
// Test localized output across locales
assertEquals("Hallo sagen", mgr.translateForLocale(HelloPlugin.ID, "de_DE", "cmd.greet.title", null));
assertEquals("Say hello", mgr.translateForLocale(HelloPlugin.ID, "en", "cmd.greet.title", null));
// Execute command
mgr.commands().get(0).action.run();
assertFalse(host.messages.isEmpty());
// Stop removes all contributions
mgr.stop(inst);
assertEquals(0, mgr.contributions(HelloPlugin.ID));
assertTrue(mgr.commands().isEmpty());
}
}
For custom SQL tables, test your Store class directly against an in-memory H2 database:
try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:plugintest;MODE=Derby;DB_CLOSE_DELAY=-1")) {
MyPluginStore.initSchema(conn);
// insert, query, update, assert...
}
Debugging Tips¶
- Groovy Console (Settings › GroovyConsole): Great interactive scratchpad to inspect live
DatabaseObjects, testContextqueries, or try Swing components against your running database. - Built-in Plugin Editor (
F5): Catches Groovy syntax errors and jumps directly to the line number. - Plugin Manager error column: If a plugin enters
FAILED, its exception class and message are shown directly in Settings › Plugins. - Logging: Call
mpv5.logging.Log.Debug(MyPlugin.class, "details or exception")to write to OpenYaBS's log file.
Developing Plugins with AI Coding Agents¶
OpenYaBS's plugin system is designed to work smoothly with AI coding agents (Claude Code, Codex, Cursor, Antigravity, GitHub Copilot, etc.): the entire public API is a small set of clean interfaces in mpv5.plugin.api, plugins can be verified headlessly with ExtensionManager and in-memory H2, and five full-featured official Java plugins live right inside the OpenYaBS repository as reference examples.
Starter Prompt: Groovy Plugin (Fast Automation)¶
Copy, customize the Goal section, and paste into your AI agent:
Write a single-file OpenYaBS Groovy plugin (.groovy) following the OpenYaBS Plugin Developer Guide:
https://github.com/anti43/openyabs/wiki/Writing-plugins-(EN)
Goal:
<Describe what your plugin should do, e.g. "Add a command that exports all unpaid invoices older than 30 days to a CSV file, and show a red badge on overdue invoices when opened.">
Requirements:
- Include header metadata comments at the very top: // @id, // @name, // @description, // @version, // @author, // @minYabsVersion 2.0.10.
- Use the bound `yabs` (mpv5.plugin.api.ExtensionContext) variable.
- Do NOT use @Grab (Ivy is not bundled). Only use JDK 21, Groovy 4, and OpenYaBS classes.
- Match record types via mpv5.db.common.Context (e.g. Context.getInvoice()) and mpv5.globals.Constants.TYPE_*, never on localized strings like "Rechnung".
- In onActivity, check !entry.draft before reacting to FILE events.
- Offload slow DB/file/network work to yabs.background({ ... }, { ... }) so the Swing EDT stays responsive.
- Provide clean error handling and register any cleanup in onStop = { ... }.
Starter Prompt: Java Plugin (Full Module with Gradle & Tests)¶
Copy, customize the Goal section, and paste into your AI agent:
Create an OpenYaBS Java plugin project (Gradle, Java 21) following the OpenYaBS Plugin Developer Guide:
https://github.com/anti43/openyabs/wiki/Writing-plugins-(EN)
Reference official plugins in https://github.com/anti43/openyabs/tree/master/plugins (especially plugins/workshop and plugins/verein).
Goal:
<Describe your domain plugin: custom tables, UI banners/dialogs, settings page, commands, template placeholders, exports, validations, etc.>
Technical requirements:
1. Implement mpv5.plugin.api.YabsExtension (target Java 21, minYabsVersion "2.0.10") and register it in src/main/resources/META-INF/services/mpv5.plugin.api.YabsExtension.
2. Separate concerns cleanly: *Plugin (entry point), *Store (cross-DB JDBC with PreparedStatement & GlobalSettings), *Validator (pure testable logic + template fields), *Ui (Swing panels/dialogs).
3. Guard DB initialization with hasDatabase() so start(ctx) succeeds cleanly in headless tests and handles database switches.
4. Use OpenYaBS's plugin i18n API (addTranslationBundle + ctx.tr) with UTF-8 messages_en.properties and messages_de.properties (identical key sets).
5. Prefix custom DB tables and template placeholder keys (e.g. [myplugin.*]) with a unique plugin namespace. Return "" instead of null for empty template fields.
6. Never close OpenYaBS's shared JDBC Connection; only close Statement/PreparedStatement/ResultSet.
7. Write JUnit 5 tests covering: ServiceLoader discovery, translation bundle key parity, pure validator/template logic, SQL store against in-memory H2 (jdbc:h2:mem:...;MODE=Derby), and headless ExtensionManager start/stop lifecycle.
8. Verify with `./gradlew test jar` and confirm META-INF/services/mpv5.plugin.api.YabsExtension is inside the built JAR.
AI Agent Pitfalls Checklist¶
When reviewing or prompting AI-generated plugins, watch out for these common mistakes:
- Wrong plugin API package: Use
mpv5.plugin.api.YabsExtension+ExtensionContext, never the deprecatedmpv5.pluginhandling.YabsPlugin/plugin.Main. - Missing
ServiceLoaderfile: Java JARs must containMETA-INF/services/mpv5.plugin.api.YabsExtension(exact filename!) with the fully qualified class name. - Header comments placed after
importin Groovy: Groovy@name/@idtags are only parsed at the very top of the file before the first code/import line. - Using
@Grabin Groovy: Apache Ivy is excluded from OpenYaBS;@Grabwill fail. Use Java + Gradle if you need extra libraries. - Matching localized strings in
onActivity: CheckContext.getInvoice().equals(entry.context)instead ofentry.detail == "Rechnung"(breaks in other UI languages). - Ignoring
entry.draft: Previews and intermediate PDFs emitActivity.Kind.FILEwithentry.draft == true. Always skip drafts for archiving/finalization. - Blocking the Swing EDT: Put slow DB queries, file exports, or HTTP requests inside
ctx.background(work, then). - Not guarding
hasDatabase()instart(ctx): Headless tests and pre-login/DB-switch lifecycles may callstart(ctx)when no DB connection is active. - Closing the shared JDBC
Connection: Never putDatabaseConnection.getConnector().getConnection()in atry (...)block! Closing it breaks OpenYaBS's database session. - Wrong settings scope:
ctx.settings()is local to one computer (plugins/<id>.properties); useGlobalSettingsfor business configuration shared across a multi-user database. - Forgetting
ChangeNotApprovedExceptionconstructor argument: Usethrow new ChangeNotApprovedException(object)(it takes theDatabaseObject, not aStringmessage — show a message viaJOptionPaneorctx.error(...)first). - Leaving unreplaced
[myplugin.key]placeholders: Always populate every documented template key with""when empty instead of omitting it or returningnull.
Official Plugins as Reference Implementations¶
When building a plugin (yourself or with an AI agent), study the official open-source plugins in the OpenYaBS repository — each demonstrates clean patterns for different parts of the API:
| Plugin | Source | Best Reference For |
|---|---|---|
| Car Repair Shop (Kfz-Werkstatt) | plugins/workshop |
Bilingual DE/EN i18n bundles (addTranslationBundle / tr), custom JDBC tables (WorkshopStore), onView banners + dialogs, addTemplateFields + bundled .fodt templates, modifyOnSave warnings, JUnit 5 tests |
| Association (Verein e.V.) | plugins/verein |
Batch invoice creation (Item.save(true)), SEPA XML batch generation, custom overview tab, bilingual i18n, starter product import |
| DATEV Export | plugins/datev |
addJournalExport (interactive CSV + adviserPackageEntries in tax-adviser ZIP), JournalLoader.loadAllResult, validation dialog |
| Heilpraktiker & GebüH | plugins/heilpraktiker |
addPrivacyContributor (GDPR retention, Art. 15/20 JSON export, final delete), addMailWarningProvider, addEInvoiceSkipRule, bundled JSON catalog, AES-256-GCM encryption using ctx.dataFolder() |
| GoBD Compliance | plugins/gobd |
addLockedDocumentProvider (archived originals + duplicates), onView content locking, onActivity file handling, addSearchProvider, JDBC transactions, multi-tab auditor UI, Groovy→Java ID migration |
| Activity Journal (built-in) | ActivityJournal.java |
Compact ~170-line example combining onActivity, addCommand, addSearchProvider, addSettingsPage, ctx.settings(), and ctx.dataFolder() |
| Cash Register (built-in) | CashRegister.java |
Embedded HTTP server lifecycle (start/stop), modern OpenYaBS UI cards (ModernTheme, Card, Applets, PrimaryButton) |
Classic Plugins (Legacy)¶
Plugins from older YaBS versions (a class plugin.Main implementing mpv5.pluginhandling.YabsPlugin, stored inside the database per user) remain supported for backward compatibility and appear at the bottom of Settings › Plugins under Classic plugins (database) (click Show). Do not use the classic API for new plugins — always implement mpv5.plugin.api.YabsExtension (Java) or write a .groovy plugin script.