Skip to content
Developer Guide

Developer Guide

Gradle and Maven

repositories {
    maven { url 'https://jitpack.io' }
}
dependencies {
    compileOnly 'com.github.Xyness:XCore:2.1'
}
<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>com.github.Xyness</groupId>
        <artifactId>XCore</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

XCore is already on the server at runtime: compileOnly or provided, never shaded. A plugin that uses what 2.1 adds (money(), the dashboard's fields and grid, positioned entries in PagedGui) should check the version in enable() and refuse to start on an older XCore, with a line that says why, as XShop does.

Plugin Structure

A plugin built on XCore is a Paper plugin, in plugins/, whose main class extends fr.xyness.XCore.Extension.XPlugin. It gets the whole XCore API under the same names as an addon, its own timings, and its own data folder, plugins/<name>/. The X plugins are built this way since 2.0.

paper-plugin.yml

name: MyPlugin
version: '1.0.0'
main: com.example.myplugin.MyPlugin
author: YourName
api-version: '1.21.1'
folia-supported: true
# Read by initUpdater(). The server ignores keys it does not know.
update-url: 'https://raw.githubusercontent.com/you/MyPlugin/refs/heads/main/version.yml'
dependencies:
  server:
    XCore:
      load: BEFORE
      required: true
      join-classpath: true
    # Optional, and the code uses its classes: join-classpath too
    PlaceholderAPI:
      load: BEFORE
      required: false
      join-classpath: true

join-classpath: true on XCore is what makes XPlugin, the API and XCore's libraries visible to the plugin. It does not carry over to XCore's own dependencies: a plugin whose code uses the classes of Vault or PlaceholderAPI declares them too. Write required: false out for an optional one, since an entry without it is required.

The main class

public class MyPlugin extends XPlugin {

    @Override
    protected boolean enable() {
        updateConfigWithDefaults();
        loadLanguage("en", "fr");
        registerListener(new MyListener(this));
        // Commands go through this plugin's own lifecycle manager, last
        getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS,
                event -> new MyCommands(this).register(event.registrar()));
        return true;
    }

    @Override
    protected void disable() { }

    @Override
    public void reload() {
        reloadConfig();
        loadLanguage("en", "fr");
    }
}
  • load(), enable(), disable() and reload() take the place of the server's onLoad, onEnable and onDisable, which are final. enable() returning false stops the plugin cleanly, with a line in the console. disable() only runs after an enable() that returned true. reload() is what /xcore reload and the dashboard's configuration editor call.
  • startFailed(reason) is called whenever the plugin does not start: XCore not running, enable() returning false or throwing. Returning true keeps the plugin enabled with only what it set up there; XLogin keeps its lockdown that way.
  • Its tasks, listeners and commands belong to it, and stop with it. What it handed XCore (web module, sync channels, UUID-change handlers, placeholders) is taken back when it is disabled.
  • XCore still lists it: /xcore addons, /xcore reload, /xcore diag, the dashboard and the addons.yml switches cover it as they cover addons.

Addons (XAddon)

XAddon is still supported, with the same API: an addon is a jar in plugins/XCore/addons/ with an addon.yml, loaded by XCore and run under XCore's plugin identity, and its files are in plugins/XCore/addons/<name>/.

addon.yml

name: MyAddon
version: '1.0.0'
author: 'YourName'
main: com.example.myaddon.MyAddonAddon
description: What this addon does
depend: []
soft-depend: []

A depend entry is met by an addon of that name, or by a plugin of that name installed in plugins/. The X plugins enable after every addon: an addon that depends on one finds its classes in its own onEnable(), but should only use it from ServerLoadEvent on, or check isEnabled() first.

Main Class

public class MyAddon extends XAddon {

    @Override
    public boolean onEnable() {
        saveDefaultConfig();
        // Register listeners, commands, tables...
        return true;
    }

    @Override
    public void onDisable() { }

    @Override
    public void onReload() { }
}

Available APIs

The same methods, under the same names, on XPlugin and on XAddon.

MethodDescription
api()XCore API (database, cache, sync, GUI, vault, web, UUID changes)
core()XCore plugin instance (sync manager, web panel, settings)
scheduler()Folia-compatible SchedulerAdapter. On a plugin, its tasks belong to the plugin and stop with it
logger()Logger scoped to the plugin
lang()The plugin's language namespace (MiniMessage)
LangNamespace.escape(String)Neutralise the MiniMessage tags in text a player wrote, before it is passed to a message
guiRegistry()GUI definition registry (loaded from YAML)
guiUtils()Item building, sounds, heads, click handling
delivery()Give an item or money to someone offline
money()Take and give money in an XCore currency or another plugin's Vault economy, with the currency's rounding (see Money). Since 2.1
leaderboards()Declare a ranking once, read it from memory
network()Which servers are up, and where a player is
ranks()Primary group and numbered permission levels (LuckPerms or Vault)
discord()The shared webhook sender
cooldowns()Per-player cooldowns for this plugin
placeholders()Publish placeholders without writing an expansion
onUuidChange(handler)Move this plugin's data when a returning player's UUID changed, before its login checks run
renamedKeys(file, renames)Keep the value an administrator gave a key that was renamed
registerListener(Listener)Bukkit listener, unregistered automatically on disable
getConfig()The plugin's config.yml, as it is on disk: no bundled defaults attached
updateConfigWithDefaults(protected...)Add the settings a new version introduces
isConfigReadable() / configProblem()Whether config.yml was read as it stands on disk, and where it stops being YAML when it was not. Worth telling whoever asked for a reload. Since 2.0.1
updateConfigFile(change)Write a few keys into config.yml as it is on disk now, and into the loaded configuration. Use it instead of getConfig().set(...) then saveConfig(), which writes the file as it was last read and undoes whatever was typed into it since. Since 2.0.1
setAsideIfUnreadable(File)For a file of your own that you are about to rewrite: copies it to <name>.unreadable-<millis> when it is not valid YAML, and reports it. config.yml, the language files and the dashboard strings no longer need it: since 2.0.1 a file that cannot be read is never written
loadLanguage(codes...)Extract the bundled translations and load the chosen one
getDataFolder()plugins/<name>/ (an addon's: plugins/XCore/addons/<name>/)

Two thread pools

api().getExecutor() is for logic, api().getDbExecutor() for anything that opens a connection. Never wait on a task belonging to the pool you are already running on: with a single pool, a thread ends up waiting for work queued behind itself.

A connection taken on a tick thread while the server runs is reported in the console, once per call site, with the class and the line to change.

UUID Changes

When XCore recognises a returning player under a new UUID (a server switched between offline and online mode, or put behind a proxy that changes it), it moves its own row during the player's pre-login, then calls every registered handler. The login waits for them, side by side and five seconds each at most, before the plugins' own login checks run, so those checks already find the data under the new UUID. The whole recognition is bounded: about 10 seconds to find and move the row, 2 more for a move already under way, then 5.5 for the handlers. When the time runs out before the move has begun, nothing is moved and the data follows at the next login.

onUuidChange((oldUuid, newUuid, name) -> CompletableFuture.runAsync(
        () -> moveMyRows(oldUuid, newUuid), api().getDbExecutor()));
  • The handler is called on XCore's work pool: return a future at once, and do the SQL on api().getDbExecutor().
  • Make the move one transaction, harmless to run twice. Nothing is retried. A handler that fails or runs out of time is reported in the console under the plugin's name, and the login goes on.
  • On a network sharing one database, it runs once, on the server where XCore moved the row: move every server's rows, then publish your usual sync message so the other servers drop what they cached.
  • Register it in enable(); it is taken back when the plugin is disabled. A plugin not built on XCore registers with api().uuidChanges().register(this, handler).

A PlayerUuidChangeEvent is fired afterwards, asynchronously, for code that only needs to know; nothing waits for it.

A handler is only called for a player XCore is sure of: the connection proves its identity with a version-4 UUID (online mode, a proxy forwarding Mojang UUIDs, XLogin's REAL mode) and it matches the Mojang UUID stored with the row, or the row carries exactly the same name, capitals included. A name in other capitals, two Mojang accounts, or several rows that could match: nothing is moved. The rules are in Configuration.

Pre-login listeners at LOWEST run before XCore. Never change a connection's UUID after that priority: XCore moves the data onto the UUID it sees at LOW.

Renamed Keys

A renamed key otherwise reads as one key to add and one to remove: the merge writes the new name with its default, the prune drops the old one, and the value the administrator chose is lost. Declare the renames first in enable(), before updateConfigWithDefaults, loadLanguage and pruneObsoleteKeys:

renamedKeys("config.yml", Map.of("anti-afk.enabled", "afk.enabled"));
renamedKeys("lang/*.yml", Map.of("lore-buyout", "lore-buyout-drop"));
updateConfigWithDefaults();
loadLanguage("en", "fr");

A value moves only when the new key is absent. Nested paths and whole sections move, a chain of renames is followed, and running it twice changes nothing, so keep the declarations from one version to the next. * in the last segment covers every language file, the administrator's own included. Each move is logged once. A key that moved to another file is not covered.

Versioned Sync

Every sync message carries the protocol version of its channel. A message of another version is not handed to the listener, and the console says once, per channel and server, which side is behind.

core().getSyncManager().registerChannel("myplugin", 1, message -> handle(message));

registerChannel(name, listener) still exists and means version 0, the version of every XCore 1.x message. Raise the number only when an older listener would misread the messages (an action renamed, a payload laid out differently): while a network is being updated, servers on different versions then stop hearing each other on that channel instead of acting on the wrong data.

Dashboard Pages

A web module describes its pages, and the browser builds them. There are four kinds:

PageBuilds
WebPageSpec.table(endpoint)Rows, with a search, filters, paging, row actions, a creation form and page-wide buttons
WebPageSpec.stats(endpoint)Statistic tiles, charts (each with a table view), short lists under them, and filters that read the page again
WebPageSpec.grid(endpoint)One container at a time as an inventory: rows of nine slots, an icon in each. Since 2.1
WebPageSpec.config()The config.yml editor, served by XCore for every module

Fields

Since 2.1 a field is a text box unless it says otherwise:

// A number, with its bounds and its step
WebPageSpec.field("price", "field-price", true).number().range(0, 1e9).step(0.01)
// A switch: it sends "true" or "false"
WebPageSpec.field("enabled", "field-enabled", false).toggle()
// A list, written out or read from an endpoint
WebPageSpec.field("period", "field-period", false)
    .select(WebPageSpec.option("daily", "value-daily"))
WebPageSpec.field("shop", "field-shop", false)
    .selectFrom("/api/myplugin/shops", "shops", "id", "label")
// The server's currencies; every item, searched by name, with its icon
WebPageSpec.field("currency", "field-currency", false).currency()
WebPageSpec.field("item", "field-item", true).item()
// Several lines, a value to start with, and a line of help under the field
WebPageSpec.field("commands", "field-commands", false).multiline()
    .value("")
    .helpKey("myplugin-help-commands")

An item field searches /api/items and sends the material in capitals; a currency field reads /api/currencies.

Actions and buttons

  • A form on a row. .fields(...) on an action opens a form instead of asking "are you sure?", each field filled in from the row: .from("row_field"), or the field of its own key. A form opened from a row or a button sends every field, the empty ones as "", so the endpoint can tell "emptied" from "not asked". The page's creation form keeps the old way and leaves empty fields out.
  • A chart. .chart(labelField, valueField) turns an action into "show me": the endpoint is read and its series drawn in a dialog. A chart only reads, like a download, so it is judged as reading the page is: without a permission of its own, it is not asked for xcore.dashboard.<module>.manage.
  • Only on some rows. .when("field", "value", ...) shows the button only on the rows it applies to.
  • Page buttons. .buttons(WebPageSpec.button(labelKey, endpoint)), as many as needed, each with its own .fields(...), .confirmKey(...) and .permission(...). .download() reads the endpoint with the page's search and filters, and saves what it answers as a file, named by its Content-Disposition. bulk(...) still works.
  • Filters. filterFrom(param, placeholderKey, endpoint, dataKey, valueField, labelField) fills a filter from an endpoint, on a stats page too, where the page is read again with the choice in its query.
  • Lists. list(titleKey, endpoint, dataKey, emptyKey) puts a short table under the charts of a stats page.

The grid

A grid page reads its endpoint with ?container=<id>&page=<n>, the first parameter's name set by containerParam, and draws the cells it answers:

{
  "containers": [{"id": "blocks", "label": "Blocks", "material": "BRICKS", "count": 42}],
  "container": "blocks",
  "rows": 6, "page": 1, "pages": 3,
  "slots": [{"slot": 10, "material": "STONE", "label": "4 $", "sub": "1 $"}],
  "locked": [45, 46, 47, 48, 49, 50, 51, 52, 53]
}

A cell is a row like a table's: material or itemDetails draws its icon, amount the count in its corner, label and sub two short lines under it, tone a colour (success, warning, danger), and every other field is listed in the panel a click opens, with the page's actions. .pickSlot() on an action asks the reader to click a destination, sent as to_page and to_slot. A click on an empty cell opens the page's form, which is sent the container, the page and the slot besides its fields; a locked cell opens neither the panel nor the form. containerActions(...) act on the container shown, their parameters read from its entry in containers. XShop's Shops page is one.

Dashboard Actions

Each thing a dashboard page lets the reader change names the permission the matching command asks for in game. The panel checks it on every request, and leaves out the buttons a reader could not use.

WebPageSpec.table("/api/myplugin/homes")
    .titleKey("myplugin-homes")
    .actions(WebPageSpec.action("delete", "/api/myplugin/delete")
        .idFrom("name")
        .send("name", "name")
        .permission("myplugin.delete", "myplugin.admin"))   // any one of them
    .form("create-home", "/api/myplugin/create",
        WebPageSpec.field("name", "name", true))
    .formPermission("myplugin.create");

bulkPermission does the same for the page-wide button, and .permission(...) on a WebPageSpec.button for each of the others. An action that names no permission needs xcore.dashboard.<module>.manage, and every page of the module needs xcore.dashboard.<module>: WebPanel.modulePermission(name) and WebPanel.managePermission(name) give those two nodes.

Reading

A page that shows what not every member of staff may see names the permission of the matching screen with readPermission(...). It covers every endpoint the page reads, its charts' included, and a reader without it does not get the page. A route no page describes, such as the /api/<module>/player/<name> routes the player profile reads from every module, is declared by the web module, * standing for one path segment:

@Override
public List<WebRoute> getRoutePermissions() {
    return List.of(WebRoute.of("/api/myplugin/player/*")
        .requires("myplugin.lookup")                  // each requires() is needed
        .requires(WebPanel.PLAYERS_PERMISSION));      // several nodes in one: any of them
}

A field only some may fill

Some changes need more than their action's permission: console commands written into a form run as the console later, so XShop takes them only from a reader with the trust a configuration save asks. sessionHolds(exchange, nodes...) on the web panel (2.1) says whether the player behind a request holds every one of these permissions, as the panel read them for the session:

if (!panel.sessionHolds(exchange, WebPanel.CONFIG_PERMISSION,
        WebPanel.CONFIG_SAVE_PERMISSION, "myplugin.admin")) {
    // refuse the change: answer 403, naming what is missing
    return;
}

Saving the configuration

Saving needs xcore.dashboard.config.save and what the module names for it, usually its reload command's permission: from getConfigSavePermission(), or with savePermission(...) on its configuration page (both are needed when both are set). A module that names none can only have its configuration saved by an operator: a configuration can make a plugin run console commands, so saving one is trusted like the console.

@Override
public List<String> getConfigSavePermission() {
    return List.of("myplugin.admin");   // what /myplugin reload asks for
}

Moving an Addon to XPlugin

  1. Extend XPlugin (fr.xyness.XCore.Extension) instead of XAddon.
  2. Rename onLoad() to load(), onEnable() to enable(), onDisable() to disable() and onReload() to reload(), which stays public. The server's methods are final, so a rename you forget is a compile error.
  3. Replace addon.yml with a paper-plugin.yml that keeps the same name (see Plugin Structure). Dependencies go under dependencies.server; there are no depend, soft-depend or commands keys.
  4. Register the commands through the plugin's own getLifecycleManager(). XCore's is closed by the time the plugin enables, and registering on it throws.
  5. Ship the jar for plugins/. On its first start, plugins/XCore/addons/<name>/ is moved to plugins/<name>/ before load() runs.

What behaves differently once it is a plugin:

  • Keep every NamespacedKey created with core() as it is. Those keys are in XCore's namespace, and the data already saved under them on items, entities and players must stay readable.
  • Schedule nothing from disable(). The server refuses tasks from a plugin being disabled: do that work synchronously.
  • The plugin is disabled before XCore at shutdown, so core().isEnabled() no longer means the server keeps running.
  • Read no file or setting in a constructor or a field initializer. Both run before the folder is moved, and getConfig() throws there.
  • Unregister hand-written PlaceholderAPI expansions in disable(). Placeholders published through placeholders() are withdrawn for you.

SchedulerAdapter (Folia)

Never use Bukkit.getScheduler(). Use scheduler() for Folia compatibility.

MethodUsage
runGlobalTask(Runnable)Sync main thread
runGlobalTaskTimer(Runnable, start, period)Repeating sync
runGlobalTaskLater(Runnable, delay)Delayed sync
runEntityTask(Player|Entity, Runnable)Entity region thread
runEntityTask(Player, Runnable task, Runnable retired)The same, and retired runs instead when the player left before the task could run, so what it was to hand over can be put back. Exactly one of the two runs
runEntityTaskLater(Player|Entity, Runnable, delay)Delayed entity task
runEntityTaskTimer(Entity, Runnable, start, period)Repeating, follows the entity across regions
runLocationTask(Runnable, Location)The region owning that location, also runLocationTaskLater
runChunkTask(Runnable, World, x, z)The region owning that chunk, also runChunkTaskLater
runAsyncTask(Runnable)Async thread
runAsyncTaskTimer(Runnable, start, period)Repeating async
runAsyncTaskLater(Runnable, delay)Delayed async, off the server thread on Paper as on Folia
teleportAsync(Player, Location)Teleport with the destination chunk loaded off the main thread
getChunkAtAsync(World, x, z)Load a chunk without blocking
cancelTask(Object)Cancel a task handle

The state of an entity — setAware, remove, effects — must be changed on the thread of its own region: runEntityTask(entity, ...), not runGlobalTask.

Since XCore 2.0, runAsyncTaskLater runs off the server thread on Paper too; it used to run on it. A delayed callback must not touch players or the world directly: hand that part to runEntityTask or runGlobalTask.

On a plugin built on XCore, every task scheduled through scheduler() belongs to the plugin and stops when it is disabled. None can be scheduled from disable(): the server refuses them. Do not schedule through core().schedulerAdapter() either, or the task belongs to XCore and outlives the plugin.

GUI Framework

XCore provides a YAML-driven GUI system. Place YAML files in src/main/resources/guis/.

gui-title: "gui-title-key"        # Lang key for inventory title
rows: 6
slots: [0,1,2,...,44]             # Slots for paginated content
slots-sound: "minecraft:ui.button.click"

items:
  BackPage:
    slot: 48
    material: ARROW
    target-title: "previous-title"
    target-lore: "previous-lore"
    target-button-on: "previous-button-on"
    target-button-off: "previous-button-off"
    permission: "myaddon.gui.navigate"
    sound: "minecraft:ui.button.click"
    custom_model_data_value: 0
    item_model_key: "my_pack:my_item"
    actions:
      left:
        - "command:mycommand"
      right:
        - "message:<green>Hello!"

GuiUtils Methods

MethodDescription
createItem(Material, Component, List<Component>)Create item with name, lore, all ItemFlags
createItemFromDef(GuiItem, Component, List<Component>)Create from YAML definition (handles heads, model data)
updateGuiItem(Inventory, slot, Component, List<Component>)Update existing item's name/lore in-place
buildNavLore(LangNamespace, loreKey, offKey, onKey, check, ...)Build nav button lore with blink state
playSound(Player, String)Play sound from namespaced key
handleCommonFeatures(Player, slot, click, def)Sound, configured actions and permission of the clicked item, in one call
blinkBarItem(BlinkCache, lang, itemDef, on, viewer, ...)Render a bar button and cache both of its faces

Since 2.1 a click on an empty slot makes no sound: a hole in a page, or a button the page does not show (no "previous" on the first page). slots-sound is the sound of the page's entries, so an item of the file without a sound of its own, a border, stays silent too.

Paginated screens

PagedGui covers what a list screen always needs: page maths, the bar at slots 48 / 49 / 50, the blink task and its cancellation, and click routing. XCore listens for these screens itself, so nothing has to be registered.

public class WarpGui extends PagedGui<Warp> {

    public WarpGui(MyAddon addon) {
        super(addon.scheduler(), addon.guiUtils(), addon.lang(),
              addon.guiRegistry().get("warps"));
    }

    protected List<Warp> items(Player viewer) { return manager.warps(); }

    protected ItemStack render(Warp warp, Player viewer, boolean blinkOn) {
        return guiUtils().createItemFromDef(itemDef, title(warp), lore(warp), viewer);
    }

    protected void onItemClick(Warp warp, Player viewer, ClickType click) {
        manager.teleport(viewer, warp);
    }
}

items() runs off the server thread, on every open and every page change, so reading the database in it is the expected thing to do.

Entries are drawn once per page. itemsBlink() returns true for a list whose entries have two faces; they then go through the blink cache, which is dropped every itemCacheTicks() so a remaining time in a lore still moves.

A list too large to hold in memory — every account a server has ever seen, for one — pages in the database instead: override totalItems(viewer) with the count and loadPage(viewer, page, perPage) with that one page. items() is then never called.

A screen whose entries each have a place of their own, a shop laid out by hand, overrides pageCount(viewer) with the number of pages, loadPage(viewer, page, perPage) with the entries of the page asked for, and slotOf(entry, index) with the slot each one sits in: -1 leaves an entry out, and of two entries on one slot the later is left out. A click is routed by its slot, and entryAt(slot) gives the entry drawn there. All three since 2.1.

Never modify the ItemStack returned by inv.getItem(slot) — it is a live mirror of what the server is holding. Build a new one, or use updateGuiItem, which clones it for you.